本文為《Python機器學習及實踐:從零通往Kaggle競賽之路》一書學習筆記,歡迎與我交流數據挖掘、機器學習相關話題。
[完整代碼]:
所用到的數據:百度云鏈接 密碼:ao7w
數據集:
如下圖第一列為編號 第二、第三列為描述癌細胞的兩個特征,意為腫塊密度、細胞大小,第四列為細胞類別(0為惡性,1為良性)

數據集樣式
數據集中訓練集一共有524條樣本,測試集一共有175條樣本,一般記良性腫瘤樣本為正樣本,惡性腫瘤樣本為負樣本。
#讀取數據
train = pd.read_csv('../Datasets/Breast-Cancer/breast-cancer-train.csv')
test = pd.read_csv('../Datasets/Breast-Cancer/breast-cancer-test.csv')
#構建測試集訓練特征
test_positive = test.loc[test['Type'] == 1][['Clump Thickness','Cell Size']] #負樣本訓練特征
test_negative = test.loc[test['Type'] == 0][['Clump Thickness','Cell Size']] #正樣本訓練特征
其中測試集樣本中有118個惡性腫瘤,57個良性腫瘤,繪制測試集中正負樣本分布散點圖

測試集數據分布
#繪制正負樣本分布散點圖
plt.scatter(test_negative['Clump Thickness'],test_negative['Cell Size'],marker='o',s=200,c='red')
plt.scatter(test_positive['Clump Thickness'],test_positive['Cell Size'],marker='x',s=150,c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.show()
1.繪制一條隨機直線進行分類

隨機參數下的直線分類器
#隨機生成直線的參數
intercept = np.random.random([1])
coef = np.random.random([2])
lx = np.arange(0,12) #x軸
ly = (-intercept -lx * coef[0])/coef[1] #y軸 直線方程ax+by+c=0
#繪制一條隨機直線進行區(qū)分
plt.scatter(test_negative['Clump Thickness'],test_negative['Cell Size'],marker='o',s=200,c='red')
plt.scatter(test_positive['Clump Thickness'],test_positive['Cell Size'],marker='x',s=150,c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.plot(lx,ly,c='yellow')
plt.show()
2.使用邏輯回歸算法訓練前10條訓練樣本

使用前10條訓練樣本得到的分類直線
#使用邏輯回歸算法訓練前10條訓練樣本
from sklearn.linear_model import LogisticRegression
model = LogisticRegression() #生成模型
model.fit(train[['Clump Thickness','Cell Size']][:10],train['Type'][:10]) #訓練模型
print model.score(test[['Clump Thickness','Cell Size']],test['Type']) #預測并評價
#繪制使用邏輯回歸訓練前10條樣本得到的分類直線 正確率約為87%
#直線參數由算法生成
intercept = model.intercept_
coef = model.coef_[0,:]
lx = np.arange(0,12) #x軸
ly = (-intercept -lx * coef[0])/coef[1]
plt.scatter(test_negative['Clump Thickness'],test_negative['Cell Size'],marker='o',s=200,c='red')
plt.scatter(test_positive['Clump Thickness'],test_positive['Cell Size'],marker='x',s=150,c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.plot(lx,ly,c='green')
plt.show()
3.使用邏輯回歸算法訓練所有訓練樣本 正確率約為94%

使用所有訓練樣本得到的分類直線
#繪制使用邏輯回歸訓練全部樣本得到的分類直線
model = LogisticRegression()
model.fit(train[['Clump Thickness','Cell Size']],train['Type'])
print model.score(test[['Clump Thickness','Cell Size']],test['Type'])
intercept = model.intercept_
coef = model.coef_[0,:]
lx = np.arange(0,12) #x軸
ly = (-intercept -lx * coef[0])/coef[1]
plt.scatter(test_negative['Clump Thickness'],test_negative['Cell Size'],marker='o',s=200,c='red')
plt.scatter(test_positive['Clump Thickness'],test_positive['Cell Size'],marker='x',s=150,c='black')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.plot(lx,ly,c='blue')
plt.show()