Logistic分类是一种很经典的线性分类器,现在参考《机器学习及实践》使用它来练习一下。案例就是很经典的“良/恶性乳腺癌预测”,使用的是python3.6,编辑器是pycharm,用的是anaconda的环境,各种包贼齐全贼方便。废话不多说,代码如下:
import pandas as pd
import numpy as np
#---------数据预处理
colume_names=['Sample code number','Clump Thickness','Uniformity of Cell Size','Uniformity of Cell Shape','Marginal Adhesion','Single Epithelial CellSize','Bare Nuclei','Bland Chromatin','Normal Nucleoli','Mitoses','Class']
data=pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data',names=colume_names)
data=data.replace(to_replace='?',value=np.nan)
data=data.dropna(how='any')#print(data.shape)
#---------训练集、测试集划分,随机选取,训练集占75%
fromsklearn.cross_validationimporttrain_test_split
X_train,X_test,y_train,y_test=train_test_split(data[colume_names[1:10]],data[colume_names[10]],test_size=0.25,random_state=33)print(y_train.value_counts())print(y_test.value_counts())
#random_state是指随机数生成种子
#---------训练模型
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
#---------标准化数据
ss=StandardScaler()
X_train=ss.fit_transform(X_train)
X_test=ss.transform(X_test)
#---------初始化LogisticRegression与训练模型
lr=LogisticRegression()
lr.fit(X_train,y_train)
lr_y_predict=lr.predict(X_test)
#--------性能分析
from sklearn.metrics import classification_report
print('Accurracy of LR Classifier:',lr.score(X_test,y_test))
xnfx=classification_report(y_test,lr_y_predict,target_names=['Benign','Malignant'])
print(xnfx)
性能分析如下: