[Machine Learning with Python] Cross Validation and Grid Search: An Example of KNN

Posted Sherrrry

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Machine Learning with Python] Cross Validation and Grid Search: An Example of KNN相关的知识,希望对你有一定的参考价值。

Train model:

from sklearn.model_selection import GridSearchCV

param_grid = [
    # try 6 (3×2) combinations of hyperparameters
    {n_neighbors: [3, 5, 7], weights: [uniform,distance]}
  ]

knn_clf = KNeighborsClassifier()
# train across 3 folds, that‘s a total of 6*3=18 rounds of training 
grid_search = GridSearchCV(knn_clf, param_grid, cv=3,
                           scoring=accuracy, return_train_score=True, n_jobs=-1)
grid_search.fit(X_train, y_train)

Show parameters of best model:

grid_search.best_params_

Show the score of train set:

grid_search.best_score_

Fit on test set:

y_pred = grid_search.predict(X_test)

Show the score of test set:

from sklearn.metrics import accuracy_score
accuracy_score(y_test, y_pred)

More about GridSearchCV: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html

以上是关于[Machine Learning with Python] Cross Validation and Grid Search: An Example of KNN的主要内容,如果未能解决你的问题,请参考以下文章

Machine Learning with Oracle Database Advanced Analytics

An introduction to machine learning with scikit-learn

Building Machine Learning Systems with Python 2

A Exam:Machine Learning with Python

Machine Learning with Matminer(附代码)

Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow ——Chapter 1 Machine Learning Land