用python实现性别BMI对disease的预测划分训练80和测试集20在测试集上做疾病的预测需要使用随机森林算法选择评价预测效果的指标准确率和AUC绘图并评估预测效果
由于没有提供数据集,以下是基本的代码框架:
导入必要的库
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, roc_curve, auc import matplotlib.pyplot as plt
读取数据集
data = pd.read_csv('data.csv')
将性别转换为0和1
data['sex'] = data['sex'].apply(lambda x: 1 if x == 'Male' else 0)
划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(data[['sex', 'BMI']], data['disease'], test_size=0.2, random_state=42)
建立随机森林模型
rf = RandomForestClassifier(n_estimators=100, random_state=42) rf.fit(X_train, y_train)
在测试集上进行预测
y_pred = rf.predict(X_test)
计算准确率
accuracy = accuracy_score(y_test, y_pred) print('Accuracy:', accuracy)
计算AUC
fpr, tpr, thresholds = roc_curve(y_test, y_pred) roc_auc = auc(fpr, tpr) print('AUC:', roc_auc)
绘制ROC曲线
plt.figure() plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show()
评估预测效果
...根据实际情况进行评
原文地址: https://www.cveoy.top/t/topic/gFa3 著作权归作者所有。请勿转载和采集!