1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
| import pandas as pd import numpy as np import matplotlib.pyplot as plt import graphviz from time import time import datetime from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import KBinsDiscretizer from sklearn.preprocessing import StandardScaler from sklearn import tree from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedKFold from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import precision_score, recall_score from sklearn.linear_model import LogisticRegression as LR from sklearn.metrics import mean_squared_error from sklearn.svm import SVC
COLUMNS1 = ['Ville_id', 'Age', 'Married', 'Number_children', 'education_level', 'total_members', 'gained_asset', 'durable_asset', 'save_asset', 'living_expenses', 'other_expenses', 'incoming_salary', 'incoming_own_farm', 'incoming_business', 'incoming_no_business', 'incoming_agricultural', 'farm_expenses', 'labor_primary', 'lasting_investment', 'no_lasting_investmen', 'depressed', 'sex_0', 'sex_1'] COLUMNS1_1 = ["sex"]
COLUMNS2 = ['Ville_id', 'Married', 'Number_children', 'education_level', 'total_members', 'incoming_salary', 'incoming_own_farm', 'incoming_business', 'incoming_no_business', 'labor_primary', 'sex_0', 'sex_1', 'depressed', 'Age', 'gained_asset', 'durable_asset', 'save_asset', 'living_expenses', 'other_expenses', 'incoming_agricultural', 'farm_expenses', 'lasting_investment', 'no_lasting_investmen'] COLUMNS2_2 = ['Age', 'gained_asset', 'durable_asset', 'save_asset', 'living_expenses', 'other_expenses', 'incoming_agricultural', 'farm_expenses', 'labor_primary', 'lasting_investment', 'no_lasting_investmen']
parameter_grid = {'max_depth': np.arange(5, 8, 1), 'max_features': np.arange(7, 10, 1)} max_depthl = [] max_featuresl = []
feature_name = ['Ville_id', 'Married', 'Number_children', 'education_level', 'total_members', 'incoming_salary', 'incoming_own_farm', 'incoming_business', 'incoming_no_business', 'labor_primary', 'sex_0', 'sex_1', 'Age', 'gained_asset', 'durable_asset', 'save_asset', 'living_expenses', 'other_expenses', 'incoming_agricultural', 'farm_expenses', 'lasting_investment', 'no_lasting_investmen']
COLUMNS3 = ['Ville_id', 'Married', 'Number_children', 'education_level', 'total_members', 'incoming_salary', 'incoming_own_farm', 'incoming_business', 'incoming_no_business', 'labor_primary', 'sex_0', 'sex_1', 'Age', 'gained_asset', 'durable_asset', 'save_asset', 'living_expenses', 'other_expenses', 'incoming_agricultural', 'farm_expenses', 'lasting_investment', 'no_lasting_investmen']
class Depression:
def __init__(self, data): self.data = data
self.i = 0 self.j = 0 self.k = 0 self.m = 0
def preprocess(self):
self.data = self.data.sort_values(by="Survey_id") self.data.loc[:, "no_lasting_investmen"] = self.data.loc[:, "no_lasting_investmen"].fillna( self.data.loc[:, "no_lasting_investmen"].median())
return self.data
def preprocessDetail(self): encode_data = self.oneHotEncode()
standard_data = self.standardData(encode_data)
discretizer_data = self.binsDiscretizer(standard_data)
return discretizer_data
def oneHotEncode(self): enc = OneHotEncoder(categories='auto').fit(self.data.iloc[:, 1:2]) result = enc.transform(self.data.iloc[:, 1:2]).toarray() print("哑变量特征的命名: %s" % enc.get_feature_names_out()) dic = {} for i in range(len(self.data)): dic[i] = i + 1 df = pd.DataFrame(result) df = df.rename(dic) new_data = pd.concat([self.data, df], axis=1) new_data.drop(COLUMNS1_1, axis=1, inplace=True) new_data.columns = COLUMNS1 depressed = new_data.pop('depressed') new_data.insert(loc=new_data.shape[1], column='depressed', value=depressed, allow_duplicates=False) return new_data
def binsDiscretizer(self, data): new_data = data.copy() result = KBinsDiscretizer(n_bins=2, encode='ordinal', strategy='uniform').fit_transform( new_data.loc[:, COLUMNS2_2]) dic = {} for i in range(len(data)): dic[i] = i + 1 df = pd.DataFrame(result) df = df.rename(dic) new_data = pd.concat([new_data, df], axis=1) new_data.drop(COLUMNS2_2, axis=1, inplace=True) new_data.columns = COLUMNS2 depressed = new_data.pop('depressed') new_data.insert(loc=new_data.shape[1], column='depressed', value=depressed, allow_duplicates=False) return new_data
def standardData(self, data): scalar = StandardScaler() new_data = data.copy() depressed = new_data.pop('depressed') new_data_frame = scalar.fit_transform(new_data) new_data = pd.DataFrame(new_data_frame, index=new_data.index, columns=new_data.columns) new_data.insert(loc=new_data.shape[1], column='depressed', value=depressed, allow_duplicates=False) return new_data
def decisionTree(self, Xtrain, Xtest, ytrain, ytest): max_depthl.clear() max_featuresl.clear() decision_tree_classifier = tree.DecisionTreeClassifier() cross_validation = StratifiedKFold(n_splits=10).get_n_splits(ytrain) gridsearch = GridSearchCV(decision_tree_classifier, param_grid=parameter_grid, cv=cross_validation) gridsearch.fit(Xtrain, ytrain) best_param = gridsearch.best_params_ max_depthl.append(best_param['max_depth']) max_featuresl.append(best_param['max_features']) print("决策树的最优参数为max_depth = %s, max_feature = %s" % (best_param['max_depth'], best_param['max_features'])) clf = tree.DecisionTreeClassifier(criterion="entropy", random_state=90, splitter="random" , max_depth=best_param['max_depth'] , max_features=best_param['max_features']) clf = clf.fit(Xtrain, ytrain) score = clf.score(Xtest, ytest) data_train_predictions = clf.predict(Xtest) lin_mse = mean_squared_error(ytest, data_train_predictions) lin_rmse = np.sqrt(lin_mse) y_train_pred = cross_val_predict(clf, Xtrain, ytrain, cv=10) precision = precision_score(ytrain, y_train_pred) recall = recall_score(ytrain, y_train_pred) print("决策树模型的均方误差(mse)为%s, 均方根误差(rmse)为%s" % (lin_mse, lin_rmse)) print("决策树模型的精度(precision)为%s, 召回率(recall)为%s" % (precision, recall)) print("决策树模型的预测精准度为%s" % score) dot_data = tree.export_graphviz(clf, feature_names=feature_name, class_names=["depressed", "undepressed"], filled=True, rounded=True) graph = graphviz.Source(dot_data) graph.view()
return score
def randomForest(self, Xtrain, Xtest, ytrain, ytest): random_forest_classifier = RandomForestClassifier() cross_validation = StratifiedKFold(n_splits=10).get_n_splits(ytrain.ravel()) gridsearch = GridSearchCV(random_forest_classifier, param_grid=parameter_grid, cv=cross_validation) gridsearch.fit(Xtrain.values.tolist(), ytrain.ravel()) best_param = gridsearch.best_params_ max_depthl.append(best_param['max_depth']) max_featuresl.append(best_param['max_features'])
plt.figure() plt.bar(range(len(max_depthl)), max_depthl, tick_label=['df', 'rf']) plt.ylabel('max_depth') plt.xlabel('type(1:df,2:rf)') plt.title('best max_depth')
self.i = self.i + 1 plt.show()
plt.figure() plt.bar(range(len(max_featuresl)), max_featuresl, tick_label=['df', 'rf']) plt.ylabel('max_featuresl') plt.xlabel('type(1:df,2:rf)') plt.title('best max_features') self.j = self.j + 1 plt.show()
print("随机森林的最优参数为max_depth = %s, max_feature = %s" % (best_param['max_depth'], best_param['max_features'])) rfc = RandomForestClassifier(n_estimators=112, random_state=90 , max_depth=best_param['max_depth'] , max_features=best_param['max_features']) rfc = rfc.fit(Xtrain.values.tolist(), ytrain.ravel()) score = rfc.score(Xtest.values, ytest.values) data_train_predictions = rfc.predict(Xtest.values) lin_mse = mean_squared_error(ytest.values, data_train_predictions) lin_rmse = np.sqrt(lin_mse) y_train_pred = cross_val_predict(rfc, Xtrain.values, ytrain.values, cv=10) precision = precision_score(ytrain.values, y_train_pred) recall = recall_score(ytrain.values, y_train_pred) print("随机森林模型的均方误差(mse)为%s, 均方根误差(rmse)为%s" % (lin_mse, lin_rmse)) print("随机森林模型的精度(precision)为%s, 召回率(recall)为%s" % (precision, recall)) print("随机森林模型的预测精准度为%s" % score)
return score
def fitEstimators(self, X, y): scorel = [] for i in range(0, 200, 10): rfc = RandomForestClassifier(n_estimators=i + 1, n_jobs=-1, random_state=90) score = cross_val_score(rfc, X, y, cv=10).mean() scorel.append(score) print("第一次查找随机森林的estimators得分: %s, 最优值: %s " % (max(scorel), (scorel.index(max(scorel)) * 10 + 1))) plt.figure(figsize=[20, 5]) plt.plot(range(1, 201, 10), scorel) plt.show() best_index = scorel.index(max(scorel)) * 10 + 1 scorel = [] for i in range(best_index - 10, best_index + 10): rfc = RandomForestClassifier(n_estimators=i, n_jobs=-1, random_state=90) score = cross_val_score(rfc, X, y, cv=10).mean() scorel.append(score) print("第二次查找随机森林的estimators得分: %s, 最优值: %s " % ( max(scorel), ([*range(best_index - 10, best_index + 10)][scorel.index(max(scorel))]))) plt.figure(figsize=[20, 5]) plt.plot(range(best_index - 10, best_index + 10), scorel) plt.show()
def lgPredict(self, Xtrain, Xtest, ytrain, ytest): LR_ = LR(penalty="l2", solver="liblinear", random_state=420, max_iter=1000) LR_.fit(Xtrain, ytrain) print("逻辑回归L2正则化每个特征的权重: %s" % LR_.coef_) plt.figure(figsize=[60, 5]) plt.bar(range(len(LR_.coef_[0])), abs(LR_.coef_[0]), color=['blue' if item > 0 else 'red' for item in LR_.coef_[0]], tick_label=COLUMNS3) plt.xlabel('characters') plt.ylabel('weight') plt.title('weight of characters(red is negative)') self.k = self.k + 1 plt.show() score = LR_.score(Xtest, ytest) data_train_predictions = LR_.predict(Xtest) lin_mse = mean_squared_error(ytest, data_train_predictions) lin_rmse = np.sqrt(lin_mse) y_train_pred = cross_val_predict(LR_, Xtrain, ytrain, cv=10) precision = precision_score(ytrain, y_train_pred) recall = recall_score(ytrain, y_train_pred) print("逻辑回归模型的均方误差(mse)为%s, 均方根误差(rmse)为%s" % (lin_mse, lin_rmse)) print("逻辑回归模型的精度(precision)为%s, 召回率(recall)为%s" % (precision, recall)) print("逻辑回归模型的预测精准度为%s" % score) return score
def svmPredict(self, Xtrain, Xtest, ytrain, ytest): kernels = ["linear", "poly", "rbf", "sigmoid"] scores = [] difference = [] for kernel in kernels: time0 = time() clf = SVC(kernel=kernel, gamma="auto", cache_size=2000).fit(Xtrain, ytrain) score = clf.score(Xtest, ytest) run_time = time() - time0 scores.append(score) print("在kernel为%s时, 准确率为%f" % (kernel, score)) print("运行时间为%s" % (datetime.datetime.fromtimestamp(run_time).strftime("%M:%S:%f"))) selected_kernel = kernels[scores.index(max(scores))] print("选取的kernel值为%s" % selected_kernel) for item in scores: difference.append(item - np.floor(min(scores) * 10) / 10) plt.figure(figsize=[20, 10]) plt.bar(range(len(scores)), difference, tick_label=kernels) plt.xlabel('Kernel') plt.ylabel('Accuracy - float(np.floor(min(scores) * 10) / 10)') plt.title('select kernel') self.m = self.m + 1 max_score = max(scores) clf = SVC(kernel=selected_kernel, gamma="auto", cache_size=2000).fit(Xtrain, ytrain) data_train_predictions = clf.predict(Xtest) lin_mse = mean_squared_error(ytest, data_train_predictions) lin_rmse = np.sqrt(lin_mse) y_train_pred = cross_val_predict(clf, Xtrain, ytrain, cv=10) precision = precision_score(ytrain, y_train_pred) recall = recall_score(ytrain, y_train_pred) print("svm模型的均方误差(mse)为%s, 均方根误差(rmse)为%s" % (lin_mse, lin_rmse)) print("svm模型的精度(precision)为%s, 召回率(recall)为%s" % (precision, recall)) print("svm模型的预测精准度为%s" % max_score) return max_score
if __name__ == '__main__': data = pd.read_csv('data/b_depressed.csv', index_col=0)
data_ = data.copy() depression = Depression(data_)
size1 = 10 size2 = 10000 df_l = [] rf_l = [] lg_l = [] svm_l = []
depression.preprocess(); real_data = depression.preprocessDetail() X = real_data.iloc[:, :-1] y = real_data.iloc[:, -1] depression.fitEstimators(X.values.tolist(), y.ravel())
for i in range(1, size1 + 1): Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.3)
score_1 = depression.decisionTree(Xtrain, Xtest, ytrain, ytest) df_l.append(score_1)
score_2 = depression.randomForest(Xtrain, Xtest, ytrain, ytest) rf_l.append(score_2)
score_3 = depression.lgPredict(Xtrain, Xtest, ytrain, ytest) lg_l.append(score_3)
score_4 = depression.svmPredict(Xtrain, Xtest, ytrain, ytest) svm_l.append(score_4)
print("-------------------第%d组结束-------------------" % i)
print("Logistic回归预测准确率最大值为: %f, 最小值为: %f." % (max(lg_l), min(lg_l))) print("决策树预测准确率最大值为: %f, 最小值为: %f." % (max(df_l), min(df_l))) print("随机森林预测准确率最大值为: %f, 最小值为: %f." % (max(rf_l), min(rf_l))) print("svm预测准确率最大值为: %f, 最小值为: %f." % (max(svm_l), min(svm_l))) plt.figure(figsize=[20, 5]) plt.plot(range(1, size1 + 1, 1), df_l, label="DecisionTree") plt.plot(range(1, size1 + 1, 1), rf_l, label="RandomForest") plt.plot(range(1, size1 + 1, 1), lg_l, label="Logistic") plt.plot(range(1, size1 + 1, 1), svm_l, label="SVM") plt.legend() plt.show()
|