python数据分析-心脏衰竭分析与预测

研究背景

人的心脏有四个瓣膜,主动脉银、二尖、肺动脉和三尖源 不管是那一个膜发生了病变,都会导致心脏内的血流受到影响,这就是通常所说的心脏期膜病,很多是需要通过手术的方式进行改善的。随着人口老龄化的加剧,,心脏期膜病是我国最常见的心血管疾病之-,需要接受心脏瓣膜手术治疗的患者数量逐年拳升。心脏期膜手术是对病变的心脏辨膜所进行的外科手术,一般包括心脏期的置换和修复手术,心期手术是在外科技术的基础上,对病变的心脏期膜所进行的手术,可以改善患者心脏期聘狭窄或关闭不全的现象。不过心脏瓣膜病手术可能会引发机械瓣并发症,导致心功能变差,严重的还会直接造成患者死亡。

实验分析

首先导入基本的数据分析包

python 复制代码
# import data handling libs

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns


# import models

from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.svm  import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

import warnings
warnings.filterwarnings('ignore')

读取数据

python 复制代码
# Importing dataset

df = pd.read_csv('dataset.csv')

展示数据集和结构

python 复制代码
df.head()
rows, columns = df.shape

print(f"Number Of Rows : {rows}")
print(f"Number Of Columns : {columns}")

数据集特征结构

python 复制代码
df.info()

描述性分析

python 复制代码
df.describe()

查看每列的唯一值的数量

python 复制代码
df.nunique()

查看下相关系数并且画出热力图

python 复制代码
plt.figure(figsize=(10, 8))
corr = df.corr()
sns.heatmap(corr, annot=True, cmap='Blues')

查看缺失值

python 复制代码
df.isnull().sum()

接下来进行特征选择

python 复制代码
plt.rcParams['figure.figsize']=15,6 
sns.set_style("darkgrid")

x = df.iloc[:, :-1]
y = df.iloc[:,-1]

from sklearn.ensemble import ExtraTreesClassifier
import matplotlib.pyplot as plt
model = ExtraTreesClassifier()
model.fit(x,y)
print(model.feature_importances_) 
feat_importances = pd.Series(model.feature_importances_, index=x.columns)
feat_importances.nlargest(12).plot(kind='barh', color='teal')
plt.show()

检查一下离群值

python 复制代码
sns.boxplot(x = df.ejection_fraction, color='teal')
plt.show()

可以发现有两个离群值

接下来对特征进行可视化

python 复制代码
# Distribution of Age

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Histogram(
    x = df['age'],
    xbins=dict( # bins used for histogram
        start=40,
        end=95,
        size=2
    ),
    marker_color='#e8ab60',
    opacity=1
))

fig.update_layout(
    title_text='AGE DISTRIBUTION',
    xaxis_title_text='AGE',
    yaxis_title_text='COUNT', 
    bargap=0.05, # gap between bars of adjacent location coordinates
    xaxis =  {'showgrid': False },
    yaxis = {'showgrid': False },
    template = 'plotly_dark'
)

fig.show()
python 复制代码
plt.style.use("seaborn")
for column in df.columns:
    if df[column].dtype!="object":
        plt.figure(figsize=(15,6))
        plt.subplot(2,2,1)
        sns.histplot(data=df,x=column,kde=True)
        plt.ylabel("freq")
        plt.xlabel(column)
        plt.title(f"distribution of {column}")
        plt.subplot(2,2,2)
        sns.boxplot(data=df,x=column)
        plt.ylabel(column)
        plt.title(f"boxplot of {column}")
        plt.show()

接下来进行机器学习预测,划分训练集和测试集

逻辑回归

python 复制代码
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()

x = scaler.fit_transform(x)
y = scaler.fit_transform(y.values.reshape(-1,1))
python 复制代码
model = LogisticRegression()
model.fit(x_train, y_train)
y_pred = model.predict(x_test)
print(classification_report(y_test,y_pred))

决策树

支持向量机

python 复制代码
plt.rcParams['figure.figsize']=15,6 
sns.set_style("darkgrid")
ax = sns.barplot(x=mylist2, y=mylist, palette = "rocket", saturation =1.5)
plt.xlabel("Classifier Models", fontsize = 20 )
plt.ylabel("% of Accuracy", fontsize = 20)
plt.title("Accuracy of different Classifier Models", fontsize = 20)
plt.xticks(fontsize = 12, horizontalalignment = 'center', rotation = 8)
plt.yticks(fontsize = 13)
for p in ax.patches:
    width, height = p.get_width(), p.get_height()
    x, y = p.get_xy() 
    ax.annotate(f'{height:.2%}', (x + width/2, y + height*1.02), ha='center', fontsize = 'x-large')
plt.show()

完整代码和数据

创作不易,希望大家多点赞关注评论!!!

相关推荐
AI视觉网奇1 小时前
麒麟系统播放图片 速度比较
开发语言·python·pygame
言之。1 小时前
Django REST框架核心:GenericAPIView详解
数据库·python·django
这里有鱼汤1 小时前
别傻了,这些量化策略AI 10 秒就能帮你写好
后端·python
胡耀超1 小时前
机器学习数学基础与商业实践指南:从统计显著性到预测能力的认知升级
人工智能·python·机器学习·数据挖掘·数据分析·数据科学·统计学
Caaacy_YU2 小时前
多模态大模型研究每日简报【2025-08-21】
论文阅读·人工智能·机器学习·计算机视觉
杨荧2 小时前
基于Python的反诈知识科普平台 Python+Django+Vue.js
大数据·前端·vue.js·python·数据分析
大模型真好玩2 小时前
深入浅出LangChain AI Agent智能体开发教程(九)—LangChain从0到1搭建知识库
人工智能·python·mcp
星期天要睡觉3 小时前
机器学习——网格搜索(GridSearchCV)超参数优化
人工智能·机器学习
MZ_ZXD0017 小时前
springboot汽车租赁服务管理系统-计算机毕业设计源码58196
java·c++·spring boot·python·django·flask·php
A 计算机毕业设计-小途8 小时前
大四零基础用Vue+ElementUI一周做完化妆品推荐系统?
java·大数据·hadoop·python·spark·毕业设计·毕设