import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import precision_score, recall_score, roc_curve, accuracy_score import matplotlib.pyplot as plt def drop_duplicates(path): data = pd.read_csv(path) data = data.drop_duplicates() # 去重 y = data.iloc[:, -1] y = y.drop_duplicates() print(y) # 9 10 8 20 16 19 14 11 12 18 13 5 4 6 21 17 22 1 3 26 23 29 2 27 25 24 def process_data(path): data = pd.read_csv(path) data = data.drop_duplicates() # 去重 # print(data) # 定义一个字典 将M 作为键 ;0 作为值。。。 class_dict = {"M": 0, "F": 1, "I": 2} # 将species 下的 替换 成 字典规则 data["Sex "] = data["Sex "].map(class_dict) # 将字典的键映射为值 即完成转换 # print(data) data = data.astype(float) X = data.iloc[:, :-1] y = data.iloc[:, -1] # 9 10 8 20 16 19 14 11 12 18 13 5 4 6 21 17 22 1 3 26 23 29 2 27 25 24 # 1 2 3 4 5 6 8 9 10 11 12 13 14 16 17 18 19 20 21 22 23 24 25 26 27 29 y[y == 1] = 0 y[y == 2] = 0 y[y == 3] = 0 y[y == 4] = 0 y[y == 5] = 0 y[y == 6] = 0 y[y == 7] = 0 y[y == 8] = 0 y[y == 9] = 0 y[y == 10] = 0 y[y == 11] = 1 y[y == 12] = 1 y[y == 13] = 1 y[y == 14] = 1 y[y == 16] = 1 y[y == 17] = 1 y[y == 18] = 1 y[y == 19] = 1 y[y == 20] = 1 y[y == 21] = 2 y[y == 22] = 2 y[y == 23] = 2 y[y == 24] = 2 y[y == 25] = 2 y[y == 26] = 2 y[y == 27] = 2 y[y == 29] = 2 # print(X) # print(y) # 特征标准化 自变量数据的归一化 mu = X.mean(0) std = X.std(0) X = (X - mu) / std # 归一化 使其范围缩小到(-1,1) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.33, random_state = 42) return X_train, X_test, y_train, y_test def decisionTree( X_train, X_test, y_train, y_test): # 默认为gini系数方法 需要指定信息增益的方法-即ID3决策树 clf = DecisionTreeClassifier(criterion="entropy")# ID3决策树 clf.fit(X_train,y_train) y_predict = clf.predict(X_test) # print("预测值-pridict", y_predict) print("自己计算-模型准确率", np.sum(y_test == y_predict) / len(y_test)) # 手动计算模型准确率 # 模型评价 print("precision_score:", precision_score(y_test, y_predict, average='micro')) print("recall_score:", recall_score(y_test, y_predict, average='micro')) print("accuracy_score:", accuracy_score(y_test, y_predict)) # roc曲线绘制 fpr, tpr, thresholds = roc_curve(y_test, y_predict,pos_label=2) plt.xlim(0, 1) plt.ylim(0, 1) plt.plot(fpr, tpr, color="blue") plt.show() print("accuracy on training set:",clf.score(X_train, y_train))# 训练集上的精度是 100%,这是因为叶结点都是纯的,树的深度很大 print("accuracy on test set:{:.3f}".format(clf.score(X_test, y_test)))# 线性模型的精度 # y_pred = clf.predict(X_test) # return y_pred if __name__ == '__main__': path = r"F:\\desktop\\abalone.csv" X_train, X_test, y_train, y_test = process_data(path) decisionTree(X_train, X_test, y_train, y_test)
我是哭哭我还是苦苦
最新推荐文章于 2024-08-15 14:09:45 发布