import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_extraction import DictVectorizer
def decide_play():
df = pd.read_csv(‘dtree.csv’)
dict_train = df.loc[:,[‘Outlook’,‘Temperatur’,‘Humidity’,‘Windy’]].to_dict(orient=‘record’)
#如果pandas从DataFrame取出一列数据,该数据类型会变成Series
dict_target = pd.DataFrame(df[‘Play’],columns=[‘Play’]).to_dict(orient=‘record’)
print(dict_target)
#训练数据字典向量化
dv_train = DictVectorizer(sparse=False)
x_train = dv_train.fit_transform(dict_train)
#目标数据字典向量化
dv_target = DictVectorizer(sparse=False)
y_target = dv_target.fit_transform(dict_target)
#创建训练模型并训练
d_tree = DecisionTreeClassifier()
d_tree.fit(x_train,y_target)
data_predict = {
'Humidity':85,
'Outlook':'sunny',
'Temperatur':85,
'Windy':False
}
x_data = dv_train.transform(data_predict)
print(dv_target.inverse_transform(d_tree.predict(x_data)))
if name == ‘main’:
decide_play()