基于病理数据进行乳腺癌预测(良性2/恶性4),利用逻辑回归的算法构建模型,通过概率来预测
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report, roc_auc_score, roc_curve
数据加载处理
# 将标签结果由4,2,转化为1,0。根据情况而定,转成1和0为了按照逻辑回归的二分类0和1来分类
df[['Class']] = df[['Class']]/2 - 1
# 清除有缺失值数据
#1、先换成nan
df = df.replace("?",np.nan)
#2、再把nan进行drop删除
df = df.dropna(how="any")
数据的标签数量差距较大时,使用过采样处理,将数据类别调整平衡,比如444个数量和另一类239个
#DataFrame.sample n 要抽取的行数 frac 抽取比例 replace是否又放回采样
df1 = df1.sample(frac=(444-239)/239)
#把239乘上1.8577的比例,通过比例来准确复制,进行调整数量平衡
df = pd.concat([df,df1],axis=0)
标准化来进行防止过拟合,因为调整平衡的时候进行了过拟合的预处理调整
scaleCoder = StandardScaler()
std = scaleCoder.fit_transform(x)
x = pd.DataFrame(std)
#留出法
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
进行评估,测试模型评分
model=LogisticRegression(solver="sag",C=1.5,fit_intercept=True,max_iter=500,multi_class='multinomial')
#solver =sag 随机梯度下降, C正则化系数的倒数, fit_intercepet拟合截距 max_iter 最大迭代次数 culticlass,处理的属性数量
model.fit(x_train,y_train)
score = model.score(x_test,y_test)
print(score)
用混淆矩阵来评估模型预测能力
y_ = model.predict(x_test)#计算预测值
print(confusion_matrix(y_test, y_))#混淆矩阵
print(classification_report(y_test, y_))#分类报告,打印出各种评估指标,一般都要达到99.9····%
ROC曲线评估
fpr, tpr, th = roc_curve(y_test, y_)# fpr横坐标,tpr纵坐标,th阈值
plt.plot(fpr, tpr)
plt.xlabel('fpr')
plt.ylabel('tpr')
plt.grid()
plt.show()
AUC面积评分
print(roc_auc_score(y_test, y_))#auc面积
实验采用 UCI 数据集中的 Wisconsin 医学院的 William H.Wolberg 博士提供的乳腺 癌 的 数 据
样 本 。所有数据来自真实临床案例,每个案例有 10 个属性。其中前九个属性是检 测指标, 每个
属性值用 1 到 10 的整数表示, 1 表示检测指标最正常, 10 表示最不正常。 第十个属性是分类属
性, 指示该肿瘤是否为恶性。