[Kaggle] Heart Disease Prediction

文章目录

    • 1. 数据探索
    • 2. 特征处理管道
    • 3. 训练模型
    • 4. 预测

kaggle项目地址

1. 数据探索

import pandas as pd
train = pd.read_csv('./train.csv')
test = pd.read_csv('./test.csv')train.info()
test.info()
abs(train.corr()['target']).sort_values(ascending=False)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 241 entries, 0 to 240
Data columns (total 14 columns):#   Column    Non-Null Count  Dtype  
---  ------    --------------  -----  0   age       241 non-null    int64  1   sex       241 non-null    int64  2   cp        241 non-null    int64  3   trestbps  241 non-null    int64  4   chol      241 non-null    int64  5   fbs       241 non-null    int64  6   restecg   241 non-null    int64  7   thalach   241 non-null    int64  8   exang     241 non-null    int64  9   oldpeak   241 non-null    float6410  slope     241 non-null    int64  11  ca        241 non-null    int64  12  thal      241 non-null    int64  13  target    241 non-null    int64  
dtypes: float64(1), int64(13)
memory usage: 26.5 KB

训练数据241条,13个特征(全部为数字特征),标签为 target

  • 特征与 标签 的相关系数
target      1.000000
cp          0.457688
exang       0.453784
ca          0.408107
thalach     0.390346
oldpeak     0.389787
slope       0.334991
thal        0.324611
sex         0.281272
age         0.242338
restecg     0.196018
chol        0.170592
trestbps    0.154086
fbs         0.035450
Name: target, dtype: float64
  • 查看特征的值
for col in train.columns:print(col)print(train[col].unique())
age
[37 41 56 44 52 57 54 48 64 50 66 43 69 42 61 71 59 65 46 51 45 47 53 6358 35 62 29 55 60 68 39 34 67 74 49 76 70 38 77 40]
sex
[1 0]
cp
[2 1 0 3]
trestbps
[130 140 120 172 150 110 160 125 142 135 155 104 138 128 108 134 122 115118 100 124  94 112 102 152 101 132 178 129 136 106 156 170 117 145 180165 192 144 123 126 154 148 114 164]
chol
[250 204 294 263 199 168 239 275 211 219 226 247 233 243 302 212 177 273304 232 269 360 308 245 208 235 257 216 234 141 252 201 222 260 303 265309 186 203 183 220 209 258 227 261 221 205 318 298 277 197 214 248 255207 223 160 394 315 270 195 240 196 244 254 126 313 262 215 193 271 268267 210 295 178 242 180 228 149 253 342 157 175 286 229 256 224 206 230276 353 225 330 290 266 172 305 188 282 185 326 274 164 307 249 341 407217 174 281 288 289 246 322 299 300 293 184 409 283 259 200 327 237 319166 218 335 169 187 176 241 264 236]
fbs
[0 1]
restecg
[1 0 2]
thalach
[187 172 153 173 162 174 160 139 144 158 114 171 151 179 178 137 157 140152 170 165 148 142 180 156 115 175 186 185 159 130 190 132 182 143 163147 154 202 161 166 164 184 122 168 169 138 111 145 194 131 133 155 167192 121  96 126 105 181 116 149 150 125 108 129 112 128 109 113  99 177141 146 136 127 103 124  88 120 195  95 117  71 118 134  90 123]
exang
[0 1]
oldpeak
[3.5 1.4 1.3 0.  0.5 1.6 1.2 0.2 1.8 2.6 1.5 0.4 1.  0.8 3.  0.6 2.4 0.11.9 4.2 1.1 2.  0.7 0.3 0.9 2.3 3.6 3.2 2.2 2.8 3.4 6.2 4.  5.6 2.1 4.4]
slope
[0 2 1]
ca
[0 2 1 4 3]
thal
[2 3 0 1]
target
[1 0]
  • 一些特征不能用大小来度量,将其转为 分类变量(string 类型,后序onehot编码)
object_cols = ['cp', 'restecg', 'slope', 'ca', 'thal']
def strfeatures(data):data_ = data.copy()for col in object_cols:data_[col] = data_[col].astype(str)return data_train_ = strfeatures(train)
test_ = strfeatures(test)

2. 特征处理管道

  • 数字特征、文字特征分离
def num_cat_split(data):s = (data.dtypes == 'object')object_cols = list(s[s].index)num_cols = list(set(data.columns)-set(object_cols))return num_cols, object_colsnum_cols, object_cols = num_cat_split(train_)
num_cols.remove('target')
  • 抽取部分数据作为本地验证
# 本地测试,分成抽样,分割训练集,验证集
from sklearn.model_selection import StratifiedShuffleSplit
splt = StratifiedShuffleSplit(n_splits=1,test_size=0.2,random_state=1)
for train_idx, valid_idx in splt.split(train_, train_['target']):train_part = train_.loc[train_idx]valid_part = train_.loc[valid_idx]train_part_y = train_part['target']
valid_part_y = valid_part['target']
train_part = train_part.drop(['target'], axis=1)
valid_part = valid_part.drop(['target'], axis=1)
  • 数据处理管道
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.pipeline import Pipeline
from sklearn.pipeline import FeatureUnion
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputerclass DataFrameSelector(BaseEstimator, TransformerMixin):def __init__(self, attribute_name):self.attribute_name = attribute_namedef fit(self, X, y=None):return selfdef transform(self, X):return X[self.attribute_name].valuesnum_pipeline = Pipeline([('selector', DataFrameSelector(num_cols)),# ('imputer', SimpleImputer(strategy='median')),# ('std_scaler', StandardScaler()),
])cat_pipeline = Pipeline([('selector', DataFrameSelector(object_cols)),('cat_encoder', OneHotEncoder(sparse=False, handle_unknown='ignore'))
])full_pipeline = FeatureUnion(transformer_list=[('num_pipeline', num_pipeline),('cat_pipeline', cat_pipeline)
])

3. 训练模型

# 本地测试
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import Perceptron
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCVrf = RandomForestClassifier()
knn = KNeighborsClassifier()
lr = LogisticRegression()
svc = SVC()
gbdt = GradientBoostingClassifier()
perceptron = Perceptron()models = [perceptron, knn, lr, svc, rf, gbdt]
param_grid_list = [# perceptron[{'model__max_iter' : [10000, 5000]}],# knn[{'model__n_neighbors' : [3,5,10,15,35],'model__leaf_size' : [3,5,10,20,30,40,50]}],# lr[{'model__penalty' : ['l1', 'l2'],'model__C' : [0.05, 0.1, 0.2, 0.5, 1, 1.2],'model__max_iter' : [50000]}],# svc[{'model__degree' : [3, 5, 7],'model__C' : [0.2, 0.5, 1, 1.2, 1.5],'model__kernel' : ['rbf', 'sigmoid', 'poly']}],# rf[{#     'preparation__num_pipeline__imputer__strategy': ['mean', 'median', 'most_frequent'],'model__n_estimators' : [100,200,250,300,350],'model__max_features' : [5,8, 10, 12, 15, 20, 30, 40, 50],'model__max_depth' : [3,5,7]}],# gbdt[{'model__learning_rate' : [0.02, 0.05, 0.1, 0.2],'model__n_estimators' : [30, 50, 100, 150],'model__max_features' : [5, 8, 10,20,30,40],'model__max_depth' : [3,5,7],'model__min_samples_split' : [10, 20,40],'model__min_samples_leaf' : [5,10,20],'model__subsample' : [0.5, 0.8, 1]}],
]for i, model in enumerate(models):pipe = Pipeline([('preparation', full_pipeline),('model', model)])grid_search = GridSearchCV(pipe, param_grid_list[i], cv=3,scoring='accuracy', verbose=2, n_jobs=-1)grid_search.fit(train_part, train_part_y)print(grid_search.best_params_)final_model = grid_search.best_estimator_pred = final_model.predict(valid_part)print('accuracy score: ', accuracy_score(valid_part_y, pred))
Fitting 3 folds for each of 2 candidates, totalling 6 fits
{'model__max_iter': 10000}
accuracy score:  0.4489795918367347Fitting 3 folds for each of 35 candidates, totalling 105 fits
{'model__leaf_size': 3, 'model__n_neighbors': 3}
accuracy score:  0.5306122448979592Fitting 3 folds for each of 12 candidates, totalling 36 fits
{'model__C': 0.1, 'model__max_iter': 50000, 'model__penalty': 'l2'}
accuracy score:  0.8979591836734694Fitting 3 folds for each of 45 candidates, totalling 135 fits
{'model__C': 1, 'model__degree': 5, 'model__kernel': 'poly'}
accuracy score:  0.6326530612244898Fitting 3 folds for each of 135 candidates, totalling 405 fits
{'model__max_depth': 5, 'model__max_features': 5, 
'model__n_estimators': 250}
accuracy score:  0.8775510204081632Fitting 3 folds for each of 7776 candidates, totalling 23328 fits
{'model__learning_rate': 0.05, 'model__max_depth': 7, 
'model__max_features': 20, 'model__min_samples_leaf': 10, 
'model__min_samples_split': 40, 'model__n_estimators': 150, 
'model__subsample': 0.5}
accuracy score:  0.8163265306122449

LR,RF,GBDT 表现较好

4. 预测

# 全量数据训练,提交测试
# 采用随机参数搜索
y_train = train_['target']
X_train = train_.drop(['target'], axis=1)
X_test = test_from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
import numpy as npselect_model = [lr, rf, gbdt]
name = ['lr', 'rf', 'gbdt']
param_distribs = [# lr[{'model__penalty' : ['l1', 'l2'],'model__C' : np.linspace(0.01, 0.5, 10),'model__max_iter' : [50000]}],# rf[{#     'preparation__num_pipeline__imputer__strategy': ['mean', 'median', 'most_frequent'],'model__n_estimators' : randint(low=50, high=500),'model__max_features' : randint(low=3, high=30),'model__max_depth' : randint(low=2, high=20)}],# gbdt[{'model__learning_rate' : np.linspace(0.01, 0.3, 10),'model__n_estimators' : randint(low=30, high=500),'model__max_features' : randint(low=5, high=50),'model__max_depth' : randint(low=3, high=20),'model__min_samples_split' : randint(low=10, high=100),'model__min_samples_leaf' : randint(low=3, high=50),'model__subsample' : np.linspace(0.5, 1.5, 10)}],
]for i, model in enumerate(select_model):pipe = Pipeline([('preparation', full_pipeline),('model', model)])rand_search = RandomizedSearchCV(pipe, param_distributions=param_distribs[i], cv=5,n_iter=1000, scoring='accuracy', verbose=2, n_jobs=-1)rand_search.fit(X_train, y_train)print(rand_search.best_params_)final_model = rand_search.best_estimator_pred = final_model.predict(X_test)print(model,"\nFINISH !!!")res = pd.DataFrame()res['Id'] = range(1,63,1)res['Prediction'] = predres.to_csv('{}_pred.csv'.format(name[i]), index=False)

测试效果如下。
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/474213.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python进程的回收—wait

1.os.wait()回收资源 os.wait()方法用来回收子进程占用的资源&#xff1a; import os import time ret os.fork() # 创建新的进程 一次调用&#xff0c;两次返回 if ret 0: # 子进程执行 # 子进程拿到的返回值是0 print("子进程&#xff1a;pid%d, ppid%d" % (…

Oracle数据库逻辑存储结构管理相关问题与解决

我们在Mysql数据库中&#xff0c;一般是登入进去一个数据库&#xff0c;紧接着就创建数据库实例&#xff1a;create databse XXX;但是在Oracle数据库就不行。在数据库连接过程中老是报监听失败的错误。在备份表空间的时候&#xff0c;设置表空间为备份模式&#xff0c;它提示我…

Python调用C的方法

参考&#xff1a;http://www.cnblogs.com/fxjwind/archive/2011/07/05/2098636.html http://amazingjxq.com/2012/01/09/python%E8%B0%83%E7%94%A8c%E5%87%BD%E6%95%B0/>>>cd /home/jxq/code/gcc -fPIC -shared bob_hash.c -o bob_hash.so然后在python里面用ctypes加载…

01.神经网络和深度学习 W2.神经网络基础

文章目录1. 二分类2. 逻辑回归3. 逻辑回归损失函数4. 梯度下降5. 导数6. 计算图导数计算7. 逻辑回归中的梯度下降8. m个样本的梯度下降9. 向量化10. 向量化的更多例子11. 向量化 logistic 回归12. 向量化 logistic 回归梯度输出13. numpy 广播机制14. 关于 python / numpy 向量…

python中的孤儿进程

1.子进程未运行完父进程就结束运行退出&#xff0c;留下来的子进程就是孤儿进程 2.父进程结束退出&#xff0c;子进程会被继父收回&#xff0c;通常是int进程&#xff08;pid为1&#xff09;无危害 import os import time ret os.fork() # 创建新的进程 一次调用&#xff0…

Oracle数据库物理存储结构管理遇到的问题与解决

问题一&#xff1a;当我创建一个重做日志文件放入重做日志文件组中的时候&#xff0c;查询数据字典发现新创建的重做日志文件的状态为“不合法”。 解决方案&#xff1a; 通过查阅相关资料了解到 新建的重做日志文件组成员状态为INVALID,这是由于新建的成员文件还没有被…

实例讲解hadoop中的map/reduce查询(python语言实现)

条件&#xff0c;假设你已经装好了hadoop集群&#xff0c;配好了hdfs并可以正常运行。 $hadoop dfs -ls /data/dw/explorerFound 1 itemsdrwxrwxrwx - rsync supergroup 0 2011-11-30 01:06 /data/dw/explorer/20111129$ hadoop dfs -ls /data/dw/explo…

python中僵尸进程

⼦进程运⾏完成&#xff0c;但是⽗进程迟迟没有进⾏回收&#xff0c;此时⼦进程实际上并没有退出&#xff0c;其仍然占⽤着系统资源&#xff0c;这样的⼦进程称为僵⼫进程。 因为僵⼫进程的资源⼀直未被回收&#xff0c;造成了系统资源的浪费&#xff0c;过多的僵⼫进程将造成…

01.神经网络和深度学习 W3.浅层神经网络

文章目录1. 神经网络概览2. 神经网络的表示3. 神经网络的输出4. 多样本向量化5. 激活函数6. 为什么需要 非线性激活函数7. 激活函数的导数8. 随机初始化作业参考&#xff1a; 吴恩达视频课 深度学习笔记 1. 神经网络概览 xW[1]b[1]}⟹z[1]W[1]xb[1]⟹a[1]σ(z[1])\left.\begin…

多进程修改全局变量

多进程中&#xff0c;每个进程中所有数据&#xff08;包括全局变量&#xff09;都各有拥有⼀份&#xff0c;互不影响 (读时共享&#xff0c;写时复制) import os import time num 100 ret os.fork() # 创建新的进程 一次调用&#xff0c;两次返回 if ret 0: # 子进程…

多进程模块multiprocessing

multiprocessing模块就是跨平台版本的多进程模块&#xff0c;提供了⼀个Process类来代表一个进程对象 创建⼦进程时&#xff0c;只需要传⼊⼀个执⾏函数和函数的参数&#xff0c;创建⼀个 Process实例&#xff0c;⽤start&#xff08;&#xff09;方法启动 &#xff0c;join()…

01.神经网络和深度学习 W2.神经网络基础(作业:逻辑回归 图片识别)

文章目录编程题 11. numpy 基本函数1.1 编写 sigmoid 函数1.2 编写 sigmoid 函数的导数1.3 reshape操作1.4 标准化1.5 广播机制2. 向量化2.1 L1\L2损失函数编程题 2. 图片&#x1f431;识别1. 导入包2. 数据预览3. 算法的一般结构4. 建立算法4.1 辅助函数4.2 初始化参数4.3 前向…

PL/SQL程序设计以及安全管理实验遇到的问题及解决

问题一&#xff1a;当我书写PL/SQL语句调用所创建的函数时&#xff0c;报“此范围不存在名为XXX函数名”的错误。 解决&#xff1a; 我通过查阅相关资料&#xff0c;了解到&#xff1a;这种情况主要是调用的函数的参数或者函数名书写错误&#xff0c; 然而&#xff0c;我经过仔…

PowerDesigner使用教程 —— 概念数据模型 (转)

一、概念数据模型概述 概念数据模型也称信息模型&#xff0c;它以实体&#xff0d;联系(Entity-RelationShip,简称E-R)理论为基础&#xff0c;并对这一理论进行了扩充。它从用户的观点出发对信息进行建模&#xff0c;主要用于数据库的概念级设计。 通常人们先将现实世界抽…

进程的创建-Process⼦类

from multiprocessing import Process&#xff08;P必须大写 import os import time classSubProcess(Process): """创建Process的子类""" def __init__(self, num, a): super(SubProcess, self).__init__() # 执行父类Process默认的初始化方法…

阿里云 超级码力在线编程大赛初赛 第1场(第245名)

文章目录1. 比赛结果2. 题目1. 树木规划2. 正三角形拼接3. 大楼间穿梭4. 对称前后缀1. 比赛结果 通过了 3 题&#xff0c;第245名&#xff0c;进入复赛了&#xff0c;收获 T恤 一件&#xff0c;哈哈。 2. 题目 1. 树木规划 题目链接 描述 在一条直的马路上&#xff0c;…

python中的进程池Pool

初始化Pool时&#xff0c;可以指定⼀个最大进程池&#xff0c;当有新进程提交时&#xff0c;如果池还没有满&#xff0c;那么就会创建新进程请求&#xff1b;但如果池中达到最大值&#xff0c;那么就会等待&#xff0c;待池中有进程结束&#xff0c;新进程来执行。 非阻塞式&a…

AS3.0面向对象的写法,类和实例

package /*package是包路径&#xff0c;例如AS文件在ActionScript文件夹下&#xff0c;此时路径应为package ActionScript。必须有的。package中只能有一个class&#xff0c;在一个AS文件中可以有若干个package*/ {public class hello /*类的名字*/{public var helloString:Str…

小小算法题(CCF)

题目 淘金 题目描述 在一片n*m的土地上&#xff0c;每一块1*1的区域里都有一定数量的金子。这一天&#xff0c;你到这里来淘金&#xff0c;然而当地人告诉你&#xff0c;如果你要挖(x, y)区域的金子&#xff0c;就不能挖(x-1&#xff0c;y),(x1, y)以及横坐标为y-1和y1的金…