Python3 決策樹,python3決策樹

來源:互聯網
上載者:User

Python3 決策樹,python3決策樹

# -*- coding: utf-8 -*-
"""
Created on Fri Dec 29 10:18:04 2017

@author: markli
"""
from sklearn.feature_extraction import DictVectorizer;
from sklearn import preprocessing;
from sklearn import tree;
from sklearn.externals.six import StringIO;
from sklearn.externals import joblib;
import csv;
import sys;

sys.path.append('../');
filepath = 'decisiontree.csv';
f = open(filepath,'r');
reader = csv.reader(f);
header = next(reader); #讀取表頭
print("表頭為 %s" % header);

feature_list = [];
label_list = [];
for row in reader:
label_list.append(row[len(row)-1]);
rowdic = {};
for i in range(1,len(row)-1):
rowdic[header[i]] = row[i];
feature_list.append(rowdic);

print("特徵值為 %s" % feature_list);

dv = DictVectorizer();
dummX = dv.fit_transform(feature_list).toarray();
print("特徵提取值矩陣為 %s" % str(dummX));

#目標值特徵化
lb = preprocessing.LabelBinarizer();
dummY = lb.fit_transform(label_list);
print("目標特徵化值為 %s" % str(dummY));

clf = tree.DecisionTreeClassifier(criterion='entropy');
clf = clf.fit(dummX,dummY);
print("樹 %s" % str(clf));

#儲存模型
with open('dicisiontreeModel.dot','w') as f:
f = tree.export_graphviz(clf,feature_names=dv.get_feature_names(),out_file=f);
joblib.dump(clf,'dicisionTree_entropyModel.dot');


#讀模數型 預測
'''
x = np.array([0,1,0,0,0,1,0,1,1,0]); #測試值
print(x.reshape((1,10)));
#sys.path.append('F:\\Python\\ML');
#f = open('F:\\Python\\ML\\dicisionTree_entropyModel.dot');

decisiontree.csv 檔案格式
clf = joblib.load('F:\\Python\\ML\\dicisionTree_entropyModel.dot');
y = clf.predict(x.reshape((1,10))); #預測結果
print(y);
'''

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.