1.代碼
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # @File : 泰坦尼克號.py 4 # @Author: 趙路倉 5 # @Date : 2020/4/4 6 # @Desc : 7 # @Contact : 398333404@qq.com 8 9 import pandas as pd 10 from sklearn.model_selection import train_test_split, GridSearchCV 11 from sklearn.tree import DecisionTreeClassifier, export_graphviz 12 from sklearn.feature_extraction import DictVectorizer 13 from sklearn.ensemble import RandomForestClassifier 14 15 16 17 def titanic(): 18 # 導入數據 19 titanic = pd.read_csv("titanic.txt") 20 # print(titanic) 21 22 # 篩選特征值和目標值 23 x = titanic[["pclass", "age", "sex"]] 24 y = titanic["survived"] 25 # print(x) 26 # print(y) 27 28 # 數據處理 29 # 1.缺失值處理 30 x["age"].fillna(x["age"].mean(), inplace=True) 31 # print(x["age"]) 32 # 2.轉換成字典 33 x = x.to_dict(orient="records") 34 # 3.數據集划分 35 x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=21) 36 37 # 4.字典特征抽取 38 transfer = DictVectorizer() 39 x_train = transfer.fit_transform(x_train) 40 x_test = transfer.transform(x_test) 41 print(x_train.toarray()) 42 print(transfer.get_feature_names()) 43 # 5.決策樹預估器 44 estimator = DecisionTreeClassifier(criterion="entropy") 45 estimator.fit(x_train, y_train) 46 47 # 6.模型評估 48 # 方法一:直接對比真實數據和預測值 49 y_predit = estimator.predict(x_test) 50 51 print("y_predit:\n", y_predit) 52 print("對比真實值和預測值:\n", y_test == y_predit) 53 54 # 方法2:計算准確率 55 score = estimator.score(x_test, y_test) 56 print("准確率為:\n", score) 57 58 # 預測 59 pre=transfer.transform([{'pclass': '1st', 'age': 48.0, 'sex': 'male'}]) 60 prediction=estimator.predict(pre) 61 print(prediction) 62 # 可視化決策樹 63 # 生成文件 64 dot_data = export_graphviz(estimator, out_file="titanic.dot") 65 66 67 def titanic_forest(): 68 # 導入數據 69 titanic = pd.read_csv("titanic.txt") 70 # print(titanic) 71 72 # 篩選特征值和目標值 73 x = titanic[["pclass", "age", "sex"]] 74 y = titanic["survived"] 75 76 # 數據處理 77 # 1.缺失值處理 78 x["age"].fillna(x["age"].mean(), inplace=True) 79 # print(x["age"]) 80 # 2.轉換成字典 81 x = x.to_dict(orient="records") 82 # 3.數據集划分 83 x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=21) 84 85 # 4.字典特征抽取 86 transfer = DictVectorizer() 87 x_train = transfer.fit_transform(x_train) 88 x_test = transfer.transform(x_test) 89 90 estimator=RandomForestClassifier() 91 # 加入網格搜索與交叉驗證 92 param_dict = { 93 "n_estimators": [120,200,300,500,800,1200],"max_depth":[5,8,15,25,30] 94 } 95 estimator = GridSearchCV(estimator, param_grid=param_dict, cv=3) 96 estimator.fit(x_train, y_train) 97 98 # 5.模型評估 99 # 方法一:直接對比真實數據和預測值 100 y_predit = estimator.predict(x_test) 101 print("y_predit:\n", y_predit) 102 print("對比真實值和預測值:\n", y_test == y_predit) 103 104 # 方法2:計算准確率 105 score = estimator.score(x_test, y_test) 106 print("准確率為:\n", score) 107 108 """ 109 最佳參數:best_params_ 110 最佳結果:best_score_ 111 最佳估計器:best_estimator_ 112 交叉驗證結果:cv_results_ 113 """ 114 print("最佳參數:\n", estimator.best_params_) 115 print("最佳結果:\n", estimator.best_score_) 116 print("最佳估計器:\n", estimator.best_estimator_) 117 print("交叉驗證結果:\n", estimator.cv_results_) 118 return None 119 120 121 if __name__ == "__main__": 122 titanic() 123 titanic_forest()
2.解釋
第一個函數 titanic() 根據游客數據
1.篩選有效數據
2.缺失值處理
3.轉換為字典
5.划分數據集
6.轉換為特征值
7.訓練模型
8.模型評估
9.預測
形成模型並評估,可以進行簡單的預測分類
第二個函數 titanic_forest()
隨機森林找到最優方案/模型,確定最優參數等等