机器学习:基于Sklearn框架,使用逻辑回归对由心脏病引发的死亡进行预测分析

前言

系列专栏:机器学习:高级应用与实践【项目实战100+】【2024】✨︎
在本专栏中不仅包含一些适合初学者的最新机器学习项目,每个项目都处理一组不同的问题,包括监督和无监督学习、分类、回归和聚类,而且涉及创建深度学习模型、处理非结构化数据以及指导复杂的模型,如卷积神经网络、门控递归单元、大型语言模型和强化学习模型

世界卫生组织估计,五分之四的心血管疾病(CVD)死亡是由心脏病发作引起的。整个研究旨在确定很有可能受到 CVD 影响的患者比例,并使用 Logistic Regression 预测总体风险。

逻辑回归: 尽管被称为回归,但实际上是一种广泛使用的监督分类技术。逻辑回归及其扩展,如多项式逻辑回归,允许我们使用一种简单易懂的方法预测观测值属于某一类的概率。

import pandas as pd
import pylab as pl
import numpy as np
import scipy.optimize as opt
import statsmodels.api as sm
from sklearn import preprocessing
'exec(% matplotlib inline)'
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import seaborn as sns

1. 数据准备

该数据集来自一项正在进行的对马萨诸塞州弗雷明汉镇居民的心血管研究。分类目标是预测患者未来10年是否有冠心病(CHD)的风险。数据集提供患者的信息。它包括4000多条记录和15个属性。

1.1 加载数据集

# dataset
disease_df = pd.read_csv("framingham.csv")
disease_df.drop(['education'], inplace = True, axis = 1)
disease_df.rename(columns ={'male':'Sex_male'}, inplace = True)

1.2 处理缺失值

# removing NaN / NULL values
disease_df.dropna(axis = 0, inplace = True)
print(disease_df.head(), disease_df.shape)
print(disease_df.TenYearCHD.value_counts())

输出

   Sex_male  age  currentSmoker  cigsPerDay  BPMeds  prevalentStroke  \
0         1   39              0         0.0     0.0                0   
1         0   46              0         0.0     0.0                0   
2         1   48              1        20.0     0.0                0   
3         0   61              1        30.0     0.0                0   
4         0   46              1        23.0     0.0                0   

   prevalentHyp  diabetes  totChol  sysBP  diaBP    BMI  heartRate  glucose  \
0             0         0    195.0  106.0   70.0  26.97       80.0     77.0   
1             0         0    250.0  121.0   81.0  28.73       95.0     76.0   
2             0         0    245.0  127.5   80.0  25.34       75.0     70.0   
3             1         0    225.0  150.0   95.0  28.58       65.0    103.0   
4             0         0    285.0  130.0   84.0  23.10       85.0     85.0   

   TenYearCHD  
0           0  
1           0  
2           0  
3           1  
4           0   (3751, 15)
TenYearCHD
0    3179
1     572
Name: count, dtype: int64

1.3 将数据集拆分为测试集和训练集

X = np.asarray(disease_df[['age', 'Sex_male', 'cigsPerDay', 
                           'totChol', 'sysBP', 'glucose']])
y = np.asarray(disease_df['TenYearCHD'])

# normalization of the dataset
X = preprocessing.StandardScaler().fit(X).transform(X)

# Train-and-Test -Split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( 
        X, y, test_size = 0.3, random_state = 4)

print ('Train set:', X_train.shape,  y_train.shape)
print ('Test set:', X_test.shape,  y_test.shape)

输出

Train set: (2625, 6) (2625,)
Test set: (1126, 6) (1126,)

2. 心脏病数据集的探索性数据分析

2.1 数据集中所有可用患者的十年冠心病记录:

# counting no. of patients affected with CHD
plt.figure(figsize=(7, 5))
sns.countplot(x='TenYearCHD', hue="TenYearCHD", data=disease_df, legend=False,
             palette="BuGn_r")
plt.show()

输出
在这里插入图片描述

2.2 计算受冠心病影响的患者人数,其中(0 = 未受影响;1 = 受影响)

laste = disease_df['TenYearCHD'].plot()
plt.show(laste)

输出
在这里插入图片描述

3. 用于心脏病预测的拟合逻辑回归模型

3.1 训练模型

from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
y_pred = logreg.predict(X_test)

3.2 评估逻辑回归模型

# Evaluation and accuracy
from sklearn.metrics import accuracy_score
print('Accuracy of the model is =', 
      accuracy_score(y_test, y_pred))

输出

Accuracy of the model is = 0.8490230905861457

3.3 混淆矩阵

# Confusion matrix 
from sklearn.metrics import confusion_matrix, classification_report

cm = confusion_matrix(y_test, y_pred)
conf_matrix = pd.DataFrame(data = cm, 
                           columns = ['Predicted:0', 'Predicted:1'], 
                           index =['Actual:0', 'Actual:1'])

plt.figure(figsize = (8, 5))
sn.heatmap(conf_matrix, annot = True, fmt = 'd', cmap = "Greens")

plt.show()
print('The details for confusion matrix is =')
print (classification_report(y_test, y_pred))

输出
在这里插入图片描述

The details for confusion matrix is =
              precision    recall  f1-score   support

           0       0.85      0.99      0.92       951
           1       0.61      0.08      0.14       175

    accuracy                           0.85      1126
   macro avg       0.73      0.54      0.53      1126
weighted avg       0.82      0.85      0.80      1126

最近更新

  1. TCP协议是安全的吗?

    2024-04-29 12:12:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-29 12:12:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-29 12:12:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-29 12:12:02       20 阅读

热门阅读

  1. FreeLearning Golang 译文集翻译完成

    2024-04-29 12:12:02       12 阅读
  2. C++——数据类型笔记

    2024-04-29 12:12:02       9 阅读
  3. python常用库函数

    2024-04-29 12:12:02       10 阅读
  4. HTTP状态码详细解读

    2024-04-29 12:12:02       12 阅读
  5. C语言真题20套

    2024-04-29 12:12:02       11 阅读
  6. Python医院挂号脚本

    2024-04-29 12:12:02       12 阅读
  7. 蓝桥杯每日一题:空调(差分)

    2024-04-29 12:12:02       13 阅读
  8. 学习 Rust 的第五天:了解程序的基本控制流程

    2024-04-29 12:12:02       10 阅读
  9. 冷热数据分离方案

    2024-04-29 12:12:02       11 阅读
  10. typedef,#define,asserr,exit函数,free函数

    2024-04-29 12:12:02       12 阅读
  11. 探索Vue 3 reactive()原理及其实现步骤

    2024-04-29 12:12:02       12 阅读
  12. vue 的 keep-alive 详解

    2024-04-29 12:12:02       12 阅读
  13. 算法基础一

    2024-04-29 12:12:02       12 阅读
  14. wps用js宏给文档增加用户名密码验证

    2024-04-29 12:12:02       13 阅读
  15. 每天学习一个Linux命令之ncdu

    2024-04-29 12:12:02       13 阅读