機器學習之良/惡性乳腺癌腫瘤預測
阿新 • • 發佈:2017-07-22
nan n) gin sample 通過 回歸 ipy read 數據集
知識點:
邏輯斯蒂回歸分類器
訓練數據集:https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data
數據預處理
打開ipython網頁解釋器
#導入模塊 import pandas as pd import numpy as np
#創建特征列表表頭 column_names = [‘Sample code number‘,‘Clump Thickness‘,‘Uniformity of Cell Size‘,‘Uniformity of Cell Shape‘,‘Marginal Adhesion‘,‘Single Epithelial Cell Size‘,‘Bare Nuclei‘,‘Bland Chromatin‘,‘Normal Nucleoli‘,‘Mitoses‘,‘Class‘] #使用pandas.read_csv函數從網上讀取數據集 data = pd.read_csv(‘https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data‘,names=column_names) #將?替換為標準缺失值表示 data = data.replace(to_replace=‘?‘,value = np.nan) #丟棄帶有缺失值的數據(只要有一個維度有缺失便丟棄) data = data.dropna(how=‘any‘) #查看data的數據量和維度 data.shape
維度打印信息為:
有683條數據,維度為11
如果用mac環境,在讀取網絡上數據集時候可能會報錯,解決方案,打開Finder,找到python解釋器,點擊安裝即可
處理後數據集如下:
由於原始數據沒有提供對應的測試樣本用於評估模型性能,這裏對帶標記的數據進行分割,25%作為測試集,其余作為訓練集
#使用sklearn.cross_validation裏的train_test_split模塊分割數據集 from sklearn.cross_validation import train_test_split #隨機采樣25%的數據用於測試,剩下的75%用於構建訓練集 X_train,X_test,y_train,y_test = train_test_split(data[column_names[1:10]],data[column_names[10]],test_size = 0.25,random_state = 33) #查看訓練樣本的數量和類別分布 y_train.value_counts()
#查看測試樣本的數量和類別分布 y_test.value_counts()
建立模型,預測數據
#從sklearn.preprocessing導入StandardScaler from sklearn.preprocessing import StandardScaler #從sklearn.linear_model導入LogisticRegression(邏輯斯蒂回歸) from sklearn.linear_model import LogisticRegression #從sklearn.linear_model導入SGDClassifier(隨機梯度參數) from sklearn.linear_model import SGDClassifier
#標準化數據,保證每個維度的特征數據方差為1,均值為,使得預測結果不會被某些過大的特征值而主導(在機器學習訓練之前, 先對數據預先處理一下, 取值跨度大的特征數據,
我們濃縮一下, 跨度小的括展一下, 使得他們的跨度盡量統一.) ss = StandardScaler() X_train = ss.fit_transform(X_train) X_test = ss.transform(X_test)
#初始化兩種模型 lr = LogisticRegression() sgdc = SGDClassifier()
#調用邏輯斯蒂回歸,使用fit函數訓練模型參數 lr.fit(X_train,y_train)
#使用訓練好的模型lr對x_test進行預測,結果儲存在變量lr_y_predict中 lr_y_predict = lr.predict(X_test)
#調用隨機梯度的fit函數訓練模型 sgdc.fit(X_train,y_train)
#使用訓練好的模型sgdc對X_test進行預測,結果儲存在變量sgdc_y_predict中 sgdc_y_predict = sgdc.predict(X_test)
下面查看兩種模型的預測結果
使用線性分類模型從事良/惡性腫瘤預測任務的性能分析
#從sklearn.metrics導入classification_report from sklearn.metrics import classification_report #使用邏輯斯蒂回歸模型自帶的評分函數score獲得模型在測試集上的準確性結果 print(‘Accuracy of LR Classifier:‘,lr.score(X_test,y_test)) #使用classification_report模塊獲得邏輯斯蒂模型其他三個指標的結果(召回率,精確率,調和平均數) print(classification_report(y_test,lr_y_predict,target_names=[‘Benign‘,‘Malignant‘]))
#使用隨機梯度下降模型自帶的評分函數score獲得模型在測試集上的準確性結果 print(‘Accuarcy of SGD Classifier:‘,sgdc.score(X_test,y_test)) ##使用classification_report模塊獲得隨機梯度下降模型其他三個指標的結果 print(classification_report(y_test,sgdc_y_predict,target_names=[‘Benign‘,‘Malignant‘]))
結論:通過比較,邏輯斯蒂模型比隨機梯度下降模型在測試集上表現有更高的準確性,因為邏輯斯蒂采用解析的方式精確計算模型參數,而隨機梯度下降采用估計值
特點分析:邏輯斯蒂對參數的計算采用精確解析的方法,計算時間長但是模型性能高,隨機梯度下降采用隨機梯度上升算法估計模型參數,計算時間短但產出的模型性能略低,一般而言,對於訓練數據規模在10萬量級以上的數據,考慮到時間的耗用,推薦使用隨機梯度算法
機器學習之良/惡性乳腺癌腫瘤預測