数据集
代码分析
第三方库文件
from sklearn.linear_model import LogisticRegression
#导入sklearn中的逻辑斯蒂回归分类器
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
都是在机器学习中常用的第三方库。
导入文件
df_train=pd.read_csv(r'F:\code\AI\Python machine learning and practice\Datasets\Breast-Cancer\breast-cancer-train.csv')
df_test=pd.read_csv(r'F:\code\AI\Python machine learning and practice\Datasets\Breast-Cancer\breast-cancer-test.csv')
通过pandas的read_csv导入数据集。
确定正负分类样本
df_test_nagative=df_test.loc[df_test['Type']==0][['Clump Thickness','Cell Size']]
df_test_positive=df_test.loc[df_test['Type']==1][['Clump Thickness','Cell Size']]
选取“Clump Thickness”与“Cell Size”作为特征,构件测试集中的正负分类样本。
绘制图形
#绘制良性肿瘤样本点,标记为红色的o
plt.scatter(df_test_nagative['Clump Thickness'],df_test_nagative['Cell Size'],marker='o',s=200,c='red')
#绘制恶性肿瘤样本点,标记为黑色的×
plt.scatter(df_test_positive['Clump Thickness'],df_test_positive['Cell Size'],marker='x',s=150,c='black')
#绘制x、y轴的说明
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
#显示图
plt.show()
numpy确定参数
intercept=np.random.random([1])
coef=np.random.random([2])
lx=np.arange(0,12)
ly=(-intercept-lx*coef[0])/coef[1]
plt.plot(lx,ly,c='yellow')
利用numpy中的random函数随机采样直线的截距和系数。
训练
lr=LogisticRegression(solver='liblinear')
lr.fit(df_train[['Clump Thickness','Cell Size']][:10],df_train['Type'][:10])
print('Testing accuracy(10 training samples):',lr.score(df_test[['Clump Thickness','Cell Size']],df_test['Type']))
intercept=lr.intercept_
coef=lr.coef_[0,:]
# 原本这个分类面应该是lx*coef[0]+ly*coef[1]+intercept=0,映射到2维平面上之后,应该是:
ly=(-intercept-lx*coef[0])/coef[1]
plt.plot(lx,ly,c='green')
使用前10条训练样本学习直线的系数和截距。
plt.plot(lx,ly,c='green')
plt.scatter(df_test_nagative['Clump Thickness'],df_test_nagative['Cell Size'],marker='o',s=200,c='red')
plt.scatter(df_test_positive['Clump Thickness'],df_test_positive['Cell Size'],marker='x',s=150,c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.show()
再训练
lr=LogisticRegression(solver='liblinear')
#使用所有的训练样本学习直线的系数和截距
lr.fit(df_train[['Clump Thickness','Cell Size']],df_train['Type'])
print('Testing accuracy(10 training samples):',lr.score(df_test[['Clump Thickness','Cell Size']],df_test['Type']))
intercept=lr.intercept_
coef=lr.coef_[0,:]
ly=(-intercept-lx*coef[0])/coef[1]
plt.plot(lx,ly,c='blue')
plt.scatter(df_test_nagative['Clump Thickness'],df_test_nagative['Cell Size'],marker='o',s=200,c='red')
plt.scatter(df_test_positive['Clump Thickness'],df_test_positive['Cell Size'],marker='x',s=150,c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.show()