如何给网站的关键词做排名,架设一个网站,网站建设需要租用什么科目,大宗现货交易平台#x1f935;♂️ 个人主页#xff1a;艾派森的个人主页 ✍#x1f3fb;作者简介#xff1a;Python学习者 #x1f40b; 希望大家多多支持#xff0c;我们一起进步#xff01;#x1f604; 如果文章对你有帮助的话#xff0c; 欢迎评论 #x1f4ac;点赞#x1f4… ♂️ 个人主页艾派森的个人主页 ✍作者简介Python学习者 希望大家多多支持我们一起进步 如果文章对你有帮助的话 欢迎评论 点赞 收藏 加关注 目录
1.项目背景
2.数据集介绍
3.技术工具
4.实验过程
4.1导入数据
4.2数据预处理
4.3数据可视化
4.4特征工程
4.5模型构建
源代码 1.项目背景 艾滋病Acquired Immunodeficiency SyndromeAIDS是一种由人类免疫缺陷病毒Human Immunodeficiency VirusHIV引起的免疫系统功能受损的严重疾病。艾滋病的流行给全球卫生健康带来了严重挑战特别是在一些发展中国家和弱势群体中。 艾滋病的研究和管理需要综合多方面的信息包括患者的个人特征、病毒的特性、医疗历史等。利用机器学习算法对艾滋病数据进行分析和建模有助于更好地理解该疾病的传播规律、风险因素以及预测患者的病情发展。Catboost算法作为一种擅长处理类别型特征的梯度提升树算法在艾滋病数据的分析与建模中具有一定的优势。 本研究旨在利用Catboost算法对艾滋病数据进行分析与建模并结合可视化技术探索艾滋病患者的特征与疾病发展之间的关系。通过这一研究可以为艾滋病的预防、诊断和治疗提供更加科学有效的支持和指导。
2.数据集介绍
本数据集来源于Kaggle数据集包含有关被诊断患有艾滋病的患者的医疗保健统计数据和分类信息。该数据集最初于 1996 年发布。
属性信息
time失败或审查的时间
trt治疗指标0 仅 ZDV1 ZDV ddI2 ZDV Zal3 仅 ddI
age基线年龄岁
wtkg基线时的体重公斤
hemo血友病0否1是
homo同性恋活动0否1是
drugs静脉注射药物使用史0否1是
karnof卡诺夫斯基分数范围为 0-100
oprior175 年前非 ZDV 抗逆转录病毒治疗0否1是
z30175之前30天的ZDV0否1是
preanti抗逆转录病毒治疗前 175 天
race种族0白人1非白人
gender性别0女1男
str2抗逆转录病毒史0未接触过1有经验
strat抗逆转录病毒病史分层1未接受过抗逆转录病毒治疗2 1 但 52周既往抗逆转录病毒治疗3 52周
symptom症状指标0无症状1症状
treat治疗指标0仅ZDV1其他
offrtrt96/-5周之前off-trt的指标0否1是
cd40基线处的 CD4
cd42020/-5 周时的 CD4
cd80基线处的 CD8
cd82020/-5 周时的 CD8
infected感染艾滋病0否1是
3.技术工具
Python版本:3.9
代码编辑器jupyter notebook
4.实验过程
4.1导入数据
首先导入本次实验用到的第三方库并加载数据集 查看数据大小 查看数据基本信息 查看数据描述性统计 4.2数据预处理
统计数据缺失值情况 可以发现原始数据集并不存在缺失值故不需要处理
统计重复值情况 可以发现原始数据集并存在重复值故不需要处理
4.3数据可视化 为了方便后面作图这里我们自定义一个画图函数
def mPlotter(r, c, size, _targets, text):bg #010108palette [#df5337, #d24644, #f7d340, #3339FF, #440a68, #84206b, #f1ef75, #fbbe23, #400a67]font ubuntufig plt.figure(figsizesize)fig.patch.set_facecolor(bg)grid fig.add_gridspec(r, c)grid.update(wspace0.5, hspace0.25)__empty_diff ((r * c) - 1) - len(_targets)axes []for i in range(r):for j in range(c):axes.append(fig.add_subplot(grid[i, j]))for idx, ax in enumerate(axes):ax.set_facecolor(bg) if idx 0:ax.spines[bottom].set_visible(False)ax.tick_params(leftFalse, bottomFalse)ax.set_xticklabels([])ax.set_yticklabels([])ax.text(0.5, 0.5,f{text},horizontalalignmentcenter,verticalalignmentcenter,fontsize18, fontweightbold,fontfamilyfont,color#fff)else:if (idx - 1) len(_targets):ax.set_title(_targets[idx - 1].capitalize(), fontsize14, fontweightbold, fontfamilyfont, color#fff)ax.grid(color#fff, linestyle:, axisy, zorder0, dashes(1,5))ax.set_xlabel()ax.set_ylabel()else:ax.spines[bottom].set_visible(False)ax.tick_params(leftFalse, bottomFalse)ax.set_xticklabels([])ax.set_yticklabels([])ax.spines[left].set_visible(False)ax.spines[top].set_visible(False)ax.spines[right].set_visible(False)def cb(ax):ax.set_xlabel()ax.set_ylabel()if __empty_diff 0:axes axes[:-1*__empty_diff]return axes, palette, cb 开始作图 4.4特征工程
拆分数据集为训练集和测试集 平衡数据集 数据标准化处理 4.5模型构建
首先找到catboost的最佳超参数! 使用超参数构建并训练模型打印模型的准确率和分类报告 将混淆矩阵可视化 最后再作出ROC曲线 源代码
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings,random,optuna
import plotly.express as px
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score,auc,roc_curve
from sklearn.preprocessing import MinMaxScaler
from imblearn.over_sampling import SMOTE
from sklearn.model_selection import train_test_split
from catboost import CatBoostClassifierplt.style.use(dark_background)
warnings.simplefilter(ignore, categoryFutureWarning)
ds pd.read_csv(AIDS_Classification.csv)
ds.head()
ds.shape
ds.info()
ds.describe(percentiles[0, .25, .30, .50, .75, .80, 1]).T.style.background_gradient(cmap inferno)
ds.isnull().sum()
ds.duplicated().sum()
def mPlotter(r, c, size, _targets, text):bg #010108palette [#df5337, #d24644, #f7d340, #3339FF, #440a68, #84206b, #f1ef75, #fbbe23, #400a67]font ubuntufig plt.figure(figsizesize)fig.patch.set_facecolor(bg)grid fig.add_gridspec(r, c)grid.update(wspace0.5, hspace0.25)__empty_diff ((r * c) - 1) - len(_targets)axes []for i in range(r):for j in range(c):axes.append(fig.add_subplot(grid[i, j]))for idx, ax in enumerate(axes):ax.set_facecolor(bg) if idx 0:ax.spines[bottom].set_visible(False)ax.tick_params(leftFalse, bottomFalse)ax.set_xticklabels([])ax.set_yticklabels([])ax.text(0.5, 0.5,f{text},horizontalalignmentcenter,verticalalignmentcenter,fontsize18, fontweightbold,fontfamilyfont,color#fff)else:if (idx - 1) len(_targets):ax.set_title(_targets[idx - 1].capitalize(), fontsize14, fontweightbold, fontfamilyfont, color#fff)ax.grid(color#fff, linestyle:, axisy, zorder0, dashes(1,5))ax.set_xlabel()ax.set_ylabel()else:ax.spines[bottom].set_visible(False)ax.tick_params(leftFalse, bottomFalse)ax.set_xticklabels([])ax.set_yticklabels([])ax.spines[left].set_visible(False)ax.spines[top].set_visible(False)ax.spines[right].set_visible(False)def cb(ax):ax.set_xlabel()ax.set_ylabel()if __empty_diff 0:axes axes[:-1*__empty_diff]return axes, palette, cb
target infected
cont_cols [time, age, wtkg, preanti, cd40, cd420, cd80, cd820]
dis_cols list(set(ds.columns) - set([*cont_cols, target]))
len(cont_cols), len(dis_cols)
axes, palette, cb mPlotter(1, 2, (20, 5), [target], Count Of\nInfected Variable\n______________)
sns.countplot(xds[target], ax axes[1], colorpalette[0])
cb(axes[1])
axes, palette, cb mPlotter(3, 3, (20, 20), cont_cols, KDE Plot of\nContinuous Variables\n________________)
for col, ax in zip(cont_cols, axes[1:]):sns.kdeplot(datads, xcol, axax, huetarget, palettepalette[1:3], alpha.5, linewidth0, fillTrue)cb(ax)
axes, palette, cb mPlotter(3, 3, (20, 20), cont_cols, Boxen Plot of\nContinuous Variables\n________________)
for col, ax in zip(cont_cols, axes[1:]):sns.boxenplot(datads, ycol, axax, palette[palette[random.randint(0, len(palette)-1)]])cb(ax)
axes, palette, cb mPlotter(5, 3, (20, 20), dis_cols, Countplot of\nDiscrete Variables\n________________)
for col, ax in zip(dis_cols, axes[1:]):sns.countplot(xds[col], ax ax, hueds[target], palettepalette[6:8])cb(ax)
ax px.scatter_3d(ds, xage, ywtkg, ztime, template plotly_dark, colorinfected)
ax.show()
ax px.scatter_3d(ds, xpreanti, ycd40, zcd420, template plotly_dark, colorinfected)
ax.show()
ax px.scatter_3d(ds, xpreanti, ycd80, zcd820, template plotly_dark, colorinfected)
ax.show()
fig plt.figure(figsize(25, 8))
gs fig.add_gridspec(1, 1)
gs.update(wspace0.3, hspace0.15)
ax fig.add_subplot(gs[0, 0])
ax.set_title(Correlation Matrix, fontsize28, fontweightbold, fontfamilyserif, color#fff)
sns.heatmap(ds[cont_cols].corr().transpose(), masknp.triu(np.ones_like(ds[cont_cols].corr().transpose())), fmt.1f, annotTrue, cmapBlues)
plt.show()
# 拆分数据集为训练集和测试集
x_train, x_test, y_train, y_test train_test_split(ds.iloc[:,:-1], ds.iloc[:, -1], random_state3, train_size.7)
x_train.shape, y_train.shape, x_test.shape, y_test.shape
# 平衡数据集
smote SMOTE(random_state 14)
x_train, y_train smote.fit_resample(x_train, y_train)
x_train.shape, y_train.shape, x_test.shape, y_test.shape
# 数据标准化处理
x_train MinMaxScaler().fit_transform(x_train)
x_test MinMaxScaler().fit_transform(x_test)
# 找到catboost的最佳超参数!
def objective(trial):params {iterations: trial.suggest_int(iterations, 100, 1000),learning_rate: trial.suggest_loguniform(learning_rate, 0.01, 0.5),depth: trial.suggest_int(depth, 1, 12),l2_leaf_reg: trial.suggest_loguniform(l2_leaf_reg, 1e-3, 10.0),border_count: trial.suggest_int(border_count, 1, 255),thread_count: -1,loss_function: MultiClass,eval_metric: Accuracy,verbose: False}model CatBoostClassifier(**params)model.fit(x_train, y_train, eval_set(x_test, y_test), verboseFalse, early_stopping_rounds20)y_pred model.predict(x_test)accuracy accuracy_score(y_test, y_pred)return accuracystudy optuna.create_study(directionmaximize)
study.optimize(objective, n_trials50, show_progress_barTrue)
# 初始化模型并使用前面的最佳超参数
model CatBoostClassifier(verbose0, random_state3,**study.best_params
)
# 训练模型
model.fit(x_train, y_train)
# 预测
y_pred model.predict(x_test)
# 打印模型评估指标
print(模型准确率,accuracy_score(y_test,y_pred))
print (classification_report(y_pred, y_test))
plt.subplots(figsize(20, 6))
sns.heatmap(confusion_matrix(y_pred, y_test), annot True, fmtd, cmapBlues, linewidths.5)
plt.show()
# 画出ROC曲线
y_prob model.predict_proba(x_test)[:,1]
false_positive_rate, true_positive_rate, thresholds roc_curve(y_test, y_prob)
roc auc(false_positive_rate, true_positive_rate)
plt.title(ROC)
plt.plot(false_positive_rate,true_positive_rate, colorred,label AUC %0.2f % roc)
plt.legend(loc lower right)
plt.plot([0, 1], [0, 1],linestyle--)
plt.axis(tight)
plt.ylabel(True Positive Rate)
plt.xlabel(False Positive Rate)
plt.show()
# 模型预测
res pd.DataFrame()
res[真实值] y_test
res[预测值] y_pred
res.sample(10)资料获取更多粉丝福利关注下方公众号获取