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

本文通过使用GridSearchCV进行KNN模型的超参数调优,探讨了如何选择最佳的邻居数量和权重类型,以提高模型在训练集和测试集上的准确性。详细介绍了GridSearchCV的使用方法和评估指标。

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

转载于:https://www.cnblogs.com/sherrydatascience/p/10206790.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值