简单的线性分类器

一个简单的线性分类器

#coding=utf-8
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#线性分类的一种算法
from sklearn.linear_model import LogisticRegression

#读入训练集和测试集,csv类似于excel
df_train = pd.read_csv("breast-cancer-train.csv")
df_test = pd.read_csv("breast-cancer-train.csv")

#选出正样本集,负样本集,特征是Type值不同而已为它们加上属性,格式为属性,去掉Type
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']]

lr = LogisticRegression()
#选出10个样本进行训练
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']))

#绘图
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='o',
            s=150,
            c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')

#画出直线
intercept = lr.intercept_
coef = lr.coef_[0, :]
lx = np.arange(0, 12)
ly = (-intercept-lx*coef[0])/coef[1]
plt.plot(lx, ly, c="yellow")
plt.show()

猜你喜欢

转载自blog.csdn.net/pkuout/article/details/75307273
今日推荐