作者:Abdullah Alrhmoun

该项目的目标是建立一个模型,该模型可以根据描述疾病的特征组合预测心脏病发生的概率。为了实现这一目标,作者使用了瑞士Cleveland Clinic Foundation收集的数据集。该项目中使用的数据集包含针对心脏病的14个特征。数据集显示不同水平的心脏病存在从1​​到4和0没有疾病。我们有303行人数据,13个连续观察不同的症状。此项目研究了不同的经典机器学习模型,以及它们在疾病风险中的发现。

导入依赖库


#导入依赖库
import pandas as pnd
import numpy as np
from sklearn import preprocessing
from sklearn import neighbors, datasets
from sklearn import cross_validation
from sklearn.linear_model import SGDClassifier
from sklearn import svm
import operator
from sklearn.cross_validation import KFoldimport itertools
import numpy as np
import matplotlib.pyplot as pltfrom sklearn import metrics
from sklearn.metrics import confusion_matrixfrom sklearn import tree
import seaborn as snsfrom IPython.display import Image%matplotlib inline

载入数据

# 添加列名
header_row = ['age','sex','chest_pain','blood pressure','serum_cholestoral','fasting_blood_sugar',\'electrocardiographic','max_heart_rate','induced_angina','ST_depression','slope','vessels','thal','diagnosis']# 载入数据
heart = pnd.read_csv('processed.cleveland.data.csv', names=header_row)
heart[:5]

#查看数据维度
heart.shape
(303, 14)   #303行人的数据,13个连续观察不同症状。

数据探索

# 计算统计值
heart.describe()

计算某个特征的人数

names_descr = dict()
categorical_columns = ["sex", "chest_pain", "fasting_blood_sugar", "electrocardiographic", "induced_angina", "slope", "vessels", \"thal", "diagnosis"]
for c in categorical_columns:print  (heart.groupby([c])["age"].count())

使用简单的均值插补方法预处理数据,将缺失的数据更改为平均值

for c in heart.columns[:-1]:heart[c] = heart[c].apply(lambda x: heart[heart[c]!='?'][c].astype(float).mean() if x == "?" else x)heart[c] = heart[c].astype(float)   

心脏病类型发现

set(heart.loc[:, "diagnosis"].values)

(0 :没有疾病;1,2,3,4 代表不同疾病类型)

计算1,2,3,4 levels 之间的相似性

vecs_1 = heart[heart["diagnosis"] == 1 ].median().values[:-2]
vecs_2 = heart[heart["diagnosis"] == 2 ].median().values[:-2]
vecs_3 = heart[heart["diagnosis"] == 3 ].median().values[:-2]
vecs_4 = heart[heart["diagnosis"] == 4 ].median().values[:-2]
print ("Similarity between type 1 and type 2 is ", np.linalg.norm(vecs_1-vecs_2))
print ("Similarity between type 1 and type 3 is ", np.linalg.norm(vecs_1-vecs_3))
print ("Similarity between type 1 and type 4 is ", np.linalg.norm(vecs_1-vecs_4))
print ("Similarity between type 2 and type 3 is ", np.linalg.norm(vecs_2-vecs_3))
print ("Similarity between type 2 and type 4 is ", np.linalg.norm(vecs_2-vecs_4))
print ("Similarity between type 3 and type 4 is ", np.linalg.norm(vecs_3-vecs_4))
sim = {"(1,2)": np.linalg.norm(vecs_1-vecs_2), \"(1,3)": np.linalg.norm(vecs_1-vecs_3),\"(1,4)": np.linalg.norm(vecs_1-vecs_4),\"(2,3)": np.linalg.norm(vecs_2-vecs_3),\"(2,4)": np.linalg.norm(vecs_2-vecs_4),\"(3,4)": np.linalg.norm(vecs_3-vecs_4)    }
# 根据相近值排序
sorted_sim = sorted(sim.items(), key=operator.itemgetter(1))
sorted_sim

可以分别使用每个特征的值来比较心脏病的类型

heart_d = heart[heart["diagnosis"] >= 1 ]
heart_d[:5]

数据预处理

# if "diagnosis" == 0, 没有疾病
# if "diagnosis" >= 1, 有疾病
heart.loc[:, "diag_int"] = heart.loc[:, "diagnosis"].apply(lambda x: 1 if x >= 1 else 0)
#数据标准化
preprocessing.Normalizer().fit_transform(heart)
#划分数据集
heart_train, heart_test, goal_train, goal_test = cross_validation.train_test_split(heart.loc[:,'age':'thal'], \heart.loc[:,'diag_int'], test_size=0.33, random_state=0)  
#计算相关系数
corr = heart.corr()
heart.corr()

#绘制热图
cmap = sns.diverging_palette(250, 10, n=3, as_cmap=True)def magnify():return [dict(selector="th",props=[("font-size", "7pt")]),dict(selector="td",props=[('padding', "0em 0em")]),dict(selector="th:hover",props=[("font-size", "12pt")]),dict(selector="tr:hover td:hover",props=[('max-width', '200px'),('font-size', '12pt')])
]corr.style.background_gradient(cmap, axis=1)\.set_properties(**{'max-width': '80px', 'font-size': '10pt'})\.set_caption("Hover to magify")\.set_precision(2)\.set_table_styles(magnify())

探索可视化

#年龄与血压关系
import matplotlib.pyplot as plt
%matplotlib inlineplt.xlabel("age")
plt.ylabel("blood pressure")# define title
plt.title("Relationship between age and blood pressure")# plot
plt.scatter(heart['age'], heart['blood pressure'])
plt.show()

建立训练模型并评估LSS参数

# add parameters for grid search
loss = ["hinge", "log"]
penalty = ["l1", "l2"]
alpha = [0.1, 0.05, 0.01]
n_iter = [500, 1000]# build the models with different parameters and select the best combination for the highest Accuracy
best_score = 0
best_param = (0,0,0,0)
for l in loss:for p in penalty:for a in alpha:for n in n_iter:print("Parameters for model", (l,p,a,n))lss = SGDClassifier(loss=l, penalty=p, alpha=a, n_iter=n)lss.fit(heart_train, goal_train)print("Linear regression SGD Cross-Validation scores:")scores = cross_validation.cross_val_score(lss, heart.loc[:,'age':'thal'], heart.loc[:,'diag_int'], cv=10)print (scores)print("Mean Linear regression SGD Cross-Validation score = ", np.mean(scores))if np.mean(scores) > best_score:best_score = np.mean(scores)best_param = (l,p,a,n)print("The best parameters for model are ", best_param)
print("The Cross-Validation score = ", best_score)
lss_best = SGDClassifier(alpha=0.05, fit_intercept=True, loss='log', n_iter=1000,
penalty='l1')
lss_best.fit(heart_train, goal_train)
print("Linear regression SGD Test score:")
print(lss_best.score(heart_test, goal_test))   

模型验证

# Compute confusion matrix
cnf_matrix = confusion_matrix(goal_test, lss_best.predict(heart_test))
np.set_printoptions(precision=2)# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=["Heart disease", "No heart disease"],title='Confusion matrix, without normalization')
plt.show()

参考:

https://github.com/Sonali1197/Heart-disease-prediction-model


DrugAI

心脏病预测模型(基于Python的数据挖据)相关推荐

  1. 基于Python大数据的的新能源汽车推荐系统的设计与实现

    基于Python大数据的的新能源汽车推荐系统的设计与实现 源码仓库------https://www.bilibili.com/video/BV1Ne4y1g7dC/ python的各种推荐算法 图书 ...

  2. 基于python大数据爬取房价数据可视化

    基于python大数据爬取房价数据可视化

  3. 基于python的数据爬取与分析_基于Python的网站数据爬取与分析的技术实现策略

    欧阳元东 摘要:Python为网页数据爬取和数据分析提供了很多工具包.基于Python的BeautifulSoup可以快速高效地爬取网站数据,Pandas工具能方便灵活地清洗分析数据,调用Python ...

  4. python聚类算法中x是多维、y是一维怎么画图_基于Python的数据可视化:从一维到多维...

    目录 一.iris数据集介绍 二.一维数据可视化 三.二维数据可视化 四.多维数据可视化 五.参考资料 一.iris数据集介绍 iris数据集有150个观测值和5个变量,分别是sepal length ...

  5. 『数据可视化』基于Python的数据可视化工具

    刘宇宙,现在一家创业型公司做技术总负责,做爬虫和数据处理相关工作,曾从事过卡系统研发.金融云计算服务系统研发,物联网方向大数据研发,著书一本,<Python3.5从零开始学> 如何做Pyt ...

  6. python pyecharts_基于Python的数据可视化库pyecharts介绍

    什么是pyecharts? pyecharts 是一个用于生成 Echarts 图表的类库. echarts 是百度开源的一个数据可视化 JS 库,主要用于数据可视化.pyecharts 是一个用于生 ...

  7. python 3d大数据可视化_基于Python的数据可视化库pyecharts介绍

    什么是pyecharts? pyecharts 是一个用于生成 Echarts 图表的类库. echarts 是百度开源的一个数据可视化 JS 库,主要用于数据可视化.pyecharts 是一个用于生 ...

  8. 基于python的数据建模与分析案例_基于案例详解Python数据分析与机器学习

    课程概述: 使用数据领域最主流语言Python及其分析与建模库作为核心武器.对于机器学习经典算法给出完整的原理推导并基于实例进行讲解,基于案例演示如何应用机器学习算法解决实际问题. 课程特色: 通俗易 ...

  9. 基于python的数据爬虫学习与体会

    文章目录 一.从Python编程基础中简述爬虫应用都会用到哪些pip模块以及对应的功能. pip install reqeusts pip install bs4 pip install pandas ...

最新文章

  1. 以太坊智能合约开发:让合约接受转账
  2. 将二叉树的叶子结点转换成单链表,并返回最左叶子结点的地址(链头)
  3. 计算机设备报废流程图,报废流程图.ppt
  4. Android如何回调编码后的音视频数据
  5. 海康相机回调方式理一下
  6. HDFView 把 JPG 图片转换成 HDF5 格式文件
  7. linux设计论文题目,计算机linux本科毕业论文题目
  8. Hackintool 3.4.7中文版 (黑苹果必备工具箱神器)
  9. 般若波罗蜜多心经(观音心经)注解
  10. Unity加载进度条
  11. 如何用建木CI更新七牛云CDN证书
  12. MySQL 查看当前数据库
  13. hexo+yilia添加隐藏左边栏目按钮
  14. 微信个人号机器人接口
  15. CSS 字体文本样式
  16. GP2Y1010AU0F使用心得
  17. 嘿,Logo,你应该是这个尺寸的!
  18. IOS H5点击穿透问题可以用fastclick.js解决
  19. Crowbar 使用教程
  20. 历年双十一网销销量。

热门文章

  1. 培训沙龙准备事项-看板记录
  2. Redis 分布式锁没这么简单,网上大多数都有 bug
  3. 亿级商城计价中心 - 从容应对复杂场景价格计算
  4. 获赞23w+在B站一夜爆火,大写的牛B!程序员进阶网盘资源(有链接和提取码)...
  5. 美团金融一面,二面后端Java面试分享!
  6. 你居然还不知道Mysql存储引擎InnoDB分为内存架构、磁盘架构?
  7. 微服务四大网关性能对比
  8. 国内外好用的协同办公软件有哪些?
  9. 分享5个我「 最死忠 」的Windows10软件
  10. Quartz.NET实际