1. 程式人生 > >模型訓練與優化

模型訓練與優化

特征 cor 搜索 grid precision from 檢驗 結果 name

數據集拆分

from sklearn.model_selection import train_test_split

# 分割數據集到訓練集和測試集
# lb.data 特征值
# lb.target 目標值
# test_size=0.25  75%數據訓練    25%數據測試
# 返回  訓練特征值, 測試特征值, 訓練目標值, 測試目標值 
x_train, x_test, y_train, y_test = train_test_split(lb.data, lb.target, test_size=0.25)

交叉驗證

from sklearn.model_selection import cross_val_score
clf = svm.SVC(kernel=‘linear‘, C=1)
# cif 估計器對象
# iris.data:特征數據
# iris.target:目標值
# cv=5   5次交叉驗證
scores = cross_val_score(clf, iris.data, iris.target, cv=5)
print(scores)

# 結果                              
array([ 0.96...,  1\.  ...,  0.96...,  0.96...,  1\.        ])

網格搜索

通常情況下,有很多參數是需要手動指定的(如k-近鄰算法中的K值), 這種叫超參數。但是手動過程繁雜,所以需要對模型預設幾種超參數組 合。每組超參數都采用交叉驗證來進行評估。最後選出最優參數組合建 立模型。

技術分享圖片

技術分享圖片

from sklearn.model_selection import GridSearchCV

param = {"n_estimators": [120, 200, 300, 500, 800, 1200], "max_depth": [5, 8, 15, 25, 30]}

# 網格搜索與交叉驗證
# rf:估計器對象
# cv=2:指定幾折交叉驗證
gc = GridSearchCV(rf, param_grid=param, cv=2)

gc.fit(x_train, y_train)

print("準確率:", gc.score(x_test, y_test))

print("查看選擇的參數模型:", gc.best_params_) 

精確率(Precision)與召回率(Recall)

技術分享圖片

技術分享圖片

from sklearn.metrics import classification_report
# 返回召回率
# labels:目標值
# target_names:目標值對應的名稱
classification_report(y_test, y_predict, labels=[2, 4], target_names=["良性", "惡性"])

  

模型訓練與優化