通過使用sklearn決策樹,簡單練習案例分析


# 根據電影中的類型,票房,產地,預測去不去看電影
import csv
from sklearn.feature_extraction import DictVectorizer
from sklearn import preprocessing

from sklearn import tree

# 導入數據集,
film_data = open('film.csv', 'rt')
reader = csv.reader(film_data)

# 表頭數據
headers = next(reader)
# 打印一下數據集的頭部
print(headers)

# 預測數據列表
feature_list = []
# 結果集列表
result_list = []
# 便利打印數據,組裝成新的數據
for row in reader:
    # print(row[1:-1])
    # print(headers[1:-1])
    result_list.append(row[-1])
    feature_list.append(dict(zip(headers[1:-1], row[1:-1])))
print(result_list, feature_list)
# ['yes', 'yes', 'yes', 'yes', 'yes', 'yes', 'no', 'no']
# [{'type': 'anime', 'country': 'Janan', 'gross': 'low'}, {'type': 'science', 'country': 'America', 'gross': 'low'}, {'type': 'anime', 'country': 'America', 'gross': 'low'}, {'type': 'action', 'country': 'America', 'gross': 'high'}, {'type': 'action', 'country': 'China', 'gross': 'high'}, {'type': 'anime', 'country': 'China', 'gross': 'low'}, {'type': 'science', 'country': 'France', 'gross': 'low'}, {'type': 'action', 'country': 'China', 'gross': 'low'}]

# 調用sklearn 自帶的特徵提取類
vec = DictVectorizer()
# 傳入訓練數據模型
dummyX = vec.fit_transform(feature_list).toarray()
"生成的這個二維數組 是根據傳入數據特徵值進行分類的,如果特徵值比比較多的話,二維數組會比較大,此二維數組前四位是代表國家,中間兩位票房,最後三位數據代表電影類型,測試數據也是一樣"
"""
[[0. 0. 0. 1. 0. 1. 0. 1. 0.]
 [1. 0. 0. 0. 0. 1. 0. 0. 1.]
 [1. 0. 0. 0. 0. 1. 0. 1. 0.]
 [1. 0. 0. 0. 1. 0. 1. 0. 0.]
 [0. 1. 0. 0. 1. 0. 1. 0. 0.]
 [0. 1. 0. 0. 0. 1. 0. 1. 0.]
 [0. 0. 1. 0. 0. 1. 0. 0. 1.]
 [0. 1. 0. 0. 0. 1. 1. 0. 0.]]
"""
#標籤二值化
dummyY = preprocessing.LabelBinarizer().fit_transform(result_list)
"""
[[1]
 [1]
 [1]
 [1]
 [1]
 [1]
 [0]
 [0]]
"""
print(dummyX)
print(dummyY)
# 調用sklearn 的 決策樹 訓練模型
clf = tree.DecisionTreeClassifier(criterion='entropy', random_state=0)
clf = clf.fit(dummyX, dummyY)
# print('clf:' + str(clf))



A = ([[0, 0, 0, 1, 0, 1, 0, 1, 0]])
B = ([[0, 0, 1, 0, 0, 1, 0, 1, 0]])
C = ([[1, 0, 0, 0, 1, 0, 1, 0, 0]])
# 傳入數據 驗證訓練模型
predict_result = clf.predict(A)
print('預測結果' + str(predict_result))



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章