Comparison supervised models
To compare the performance of various algorithms on the load_iris dataset, we first need to import the necessary libraries and load the dataset. The load_iris dataset is available in scikit-learn, so make sure you have it installed. Let's proceed with the comparison:
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.linear_model import LinearRegression, Ridge, SGDClassifier, Perceptron
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
# Load the iris dataset
data = load_iris()
X, y = data.data, data.target
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale the features (not required for all algorithms, but helps some)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Initialize the classifiers
classifiers = {
"Decision Tree": DecisionTreeClassifier(),
"Random Forest": RandomForestClassifier(),
"Gaussian Process": GaussianProcessClassifier(),
"Linear Regression": LinearRegression(),
"Ridge Regression": Ridge(),
"Stochastic Gradient Descent": SGDClassifier(),
"Perceptron": Perceptron(),
"Naive Bayes": GaussianNB(),
"Support Vector Machine": SVC(),
}
# Train and evaluate each classifier
results = {}
for name, clf in classifiers.items():
clf.fit(X_train, y_train)
y_pred = np.round(clf.predict(X_test), 0)
print(y_test)
print(y_pred)
accuracy = accuracy_score(y_test, y_pred)
results[name] = accuracy
# Sort results in descending order of accuracy
sorted_results = {k: v for k, v in sorted(results.items(), key=lambda item: item[1], reverse=True)}
# Display the results
df = pd.DataFrame.from_dict(sorted_results, orient="index", columns=["Accuracy"])
print(df)