本文使用的數(shù)據(jù)類(lèi)型是數(shù)值型,每一個(gè)樣本6個(gè)特征表示,所用的數(shù)據(jù)如圖所示:
圖中A,B,C,D,E,F列表示六個(gè)特征,G表示樣本標(biāo)簽。每一行數(shù)據(jù)即為一個(gè)樣本的六個(gè)特征和標(biāo)簽。
實(shí)現(xiàn)Bagging算法的代碼如下:
from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.preprocessing import StandardScaler import csv from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report data=[] traffic_feature=[] traffic_target=[] csv_file = csv.reader(open('packSize_all.csv')) for content in csv_file: content=list(map(float,content)) if len(content)!=0: data.append(content) traffic_feature.append(content[0:6])//存放數(shù)據(jù)集的特征 traffic_target.append(content[-1])//存放數(shù)據(jù)集的標(biāo)簽 print('data=',data) print('traffic_feature=',traffic_feature) print('traffic_target=',traffic_target) scaler = StandardScaler() # 標(biāo)準(zhǔn)化轉(zhuǎn)換 scaler.fit(traffic_feature) # 訓(xùn)練標(biāo)準(zhǔn)化對(duì)象 traffic_feature= scaler.transform(traffic_feature) # 轉(zhuǎn)換數(shù)據(jù)集 feature_train, feature_test, target_train, target_test = train_test_split(traffic_feature, traffic_target, test_size=0.3,random_state=0) tree=DecisionTreeClassifier(criterion='entropy', max_depth=None) # n_estimators=500:生成500個(gè)決策樹(shù) clf = BaggingClassifier(base_estimator=tree, n_estimators=500, max_samples=1.0, max_features=1.0, bootstrap=True, bootstrap_features=False, n_jobs=1, random_state=1) clf.fit(feature_train,target_train) predict_results=clf.predict(feature_test) print(accuracy_score(predict_results, target_test)) conf_mat = confusion_matrix(target_test, predict_results) print(conf_mat) print(classification_report(target_test, predict_results))
運(yùn)行結(jié)果如圖所示:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
