《Python machine learning and practice》—— 良\恶性乳腺癌肿瘤预测
生活随笔
收集整理的這篇文章主要介紹了
《Python machine learning and practice》—— 良\恶性乳腺癌肿瘤预测
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數據集
良\惡性乳腺癌腫瘤預測數據集
代碼分析
第三方庫文件
from sklearn.linear_model import LogisticRegression #導入sklearn中的邏輯斯蒂回歸分類器 import matplotlib.pyplot as plt import pandas as pd import numpy as np都是在機器學習中常用的第三方庫。
導入文件
df_train=pd.read_csv(r'F:\code\AI\Python machine learning and practice\Datasets\Breast-Cancer\breast-cancer-train.csv') df_test=pd.read_csv(r'F:\code\AI\Python machine learning and practice\Datasets\Breast-Cancer\breast-cancer-test.csv')通過pandas的read_csv導入數據集。
確定正負分類樣本
df_test_nagative=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']]選取“Clump Thickness”與“Cell Size”作為特征,構件測試集中的正負分類樣本。
繪制圖形
#繪制良性腫瘤樣本點,標記為紅色的o plt.scatter(df_test_nagative['Clump Thickness'],df_test_nagative['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()numpy確定參數
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')利用numpy中的random函數隨機采樣直線的截距和系數。
訓練
lr=LogisticRegression(solver='liblinear')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,映射到2維平面上之后,應該是: ly=(-intercept-lx*coef[0])/coef[1]plt.plot(lx,ly,c='green')使用前10條訓練樣本學習直線的系數和截距。
plt.plot(lx,ly,c='green') plt.scatter(df_test_nagative['Clump Thickness'],df_test_nagative['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(solver='liblinear') #使用所有的訓練樣本學習直線的系數和截距 lr.fit(df_train[['Clump Thickness','Cell Size']],df_train['Type']) print('Testing accuracy(10 training samples):',lr.score(df_test[['Clump Thickness','Cell Size']],df_test['Type']))intercept=lr.intercept_ coef=lr.coef_[0,:] ly=(-intercept-lx*coef[0])/coef[1]plt.plot(lx,ly,c='blue') plt.scatter(df_test_nagative['Clump Thickness'],df_test_nagative['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()總結
以上是生活随笔為你收集整理的《Python machine learning and practice》—— 良\恶性乳腺癌肿瘤预测的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux基础 —— Linux终端命令
- 下一篇: PAT (Basic Level) Pr