How To Train Multiple Model In One Time With Sklearn


Here is the code to show you how to check accuracy of multiple models in a pipeline.

from sklearn.model_selection import KFold
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score

data= load_iris()
Y_train = data.target
X_train = data.data[:, :2]
# Add machine learning model to list
models = []
models.append(("KNC",KNeighborsClassifier()))
models.append(("SVM",SVC()))
models.append(("DTC",DecisionTreeClassifier()))

# train multiple classifier with Kfold
results = []
names = []
for name,model in models:
    kfold = KFold(n_splits=15, random_state=42)
    result = cross_val_score(model,X_train,Y_train, cv = kfold, scoring = "accuracy")
    names.append(name)
    results.append(result)

# show the accuracy of the models
for i in range(len(names)):
    print(names[i],results[i].mean())

What’s Kfold in the code? Please check this post: The Easiest Introduction To Cross Validation.


Welcome to share or comment on this post:

Table of Contents