技术大数据时代各种涨姿势python

【machine learning】- 决策树(DTs)之Pyt

2015-05-31  本文已影响3664人  Jason_Yuan

这学期AI课的最后一次assignment,老师要让大家实践一下decision tree,而且“You can use any existing machine learning tool for this task”,所以就有了我下面这篇文章,不足之处,望指正,共勉!


目录###

1. 环境搭建
2. 什么是Decision Tree?
3. 具体Python实现,附代码


1. 环境搭建

1.1 用Python实现机器学习的基础环境搭建, click here.

1.2 安装 pyparsing (1.5.7) 和 pydot

注:以下针对于 Mac OS 并且使用 Python2.7

    $ 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
    $ 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语言脚本描述的图形。

    $ pip install xlrd

2. 什么是Decision Tree?

决策树(Decision Tree)是基于符号的监督学习方法中的一种。更多相关知识,可以看我另外一篇文章


3. 具体Python实现

import numpy as np
import pandas as pd
from sklearn import tree
from sklearn.feature_extraction import DictVectorizer
# 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])
 # 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
# 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')
vec = DictVectorizer()
X_train = vec.fit_transform(dict_X_train).toarray()
X_test = vec.fit_transform(dict_X_test).toarray()
 clf = tree.DecisionTreeClassifier()
 clf = clf.fit(X_train,y_train)

 score = clf.score(X_test,y_test)
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 格式)


结语

上一篇 下一篇

猜你喜欢

热点阅读