码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-02 10:35:02      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:dict   hyper   distance   out   sel   training   port   ted   rate   

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

标签:dict   hyper   distance   out   sel   training   port   ted   rate   

原文地址:https://www.cnblogs.com/sherrydatascience/p/10206790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!