Python机器学习-良/恶性肿瘤预测问题

良/恶性肿瘤预测问题属于典型的二分类问题,本文采用LR分类器来预测未知肿瘤患者的分类

import pandas as pd

# 调用pandas工具包的read_csv函数模块,传入训练文件地址参数,
# 获取返回数据并存在变量df_train、
df_train = pd.read_csv('E:\JavaCode\machinelearn\Datasets\Breast-Cancer\\breast-cancer-train.csv')

# 输入测试文件地址,返回数据存在df_test
df_test = pd.read_csv('E:\JavaCode\machinelearn\Datasets\Breast-Cancer\\breast-cancer-test.csv')

# 选取‘Clump Thickness’和 ‘Cell Size’作为特征值 ,构建测试集中的正负分类样本
df_test_negative = 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']]


#导入matplotlib工具包的pyplot并简称为plt
import matplotlib.pyplot as plt

# 定义绘制方法
def Print():
    # 绘制  良性肿瘤样本点,标记为红色
    plt.scatter(df_test_negative['Clump Thickness'], df_test_negative['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()

#画图
# Print()

这里写图片描述

#导入numpy 工具包 并命名为np
import numpy as np
#利用numpy的random函数随机采样直线的截距和系数
# np.random.random([1])生成一个[0,1)之间的随机浮点数, np.random.random([2])生成两个[0,1)之间的随机浮点数
intercept = np.random.random([1])
coep = np.random.random([2])
lx = np.arange(0,12)
ly = (-intercept - lx * coep[0]) / coep[1]
# 绘制一条随机直线
plt.plot(lx, ly, c='yellow')

# 画图
 Print()

这里写图片描述

#导入sklearn中的逻辑斯蒂回归分类器
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()

#使用前10条训练样本学习直线的系数和截距
lr.fit(df_train[['Clump Thickness', 'Cell Size']][:10], df_train['Type'][:10])
print('测试准确率:',lr.score(df_test[['Clump Thickness','Cell Size']],df_test['Type']))

结果 测试准确率: 0.8685714285714285

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')
Print()

这里写图片描述

lr = LogisticRegression()
lr.fit(df_train[['Clump Thickness', 'Cell Size']], df_train['Type'])
print('测试准确率:',lr.score(df_test[['Clump Thickness','Cell Size']],df_test['Type']))

测试准确率 0.9371428571428572

intercept = lr.intercept_
coef = lr.coef_[0, :]
ly = (-intercept - lx * coef[0])/coef[1]

# 画图
plt.plot(lx, ly, c='blue')
Print()

这里写图片描述

猜你喜欢

转载自blog.csdn.net/jyxmust/article/details/79116543