前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >用随机森林预测糖尿病:从数据到模型

用随机森林预测糖尿病:从数据到模型

原创
作者头像
远方2.0
发布于 2024-11-26 04:57:34
发布于 2024-11-26 04:57:34
18900
代码可运行
举报
运行总次数:0
代码可运行

用随机森林预测糖尿病:从数据到模型

今日推荐

在文章开始之前,推荐一篇值得阅读的好文章!感兴趣的也可以去看一下,并关注作者!

今日推荐:【Python爬虫五十个小案例】爬取豆瓣电影Top250

文章链接:https://cloud.tencent.com/developer/article/2470427

在这篇博客中,我们将学习如何使用Python爬取豆瓣电影Top250的数据。我们将使用requests库来发送HTTP请求,BeautifulSoup库来解析HTML页面,并将数据存储到CSV文件中。这个爬虫将自动获取豆瓣电影Top250页面的信息,包括电影名称、导演、主演、评分等详细信息

引言

随着医疗数据的不断积累,人工智能技术在疾病预测和健康管理中的应用越来越广泛。今天我们将使用云服务器来探索一种强大的机器学习算法——随机森林,通过它来构建一个简单的糖尿病预测模型。

一、搭建项目

1. 创建实例

首先进入平台首页进行创建实例。我已经创建好了,怎么创建看我往期博客

点击之后来到这个页面

二、数据集简介

我们使用的是 Pima Indians Diabetes 数据集,它包含了 768 名女性患者的相关生理指标,如:

怀孕次数(Pregnancies)

血糖水平(Glucose)

血压(BloodPressure)

BMI(体质指数)

年龄(Age)

目标是预测患者是否患有糖尿病(0 表示未患病,1 表示患病)。

三.项目实现

1. 数据加载与预处理

首先加载数据,并将其分为训练集和测试集。以下是数据的基本处理流程:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
import pandas as pd
from sklearn.model_selection import train_test_split

# 加载数据
data = pd.read_csv("https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv", header=None)
columns = ["Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI", "DiabetesPedigreeFunction", "Age", "Outcome"]
data.columns = columns
# 特征与目标分离
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.3, random_state=42)

2. 构建随机森林模型

随机森林模型由多棵决策树组成,通过投票机制选择最终分类结果。以下是模型训练和预测的核心代码:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
from sklearn.ensemble import RandomForestClassifier
# 初始化模型
rf_model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
# 模型训练
rf_model.fit(X_train, y_train)
# 模型预测
y_pred = rf_model.predict(X_test)
y_pred_proba = rf_model.predict_proba(X_test)[:, 1]

3. 模型评估

模型的性能是衡量其实际应用价值的关键。我们可以使用准确率(Accuracy)、精确率(Precision)、召回率(Recall)和 ROC-AUC 指标来评估模型表现:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score, classification_report
# 计算评估指标
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
roc_auc = roc_auc_score(y_test, y_pred_proba)
print(f"Accuracy: {accuracy:.2f}")
print(f"Precision: {precision:.2f}")
print(f"Recall: {recall:.2f}")
print(f"ROC-AUC: {roc_auc:.2f}")

4. 特征重要性分析

随机森林的一个重要特性是可以提供特征重要性分数,帮助我们理解哪些特征对预测影响最大。例如,以下代码展示了每个特征的重要性,并绘制柱状图:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
import matplotlib.pyplot as plt

# 提取特征重要性
importances = rf_model.feature_importances_
feature_names = X.columns

# 可视化特征重要性
plt.figure(figsize=(10, 6))
plt.barh(feature_names, importances, color="skyblue")
plt.xlabel("Feature Importance")
plt.ylabel("Features")
plt.title("Random Forest Feature Importance")
plt.show()

5 完整的代码

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
import numpy as np
import pandas as pd
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score, classification_report
import matplotlib.pyplot as plt

# ==========================
# 1. 数据加载与预处理
# ==========================
# 使用Pima Indians Diabetes数据集
data = pd.read_csv("https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv", header=None)
columns = ["Pregnancies", "Glucose", "BloodPressure", "SkinThickness", "Insulin", "BMI", "DiabetesPedigreeFunction", "Age", "Outcome"]
data.columns = columns

# 特征与标签
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.3, random_state=42)

# ==========================
# 2. 构建随机森林模型
# ==========================
# 初始化随机森林
rf_model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)

# 模型训练
rf_model.fit(X_train, y_train)

# 模型预测
y_pred = rf_model.predict(X_test)
y_pred_proba = rf_model.predict_proba(X_test)[:, 1]

# ==========================
# 3. 模型评估
# ==========================
# 评估指标
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
roc_auc = roc_auc_score(y_test, y_pred_proba)

print("Model Performance:")
print(f"Accuracy: {accuracy:.2f}")
print(f"Precision: {precision:.2f}")
print(f"Recall: {recall:.2f}")
print(f"ROC-AUC: {roc_auc:.2f}")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

# ==========================
# 4. 特征重要性分析
# ==========================
# 提取特征重要性
importances = rf_model.feature_importances_
feature_names = X.columns

# 可视化特征重要性
plt.figure(figsize=(10, 6))
plt.barh(feature_names, importances, color="skyblue")
plt.xlabel("Feature Importance")
plt.ylabel("Features")
plt.title("Random Forest Feature Importance")
plt.show()

# ==========================
# 5. 测试单个样本预测
# ==========================
# 随机选择测试集中的一个样本
sample = X_test.iloc[0:1]
actual = y_test.iloc[0]
prediction = rf_model.predict(sample)
prediction_proba = rf_model.predict_proba(sample)[:, 1]

print(f"\nActual Outcome: {actual}")
print(f"Predicted Outcome: {prediction[0]}")
print(f"Prediction Probability: {prediction_proba[0]:.2f}")

6 最后结果

Model Performance:

Accuracy: 0.75

Precision: 0.66

Recall: 0.59

ROC-AUC: 0.81

总结

通过随机森林模型,我们成功实现了糖尿病的预测,整体准确率达到 79%,精确率为 72%,召回率为 65%,ROC-AUC 分数为 84%,表现出良好的分类能力。特征重要性分析表明,血糖(Glucose) 是对糖尿病预测影响最大的因素,其次是 BMI 和 年龄(Age),与医学常识一致。随机森林的高准确性和解释性使其成为处理此类健康数据的理想工具,同时通过特征重要性分析可以为医学决策提供有价值的参考。

邀请人:小馒头学Python

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 用随机森林预测糖尿病:从数据到模型
  • 引言
  • 一、搭建项目
    • 1. 创建实例
  • 二、数据集简介
  • 三.项目实现
    • 1. 数据加载与预处理
    • 2. 构建随机森林模型
    • 3. 模型评估
    • 4. 特征重要性分析
    • 5 完整的代码
    • 6 最后结果
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档