對sklearn的使用之數(shù)據(jù)集的拆分與訓練詳解(python3.6)
更新時間:2018年12月14日 14:48:03 作者:子耶
今天小編就為大家分享一篇對sklearn的使用之數(shù)據(jù)集的拆分與訓練詳解(python3.6),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
研修課上講了兩個例子,融合一下。
主要演示大致的過程:
導入->拆分->訓練->模型報告
以及幾個重要問題:
①標簽二值化
②網(wǎng)格搜索法調(diào)參
③k折交叉驗證
④增加噪聲特征(之前涉及)
from sklearn import datasets
#從cross_validation導入會出現(xiàn)warning,說已棄用
from sklearn.model_selection import train-test_split
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.svm import SVC
import sklearn.exceptioins
#導入鳶尾花數(shù)據(jù)集
iris = datasets.load_iris()
#將數(shù)據(jù)集拆分為訓練集和測試集各一半
#其中X為數(shù)據(jù)特征(花萼、花瓣的高度寬度),為150*4的矩陣
#Y為鳶尾花種類(0, 1, 2三種),為150*1矩陣
#如果使用標簽二值化, 將0, 1, 2表示為100 010 001
#使用y.label_binarize(y, classes[0, 1, 2]),變?yōu)?50*3矩陣
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.5, random_state=0)
#set the parameters by cross_validation
turn_parameters = [{'kernel' : ['rbf', 'gamma' : [1e-3, 1e - 4, 'C':[1,10,100,1000]},
{'kernel':['linear'], 'C':[1,10,100,1000]}
]
#clf分離器
#使用網(wǎng)格搜索法調(diào)超參數(shù)
#訓練集做5折交叉驗證
clf = GridSearchCV(SVC(C=1), turned_parameters, cv=5, scoring='%s_weighted' % score)
#用前一半train數(shù)據(jù)再做5折交叉驗證
#因為之前的train_test_split已經(jīng)分割為2份了
#fit-擬合
clf.fit(X_train, y_train)
#超參數(shù)
print(clf.best_params_)
#得分
for params, mean_score, scores in clf.gird_scores_:
print("%.3f (+/-%.0.03f) for %r" % (mean_score, scores.std()*1.96,params))
#分類報告
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
以上這篇對sklearn的使用之數(shù)據(jù)集的拆分與訓練詳解(python3.6)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決TypeError: Object of type xxx is&
這篇文章主要介紹了解決TypeError: Object of type xxx is not JSON serializable錯誤問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

