Scikit-Learn 机器学习笔记 -- 决策树
生活随笔
收集整理的這篇文章主要介紹了
Scikit-Learn 机器学习笔记 -- 决策树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Scikit-Learn 機器學習筆記 – 決策樹
參考文檔: handson-ml
import numpy as np# 加載鳶尾花數據集 def load_dataset():from sklearn import datasetsiris = datasets.load_iris()# print(iris)# 使用第3和第4個特征X = iris['data'][:, (2, 3)]# bool類型轉為數值型y = iris['target']return X, y, iris# 決策樹分類器 def tree_classify(X, y):from sklearn.tree import DecisionTreeClassifiertree_clf = DecisionTreeClassifier(max_depth=2)tree_clf.fit(X, y)print(tree_clf.tree_)return tree_clf# 繪制決策樹圖 def draw_tree(model, iris):from sklearn.tree import export_graphvizexport_graphviz(model,out_file="iris_tree.dot",feature_names=iris.feature_names[2:],class_names=iris.target_names,rounded=True,filled=True)# import pydotplus# dot_data = export_graphviz(model, out_file=None)# graph = pydotplus.graph_from_dot_data(dot_data)# graph.write_pdf("iris.pdf")# 預測 def tree_predict(model, sample):# 預測類別predict = model.predict(sample)# 屬于各類別的概率predict_prob = model.predict_proba(sample)print('決策樹預測類別為:', predict, '屬于各類別的概率為:', predict_prob)if __name__ == '__main__':# 加載數據集X, y, iris = load_dataset()# 創建決策樹分類器tree_clf = tree_classify(X, y)# 繪制決策樹# draw_tree(tree_clf, iris)# 預測tree_predict(tree_clf, [[5, 1.5]])
總結
以上是生活随笔為你收集整理的Scikit-Learn 机器学习笔记 -- 决策树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql中的comment用法
- 下一篇: SpringBoot怎么直接访问temp