良/惡性腫瘤預測問題屬於典型的二分類問題,本文採用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_testdf_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並簡稱為pltimport 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 工具包 並命名為npimport 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 LogisticRegressionlr = 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()