Python机器学习实战-建立AdaBoost模型预测肾脏疾病(附源码和实现效果)

news/2025/2/25 16:18:04

实现功能

建立AdaBoost模型(集成学习)预测肾脏疾病

实现代码

python">
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
pd.set_option('display.max_columns', 26)

#==========================读取数据======================================
df = pd.read_csv("E:\数据杂坛\datasets\kidney_disease.csv")
df=pd.DataFrame(df)
pd.set_option('display.max_rows', None)
pd.set_option('display.width', None)
df.drop("id",axis=1,inplace=True)
print(df.head())
print(df.dtypes)
df["classification"] = df["classification"].apply(lambda x: x if x == "notckd" else "ckd")
# 分类型变量名
cat_cols = [col for col in df.columns if df[col].dtype == "object"]
# 数值型变量名
num_cols = [col for col in df.columns if df[col].dtype != "object"]

# ========================缺失值处理============================
def random_value_imputate(col):
    """
    函数:随机填充方法(缺失值较多的字段)
    """

    # 1、确定填充的数量;在取出缺失值随机选择缺失值数量的样本
    random_sample = df[col].dropna().sample(df[col].isna().sum())
    # 2、索引号就是原缺失值记录的索引号
    random_sample.index = df[df[col].isnull()].index
    # 3、通过loc函数定位填充
    df.loc[df[col].isnull(), col] = random_sample


def mode_impute(col):
    """
    函数:众数填充缺失值
    """
    # 1、确定众数
    mode = df[col].mode()[0]
    # 2、fillna函数填充众数
    df[col] = df[col].fillna(mode)

for col in num_cols:
    random_value_imputate(col)

for col in cat_cols:
    if col in ['rbc','pc']:
        # 随机填充
        random_value_imputate('rbc')
        random_value_imputate('pc')
    else:
        mode_impute(col)

# ======================特征编码============================
from sklearn.preprocessing import MinMaxScaler
mms = MinMaxScaler()
df[num_cols] = mms.fit_transform(df[num_cols])

from sklearn.preprocessing import LabelEncoder
led = LabelEncoder()
for col in cat_cols:
    df[col] = led.fit_transform(df[col])

print(df.head())

#===========================数据集划分===============================
X = df.drop("classification",axis=1)
y = df["classification"]
from sklearn.utils import shuffle
df = shuffle(df)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)

#===========================建模=====================================
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

def create_model(model):
    # 模型训练
    model.fit(X_train, y_train)
    # 模型预测
    y_pred = model.predict(X_test)
    # 准确率acc
    acc = accuracy_score(y_test, y_pred)
    # 混淆矩阵
    cm = confusion_matrix(y_test, y_pred)
    # 分类报告
    cr = classification_report(y_test, y_pred)

    print(f"Test Accuracy of {model} : {acc}")
    print(f"Confusion Matrix of {model}: \n{cm}")
    print(f"Classification Report of {model} : \n {cr}")

from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier()
ada = AdaBoostClassifier(base_estimator = dt)
create_model(ada)

实现效果

 

本人读研期间发表5篇SCI数据挖掘相关论文,现在某研究院从事数据挖掘相关科研工作,对数据挖掘有一定认知和理解,会结合自身科研实践经历不定期分享关于python机器学习、深度学习、数据挖掘基础知识与案例。

致力于只做原创,以最简单的方式理解和学习,关注我一起交流成长。

关注V订阅号:数据杂坛,即可在后台联系我获取相关数据集和源码,送有关数据分析、数据挖掘、机器学习、深度学习相关的电子书籍。


http://www.niftyadmin.cn/n/4927589.html

相关文章

Spring Initailizr--快速入门--SpringBoot的选择

😀前言 本篇博文是关于IDEA使用Spring Initializer快速创建Spring Boot项目的说明,希望能够帮助到您😊 🏠个人主页:晨犀主页 🧑个人简介:大家好,我是晨犀,希望我的文章可…

常见数据库批量插入,如何不插入重复数据?Mysql 4 种方式避免重复插入数据!

最常见的方式就是为字段设置主键或唯一索引,当插入重复数据时,抛出错误,程序终止,但这会给后续处理带来麻烦,因此需要对插入语句做特殊处理,尽量避开或忽略异常,下面我简单介绍一下,…

图的深度优先遍历和广度优先遍历

目录 图的创建和常用方法 深度优先遍历&#xff08;Depth First Search&#xff09; 广度优先遍历&#xff08;Broad First Search&#xff09; 图的创建和常用方法 //无向图 public class Graph {//顶点集合private ArrayList<String> vertexList;//存储对应的邻接…

Opencv项目实战:24 石头剪刀布

目录 0、项目介绍 1、效果展示 2、项目搭建 3、项目代码展示与部分讲解 pyzjr库

整理mongodb文档:改

个人博客 整理mongodb文档:改 求关注&#xff0c;求批评&#xff0c;求进步 文章概叙 本文主要讲的是mongodb的updateOne以及updateMany&#xff0c;主要还是在shell下进行操作&#xff0c;也讲解下主要的参数upsert以及更新的参数。 数据准备 本次需要准备的数据不是很多…

uniapp文件下载并预览

大概就是这样的咯&#xff0c;文件展示到页面上&#xff0c;点击文件下载并预览该文件&#xff1b; 通过点击事件handleDownLoad(file.path)&#xff0c;file.path为文件的地址&#xff1b; <view class"files"><view class"cont" v-for"(…

3.5 C++ 纯虚函数、抽象类 3.6 依赖倒转原则

纯虚函数 class A { public:virtual void print(){cout<<"A"<<endl;}virtual void test()0; //纯虚函数 }; 一个类内有纯虚函数&#xff0c;这个类就叫抽象类&#xff1b; 抽象类不能实例化&#xff1b; <java、python&#xff1a…

流量分析日志查看

一流量分析 buuctf wireshark 从题目出发&#xff0c;既然是上传登录信息&#xff0c;就直接过滤post请求&#xff0c;即搜索 http.request.methodPOST&#xff0c;因为上传用户登录信息使用的一定是http里的post方法 模式过滤 http.request.method “GET” http.request.…