sklearn.model_selection
阿新 • • 發佈:2020-07-09
一、交叉驗證
1.from sklearn.model_selection import train_test_split
該功能可以快速將資料隨機分為訓練集和測試集
#官方示例,使用鳶尾花的資料集 import numpy as np from sklearn.datasets import load_iris from sklearn import svm #支援向量機 from sklearn.model_selection import train_test_split x,y=load_iris(return_X_y=True) x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.4,random_state=0) x_train.shape,y_train.shape clf=svm.SVC(kernel='linear',C=1).fit(x_train,y_train) clf.score(x_test,y_test)
2.from sklearn.model_selection import cross_val_score
交叉驗證的方法
#擬合模型並連續5次計算分數(每次都有不同的分割) from sklearn.model_selection import cross_val_score clf=svm.SVC(kernel='linear',C=1) scores=cross_val_score(clf,x,y,cv=5) scores # array([0.96666667, 1. , 0.96666667, 0.96666667, 1. ])
平均得分和得分估計值的95%置信區間由下式給出:
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2)) #Accuracy: 0.98 (+/- 0.03)
交叉驗證過程:
即是將資料集分為n份,n-1份為訓練集,1份為測試集,這樣迴圈計算n次,最後將n次結果求平均值
3.from sklearn.model_selection import GridSearchCV 網格搜尋
sklearn.model_selection.GridSearchCV(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch=‘2*n_jobs’, error_score=’raise’, return_train_score=’warn’)
引數:
1.estimator:可認為是模型
2.param_grid :指定引數
屬性:
1.cv_results_:交叉驗證結果
2.best_estimator_:最佳模型
3.best_score_:最佳模型的分數
4.best_params_ :最佳引數設定
5.scorer_:分數
6.利用最佳模型來進行預測:
best_model=grid.best_estimator_
predict_y=best_model.predict(Test_X)
metrics.f1_score(y, predict_y)