赞
踩




1、我们用A1、A2、A3、A4分别表示年龄、有工作、有自己的房子和信贷四个特征。
2、此时:g(D,A1) = H(D) - H(D|A1)。
3、 此时:H(D) = - (9/15)log(9/15)-(6/15)log(6/15)。
4、此时:H(D|A1) = - [(5/15)H(D1)+(5/15)H(D2)+(5/15)H(D3)] ps:D1、D2、D3 分别指的是:青年、中年、老年;(5/15)指的是:青年、中年、老年在特征中所占数量比。。
5、此时:H(D1) = - (2/5)log(2/5) - (3/5)log(3/5) ps:2/5 指的是青年在目标值中不同选择的所占比。
6、由此我们便可计算H(D2)、H(D3)进而求出g(D,A1),最终求出g(D,A2)、g(D,A3)、g(D,A4)从而确定最优特征。
7、通过计算,我们可以确定g(D,A3)的值最大,也就说明是否有房是四个特征的信息增益中最大的,即为最优特征,同时,也从侧面反映了,女性在择偶方面“有没有房”是第一要素。

#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # Author : rusi_ import os import pandas as pd from sklearn.tree import DecisionTreeClassifier, export_graphviz from sklearn.feature_extraction import DictVectorizer from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.ensemble import RandomForestClassifier def decision_tn(): """ 决策树预测泰坦尼克号乘客生死问题 :return: None """ tn = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt") x = tn[['pclass', 'age', 'sex']] y = tn["survived"] x["age"].fillna(x["age"].mean(), inplace=True) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25) # Feature Engineering(one hot) dict_ = DictVectorizer(sparse=False) x_train = dict_.fit_transform(x_train.to_dict(orient="records")) x_test = dict_.transform(x_test.to_dict(orient="records")) dec = DecisionTreeClassifier() dec.fit(x_train, y_train) print("预测的准确率为:\n", dec.score(x_test, y_test)) print(dict_.feature_names_) # Derive the structure of decision tree export_graphviz(dec, out_file="./obj_file/tree.dot", feature_names=dict_.get_feature_names()) return def random_forest_tn(): """ 随机森林预测泰坦尼克号乘客生死问题 :return: None """ tn = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt") x = tn[['pclass', 'age', 'sex']] y = tn["survived"] x["age"].fillna(x["age"].mean(), inplace=True) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25) # Feature Engineering(one hot) dict_ = DictVectorizer(sparse=False) x_train = dict_.fit_transform(x_train.to_dict(orient="records")) x_test = dict_.transform(x_test.to_dict(orient="records")) # Random forest rf = RandomForestClassifier() # Grid search with cross validation param = {"n_estimators": [120, 200, 300, 500, 800, 1200], "max_depth": [5, 8, 15, 25, 30]} gc = GridSearchCV(rf, param, cv=2) gc.fit(x_train, y_train) print(f"准确率:{os.linesep}", gc.score(x_test, y_test)) print(f"查看选择最优的参数模型:{os.linesep}", gc.best_params_) return if __name__ == '__main__': # 预测的准确率为: # 0.8054711246200608 # decision_tn() # 准确率:0.8328267477203647 # 查看选择最优的参数模型: # {'max_depth': 5, 'n_estimators': 300} random_forest_tn()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。