對良/惡性腫瘤的預測python代碼實現

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LogisticRegression


df_train = pd.read_csv(r'E:\BaiduNetdiskDownload\Datasets\Breast-Cancer\breast-cancer-train.csv')#利用pandas讀入數據
df_test =pd.read_csv(r'E:\BaiduNetdiskDownload\Datasets\Breast-Cancer\breast-cancer-test.csv')


#選取ClumpThickness與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']]
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')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.show()
#利用numpy中的random函數隨機採樣直線的截距和係數
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')
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')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.show()


#利用sklearn中的LogisticRegression迴歸分類器
#使用前十個樣本進行訓練
lr = LogisticRegression()
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,在這裏使用ly = (-intyercept-lx*coef[0])/coef[1]
ly = (-intercept-lx*coef[0])/coef[1]
plt.plot(lx,ly,c='green')
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')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.show()
#使用所有數據訓練,學習直線的係數和截距
lr =LogisticRegression()
lr.fit(df_train[['Clump Thickness','Cell Size']],df_train['Type'])
print('Testing accuracy:',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,在這裏使用ly = (-intyercept-lx*coef[0])/coef[1]
ly = (-intercept-lx*coef[0])/coef[1]
plt.plot(lx,ly,c='blue')
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')
plt.xlabel('Clump Thickness')
plt.ylabel('Cell Size')
plt.show()
   
   
   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章