python3 學習使用隨機森林分類器 梯度提升決策樹分類 的api,並將他們和單一決策樹預測結果做出對比
附上我的git,歡迎大家來參考我其他分類器的代碼: https://github.com/linyi0604/MachineLearning
1 import pandas as pd 2 from sklearn.cross_validation import train_test_split 3 from sklearn.feature_extraction import DictVectorizer 4 from sklearn.tree import DecisionTreeClassifier 5 from sklearn.metrics import classification_report 6 from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier 7 8 ''' 9 集成分類器: 10 綜合考量多個分類器的預測結果做出考量。 11 這種綜合考量大體上分兩種: 12 1 搭建多個獨立的分類模型,然后通過投票的方式 比如 隨機森林分類器 13 隨機森林在訓練數據上同時搭建多棵決策樹,這些決策樹在構建的時候會放棄唯一算法,隨機選取特征 14 2 按照一定次序搭建多個分類模型, 15 他們之間存在依賴關系,每一個后續模型的加入都需要現有模型的綜合性能貢獻, 16 從多個較弱的分類器搭建出一個較為強大的分類器,比如梯度提升決策樹 17 提督森林決策樹在建立的時候盡可能降低成體在擬合數據上的誤差。 18 19 下面將對比 單一決策樹 隨機森林 梯度提升決策樹 的預測情況 20 21 ''' 22 23 ''' 24 1 准備數據 25 ''' 26 # 讀取泰坦尼克乘客數據,已經從互聯網下載到本地 27 titanic = pd.read_csv("./data/titanic/titanic.txt") 28 # 觀察數據發現有缺失現象 29 # print(titanic.head()) 30 31 # 提取關鍵特征,sex, age, pclass都很有可能影響是否幸免 32 x = titanic[['pclass', 'age', 'sex']] 33 y = titanic['survived'] 34 # 查看當前選擇的特征 35 # print(x.info()) 36 ''' 37 <class 'pandas.core.frame.DataFrame'> 38 RangeIndex: 1313 entries, 0 to 1312 39 Data columns (total 3 columns): 40 pclass 1313 non-null object 41 age 633 non-null float64 42 sex 1313 non-null object 43 dtypes: float64(1), object(2) 44 memory usage: 30.9+ KB 45 None 46 ''' 47 # age數據列 只有633個,對於空缺的 采用平均數或者中位數進行補充 希望對模型影響小 48 x['age'].fillna(x['age'].mean(), inplace=True) 49 50 ''' 51 2 數據分割 52 ''' 53 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=33) 54 # 使用特征轉換器進行特征抽取 55 vec = DictVectorizer() 56 # 類別型的數據會抽離出來 數據型的會保持不變 57 x_train = vec.fit_transform(x_train.to_dict(orient="record")) 58 # print(vec.feature_names_) # ['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male'] 59 x_test = vec.transform(x_test.to_dict(orient="record")) 60 61 ''' 62 3.1 單一決策樹 訓練模型 進行預測 63 ''' 64 # 初始化決策樹分類器 65 dtc = DecisionTreeClassifier() 66 # 訓練 67 dtc.fit(x_train, y_train) 68 # 預測 保存結果 69 dtc_y_predict = dtc.predict(x_test) 70 71 ''' 72 3.2 使用隨機森林 訓練模型 進行預測 73 ''' 74 # 初始化隨機森林分類器 75 rfc = RandomForestClassifier() 76 # 訓練 77 rfc.fit(x_train, y_train) 78 # 預測 79 rfc_y_predict = rfc.predict(x_test) 80 81 ''' 82 3.3 使用梯度提升決策樹進行模型訓練和預測 83 ''' 84 # 初始化分類器 85 gbc = GradientBoostingClassifier() 86 # 訓練 87 gbc.fit(x_train, y_train) 88 # 預測 89 gbc_y_predict = gbc.predict(x_test) 90 91 92 ''' 93 4 模型評估 94 ''' 95 print("單一決策樹准確度:", dtc.score(x_test, y_test)) 96 print("其他指標:\n", classification_report(dtc_y_predict, y_test, target_names=['died', 'survived'])) 97 98 print("隨機森林准確度:", rfc.score(x_test, y_test)) 99 print("其他指標:\n", classification_report(rfc_y_predict, y_test, target_names=['died', 'survived'])) 100 101 print("梯度提升決策樹准確度:", gbc.score(x_test, y_test)) 102 print("其他指標:\n", classification_report(gbc_y_predict, y_test, target_names=['died', 'survived'])) 103 104 ''' 105 單一決策樹准確度: 0.7811550151975684 106 其他指標: 107 precision recall f1-score support 108 109 died 0.91 0.78 0.84 236 110 survived 0.58 0.80 0.67 93 111 112 avg / total 0.81 0.78 0.79 329 113 114 隨機森林准確度: 0.78419452887538 115 其他指標: 116 precision recall f1-score support 117 118 died 0.91 0.78 0.84 237 119 survived 0.58 0.80 0.68 92 120 121 avg / total 0.82 0.78 0.79 329 122 123 梯度提升決策樹准確度: 0.790273556231003 124 其他指標: 125 precision recall f1-score support 126 127 died 0.92 0.78 0.84 239 128 survived 0.58 0.82 0.68 90 129 130 avg / total 0.83 0.79 0.80 329 131 132 '''