逻辑回归预测癌症分类
下面是用逻辑回归对癌症分类预测过程:
#1获取数据 读取的时候加上names #2数据处理 处理缺失值 #3数据集划分 #4特征工程 标准化 #5逻辑回归预估器 #6模型评估
import pandas as pd
import numpy as np
#1读取数据
column_name=['Sample code number','Clump Thickness','Uniformity of Cell Size','Uniformity of Cell Shape',
'Marginal Adhesion','Single Epithelial Cell Size','Bare Nuclei','Bland Chromatin','Normal Nucleoli',
'Mitoses','Class']
data=pd.read_csv("breast-cancer-wisconsin.data",names=column_name)
data.head()
#class是标签 2代表良性 4代表恶性
#2处理缺失值
#将里面的问号替换成nan
data=data.replace(to_replace="?",value=np.nan)
#将里面的缺失样本删除
data.dropna(inplace=True)
data.isnull().any()#查看是否还有缺失值
#3划分数据集
from sklearn.model_selection import train_test_split
#先筛选特征值和目标值
x=data.iloc[:,1:-1]#data里面所有的行,第一列到倒数第二列
y=data["Class"]#data里面class那一列
x_train,x_test,y_train,y_test=train_test_split(x,y)#这样就划分好了数据集
#4数据集标准化
from sklearn.preprocessing import StandardScaler
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)
#5模型训练
from sklearn.linear_model import LogisticRegression
estimator=LogisticRegression()
estimator.fit(x_train,y_train)
#逻辑回归的模型参数:回归系数和偏置
print("模型的回归系数:{}".format(estimator.coef_))
print("模型的回归偏置:{}".format(estimator.intercept_))
#查看精确率、召回率、F1-score
from sklearn.metrics import classification_report
print(classification_report(y_test,estimator.predict(x_test),labels=[2,4],target_names=["良性","恶心"]))
#计算AUC指标
from sklearn.metrics import roc_auc_score
y_true=np.where(y_test>3,1,0)
print("AUC的值:{}".format(roc_auc_score(y_true,estimator.predict(x_test))))
AUC的值:0.9956140350877193