机器学习之乳腺癌问题(SVM)
生活随笔
收集整理的這篇文章主要介紹了
机器学习之乳腺癌问题(SVM)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
機器學習之乳腺癌問題SVM
- 題目所需的代碼及數據
- 利用SVM建模
- SVM調參
題目所需的代碼及數據
鏈接:https://pan.baidu.com/s/1bS7Ku_PUfcimiVkmLz9Fzw
提取碼:0929
利用SVM建模
import matplotlib.pyplot as plt import pandas as pd import numpy as npfrom sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.model_selection import cross_val_score from sklearn.pipeline import make_pipeline from sklearn.feature_selection import SelectKBest, f_regression #特征選擇 import seaborn as sns #更改一下畫圖的要求 plt.style.use('fivethirtyeight') sns.set_style("white") plt.rcParams['figure.figsize'] = (8,4)data = pd.read_csv('data/data.csv')print("數據預處理:") # 劃分一下特征和標簽 X = data.iloc[:,2:32] # 特征 y = data.iloc[:,1] # 標簽 # 將類標簽從其原始字符串表示(M和B)轉換為整數 le = LabelEncoder() y = le.fit_transform(y) print(y)# 標準化數據(以0為中心并縮放以消除差異)。 scaler =StandardScaler() Xs = scaler.fit_transform(X)print("交叉驗證:(交叉驗證訓練集:測試集 = 7:3)") # 5.劃分測試集和訓練集 #stratify是為了保持split前類的分布 #將stratify=X就是按照X中的比例分配 #將stratify=y就是按照y中的比例分配 X_train, X_test, y_train, y_test = train_test_split(Xs, y, stratify=y,#Xs是特征 y是標簽test_size=0.3,random_state=33)# 6. 創建一個SVM分類器,并在70%的數據集上對其進行訓練。 clf = SVC(probability=True) clf.fit(X_train, y_train)#7. 對30%的持力測試樣本的預測精度進行分析。 classifier_score = clf.score(X_test, y_test)*100 print ('分類器準確度得分 {:03.2f}% \n'.format(classifier_score))print("使用SVC估計器獲得5倍交叉驗證分數的平均值") n_folds = 5 cv_error = np.average(cross_val_score(SVC(), Xs, y, cv=n_folds)) * 100 print('當n_folds={}-此分類器的交叉驗證精度分數為 {:.2f} % \n'.format(n_folds, cv_error))#特征選擇#clf2 = make_pipeline(SelectKBest(f_regression, k=3), # SVC(probability=True)) # 使用SVC估計器獲得3倍交叉驗證分數的平均值。 print("使用SVC估計器獲得3倍交叉驗證分數的平均值") n_folds = 3 cv_error = np.average(cross_val_score(SVC(), Xs, y, cv=n_folds)) * 100 print('當n_folds={}-此分類器的交叉驗證精度分數為 {:.2f} %\n'.format(n_folds, cv_error))def ROC_plot(y, yproba):from sklearn.metrics import roc_curve, aucplt.figure(figsize=(9,6))fpr, tpr, thresholds = roc_curve(y_test, probas_[:, 1])roc_auc = auc(fpr, tpr)plt.plot(fpr, tpr, lw=2, label='ROC fold (area = %0.2f)' % (roc_auc))plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Random')plt.xlim([-0.05, 1.05])plt.ylim([-0.05, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.show()plt.axes().set_aspect(1)#進行預測 預測概率 probas_ = clf.predict_proba(X_test) #畫圖 ROC_plot(y, probas_[:1])
SVM調參
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormapfrom sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.svm import SVCfrom sklearn import metrics, preprocessing from sklearn.metrics import classification_reportdata = pd.read_csv('data/data.csv')print("數據預處理:") # 劃分一下特征和標簽 X = data.iloc[:,2:32] # 特征 y = data.iloc[:,1] # 標簽 # 將類標簽從其原始字符串表示(M和B)轉換為整數 le = LabelEncoder() y = le.fit_transform(y) print(y)# 標準化數據(以0為中心并縮放以消除差異)。 scaler =StandardScaler() Xs = scaler.fit_transform(X)print("交叉驗證:(交叉驗證訓練集:測試集 = 7:3)") # 5.劃分測試集和訓練集 #stratify是為了保持split前類的分布 #將stratify=X就是按照X中的比例分配 #將stratify=y就是按照y中的比例分配 X_train, X_test, y_train, y_test = train_test_split(Xs, y, stratify=y,#Xs是特征 y是標簽test_size=0.3,random_state=33) # 6. 創建一個SVM分類器,并在70%的數據集上對其進行訓練。 clf = SVC(probability=True) clf.fit(X_train, y_train) y_pred = clf.fit(X_train, y_train).predict(X_test)#sklearn中的classification_report函數用于顯示主要分類指標的文本報告.在報告中顯示每個類的精確度,召回率,F1值等信息。 #主要參數: # 精度 記得 f1成績 支持數 #目標值。 #分類器返回的估計值。 #精確 #宏平均值 #加權平均 print(classification_report(y_test, y_pred ))## 繪圖混淆矩陣 cm = metrics.confusion_matrix(y_test, y_pred) fig, ax = plt.subplots(figsize=(5, 5)) ax.matshow(cm, cmap=plt.cm.Reds, alpha=0.3) for i in range(cm.shape[0]):for j in range(cm.shape[1]):ax.text(x=j, y=i,s=cm[i, j],va='center', ha='center') plt.xlabel('Predicted Values') plt.ylabel('Actual Values') plt.show()def decision_plot(X_train, y_train, n_neighbors, weights):h = .02 # step size in the meshXtrain = X_train[:, :2] #我們只采用前兩個特性。#================================================================ #創建顏色貼圖 #================================================================ cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])#================================================================ #我們創建了一個SVM實例并擬合數據。 #我們不縮放數據,因為我們想要繪制支持向量 #================================================================C = 1.0 # SVM regularization parametersvm = SVC(kernel='linear', random_state=0, gamma=0.1, C=C).fit(Xtrain, y_train) rbf_svc = SVC(kernel='rbf', gamma=0.7, C=C).fit(Xtrain, y_train) poly_svc = SVC(kernel='poly', degree=3, C=C).fit(Xtrain, y_train)#% matplotlib inline plt.rcParams['figure.figsize'] = (10, 6) plt.rcParams['axes.titlesize'] = 'large'# create a mesh to plot in x_min, x_max = Xtrain[:, 0].min() - 1, Xtrain[:, 0].max() + 1 y_min, y_max = Xtrain[:, 1].min() - 1, Xtrain[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),np.arange(y_min, y_max, 0.1))# title for the plots titles = ['SVC with linear kernel',#線性核函數'SVC with RBF kernel',#高斯核函數'SVC with polynomial (degree 3) kernel']#三次多項式核函數for i, clf in enumerate((svm, rbf_svc, poly_svc)):# Plot the decision boundary. For that, we will assign a color to each# point in the mesh [x_min, x_max]x[y_min, y_max].plt.subplot(2, 2, i + 1)plt.subplots_adjust(wspace=0.4, hspace=0.4)Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])# Put the result into a color plotZ = Z.reshape(xx.shape)plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)# Plot also the training pointsplt.scatter(Xtrain[:, 0], Xtrain[:, 1], c=y_train, cmap=plt.cm.coolwarm)plt.xlabel('radius_mean')plt.ylabel('texture_mean')plt.xlim(xx.min(), xx.max())plt.ylim(yy.min(), yy.max())plt.xticks(())plt.yticks(())plt.title(titles[i])plt.show()
總結
以上是生活随笔為你收集整理的机器学习之乳腺癌问题(SVM)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 笔记本小键盘怎么开启电脑小键盘如何
- 下一篇: lqb——修改数组