這學期AI課的最后一次assignment,老師要讓大家實踐一下decision tree,而且“You can use any existing machine learning tool for this task”岩臣,所以就有了我下面這篇文章亲善,不足之處,望指正芥吟,共勉!
目錄###
1. 環(huán)境搭建
2. 什么是Decision Tree专甩?
3. 具體Python實現(xiàn)钟鸵,附代碼
1. 環(huán)境搭建
1.1 用Python實現(xiàn)機器學習的基礎(chǔ)環(huán)境搭建, click here.
1.2 安裝 pyparsing (1.5.7) 和 pydot
注:以下針對于 Mac OS 并且使用 Python2.7
- 如果已經(jīng)安裝了pyparsing (2.x.x),操作如下:
$ pip uninstalled pyparsing
$ pip install -Iv https://pypi.python.org/packages/source/p/pyparsing/pyparsing-1.5.7.tar.gz#md5=9be0fcdcc595199c646ab317c1d9a709
$ pip install pydot
- 如果沒有安裝過pyparsing任何版本配深,操作如下:
$ pip install -Iv https://pypi.python.org/packages/source/p/pyparsing/pyparsing-1.5.7.tar.gz#md5=9be0fcdcc595199c646ab317c1d9a709
$ pip install pydot
1.3 安裝 GraphViz
graphviz
Graphviz (Graph Visualization Software) 是一個由AT&T實驗室啟動的開源工具包携添,用于繪制DOT語言腳本描述的圖形。
- GraphViz不能通過pip安裝篓叶。 所以烈掠,下載對于Mac的正確版本(graphviz-2.36.0.pkg)之后,自行安裝缸托。
- 你可能還需要安裝xlrd
$ pip install xlrd
- GraphViz 官網(wǎng)
2. 什么是Decision Tree左敌?
決策樹(Decision Tree)是基于符號的監(jiān)督學習方法中的一種。更多相關(guān)知識俐镐,可以看我另外一篇文章矫限。
3. 具體Python實現(xiàn)
- 導入library
import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.feature_extraction import DictVectorizer
- 讀取數(shù)據(jù)
- 使用pandas讀取Excel文件,當然pandas還支持多種文件格式的讀寫佩抹,比如:text, sql, json, csv ......
- 使用pd.read_excel() 讀取后默認生成 pandas.DataFrame
# read data from excel file as DataFrame
raw_train_data = pd.read_excel("/Users/boyuan/Desktop/TrainingData.xlsx", parse_cols=[1,2,3,4,5,6,7,8,9,10,11])
raw_test_data = pd.read_excel("/Users/boyuan/Desktop/TestingData.xlsx", parse_cols=[1,2,3,4,5,6,7,8,9,10,11])
- 清洗數(shù)據(jù)
# If the data has missing values, they will become NaNs in the resulting Numpy arrays.
# The vectorizer will create additional column <feature>=NA for each feature with NAs
raw_train_data = raw_train_data.fillna("NA")
raw_test_data = raw_test_data.fillna("NA")
exc_cols = [u'adjGross']
cols = [c for c in raw_train_data.columns if c not in exc_cols]
X_train = raw_train_data.ix[:,cols]
y_train = raw_train_data['adjGross'].values
X_test = raw_test_data.ix[:,cols]
y_test = raw_test_data['adjGross'].values
- 使用pandas to_dict() 將DataFrame轉(zhuǎn)化成Dict
# Convert DataFrame to dict See more: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_dict.html#pandas.DataFrame.to_dict
dict_X_train = X_train.to_dict(orient='records')
dict_X_test = X_test.to_dict(orient='records')
- Encoding categorical features
- 使用Scikit-learn中的DictVectorizer
- DictVectorizer中使用的是OneHotEncoder來實現(xiàn)
- 對于Label可以使用LabelEncoder
vec = DictVectorizer()
X_train = vec.fit_transform(dict_X_train).toarray()
X_test = vec.fit_transform(dict_X_test).toarray()
- 最后叼风,把train data喂給fit()函數(shù),用score()函數(shù)檢驗?zāi)P驮趖est data上的表現(xiàn)棍苹!
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train,y_train)
score = clf.score(X_test,y_test)
- 當然也可以把tree導出到dot文件中无宿,使用GraphViz畫圖
from sklearn.externals.six import StringIO
with open("文件名稱.dot", 'w') as f:
f = tree.export_graphviz(clf, out_file=f, feature_names= vec.get_feature_names())
在CLI上輸入如下命令:
$ dot -Tps tree.dot -o tree.ps
(PostScript 格式)
$ dot -Tpng tree.dot -o tree.png
(PNG 格式)
-
最后附上兩張tree圖,分別是沒有設(shè)置max_depth以及設(shè)置max_depth=8的情形
tree_with_8_depth
tree_without_limit_depth 網(wǎng)上有很多流行的數(shù)據(jù)集枢里,比如簡書上的《最流行的4個機器學習數(shù)據(jù)集》
我使用的是UCI上一個判斷年工資是否大于50k的數(shù)據(jù)集
結(jié)語
- 這是第一次使用Python進行data mining孽鸡,學習使用Python斷斷續(xù)續(xù)也有大半年蹂午,從寫簡單的算法課作業(yè),后來寫爬蟲彬碱,接觸Flask寫網(wǎng)站豆胸, 不斷體會到“人生苦短,我用Python”巷疼。這當然基于Python非常完善的代碼庫晚胡。
- 沒有一種語言是萬能的,Python當然也不是皮迟,但不得不說在某些領(lǐng)域Python確實作為一種高級語言搬泥,可以讓你更專注你核心要做的事情, 而非語言本身伏尼。