使用决策树和随机森林分析预测糖尿病

使用决策树与随机森林预测糖尿病

数据源: Pima Indians Diabetes Database | Kaggle

目的:生成决策树可视化;输出决策树和随机森林的性能报告;画出ROC图;分析不同特征的重要性

(作笔记使用,如有错误,欢迎指正!)

导入数据:

import pandas as pd
data = pd.read_csv('./datasets.csv')
data.head()

标题解释:

    ·Pregnancies:怀孕(次数)
    ·Glucose:葡萄糖
    ·BloodPressure:血压
    ·SkinThickness:皮肤厚度
    ·Insulin:胰岛素
    ·BMI:体重指数
    ·DiabetesPedigreeFunction:糖尿病谱系功能
    ·Age:年龄
    ·Outcome:结果

代码:

输出决策树和随机森林的性能报告

import pandas as pd
import numpy as np
from pandas import DataFrame
from sklearn.metrics import roc_auc_score
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split


# 读取数据
data = pd.read_csv('./datasets.csv')

# 将预测标签Outcome数据放到第一列
front = data['Outcome']
data.drop(labels='Outcome',axis = 1, inplace = True)
data.insert(0,'Outcome',front)


y = data.iloc[:,0]
x = data.iloc[:,1:]

x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=30/768)

# 决策树
# max_depth=3定义树的深度, 可以用来防止过拟合
# min_weight_fraction_leaf 定义叶子节点最少要包含多少个样本(百分比表达), 防止过拟合
dtree = tree.DecisionTreeClassifier(criterion='entropy',max_depth=3,min_weight_fraction_leaf=0.01)
dtree = dtree.fit(x_train,y_train)

print('\n\n---决策树---')
dt_roc_auc = roc_auc_score(y_test,dtree.predict(x_test))
print('决策树 AUC = %2.2f'%dt_roc_auc)
print(classification_report(y_test,dtree.predict(x_test)))

# 随机森林
# max_depth=None  定义树的深度,可以用来防止过拟合
# min_samples_split=10  定义至少多少个样本的情况下才继续分叉,可以用来防止过拟合
rf = RandomForestClassifier(criterion='entropy',n_estimators=1000,max_depth=None,min_samples_split=10,min_weight_fraction_leaf=0.02)
rf.fit(x_train,y_train)
print('\n\n---随机森林---')
rf_roc_auc = roc_auc_score(y_test,rf.predict(x_test))
print('随机森林 AUC = %2.2f'%rf_roc_auc)
print(classification_report(y_test,rf.predict(x_test)))

y_ = np.array(y_test)
print('随机森林预测结果:',rf.predict(x_test))
print('真实结果:         ',y_)

# 决策树可视化
# 生成.dot文件
with open('treeone.dot', 'w') as f:
 
    dot_data = tree.export_graphviz(dtree, out_file=None)
 
    f.write(dot_data)

决策树和随机森林的性能报告:

生成决策树可视化:

# 决策树可视化
# 生成.dot文件
with open('treeone.dot', 'w') as f:
 
    dot_data = tree.export_graphviz(dtree, out_file=None)
 
    f.write(dot_data)

会在当前目录上生成一个.dot文件,然后打开cmd,定位到.dot文件所在的路径,运行命令:dot -Tpdf treeone.dot -o treeone.pdf

则会在当前目录上生成pdf文件

(注:这里要安装Graphviz,并配置好环境变量,安装教程可参考这里;可视化决策树可参考这里

生成后的pdf大概是这样:

ROC图

from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
%matplotlib inline

rf_fpr, rf_tpr, rf_thresholds = roc_curve(y_test,rf.predict_proba(x_test)[:,1])
dt_fpr, dt_tpr, dt_thresholds = roc_curve(y_test,dtree.predict_proba(x_test)[:,1])
plt.figure()

# 随机森林 ROC
plt.plot(rf_fpr,rf_tpr, label = 'Random Forest(area=%0.2f)'%rf_roc_auc)

# 决策树 ROC
plt.plot(dt_fpr,dt_tpr, label = 'Decision Tree(area=%0.2f)'%dt_roc_auc)

plt.xlim([0.0,1.0])
plt.ylim([0.0,1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Graph')
plt.legend(loc="lower right")
plt.show()

所得结果:

分析不同特征的重要性

# 画出随机森林特征的重要性
importances = rf.feature_importances_
feat_names = data.drop(['Outcome'],axis = 1).columns

indices = np.argsort(importances)[::-1]

plt.figure(figsize=(12,6))
plt.title('Feature improtances by RandomForest')
plt.bar(range(len(indices)),importances[indices],color='lightblue', align='center')
plt.step(range(len(indices)),np.cumsum(importances[indices]),where='mid',label='Cumulative')
plt.xticks(range(len(indices)),feat_names[indices],rotation='vertical',fontsize=14)
plt.xlim([-1,len(indices)])
plt.show()

# 画出决策树的特征的重要性 
importances = dtree.feature_importances_
feat_names = data.drop(['Outcome'],axis=1).columns
indices = np.argsort(importances)[::-1]
plt.figure(figsize=(12,6))
plt.title("Feature importances by Decision Tree")
plt.bar(range(len(indices)), importances[indices], color='lightblue',  align="center")
plt.step(range(len(indices)), np.cumsum(importances[indices]), where='mid', label='Cumulative')
plt.xticks(range(len(indices)), feat_names[indices], rotation='vertical',fontsize=14)
plt.xlim([-1, len(indices)])
plt.show()

欢迎指正与指点!

好的,以下是一个基于Python实现的随机森林算法预测糖尿病的案例。 首先,我们需要加载数据集,并将其划分为训练集和测试集: ```python import pandas as pd from sklearn.model_selection import train_test_split # 加载数据集 data = pd.read_csv('diabetes.csv') # 划分特征和标签 X = data.drop('Outcome', axis=1) y = data['Outcome'] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 接下来,我们可以使用随机森林算法进行训练和预测: ```python from sklearn.ensemble import RandomForestClassifier # 创建随机森林分类器 rfc = RandomForestClassifier(n_estimators=100, random_state=42) # 训练模型 rfc.fit(X_train, y_train) # 预测结果 y_pred = rfc.predict(X_test) ``` 最后,我们可以使用一些评估指标来评估模型的性能,例如混淆矩阵、准确率、召回率和F1得分: ```python from sklearn.metrics import confusion_matrix, accuracy_score, recall_score, f1_score # 计算混淆矩阵 conf_matrix = confusion_matrix(y_test, y_pred) # 计算准确率 accuracy = accuracy_score(y_test, y_pred) # 计算召回率 recall = recall_score(y_test, y_pred) # 计算F1得分 f1 = f1_score(y_test, y_pred) print('混淆矩阵:\n', conf_matrix) print('准确率:', accuracy) print('召回率:', recall) print('F1得分:', f1) ``` 完整代码如下: ```python import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix, accuracy_score, recall_score, f1_score # 加载数据集 data = pd.read_csv('diabetes.csv') # 划分特征和标签 X = data.drop('Outcome', axis=1) y = data['Outcome'] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 创建随机森林分类器 rfc = RandomForestClassifier(n_estimators=100, random_state=42) # 训练模型 rfc.fit(X_train, y_train) # 预测结果 y_pred = rfc.predict(X_test) # 计算混淆矩阵 conf_matrix = confusion_matrix(y_test, y_pred) # 计算准确率 accuracy = accuracy_score(y_test, y_pred) # 计算召回率 recall = recall_score(y_test, y_pred) # 计算F1得分 f1 = f1_score(y_test, y_pred) print('混淆矩阵:\n', conf_matrix) print('准确率:', accuracy) print('召回率:', recall) print('F1得分:', f1) ``` 注意,这里的数据集是一个名为"diabetes.csv"的文件,其包含了多个人的各种生理指标和是否患有糖尿病的标签。在实际使用中,您需要将数据集替换为您自己的数据集。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

布响哒公

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值