• sklearn机器学习——day08


    SVC在非线性数据上的推广 

    为了能够找出非线性数据的线性决策边界,我们需要将数据从原始的空间 投射到新空间 中

    非线性SVM的损失函数的初始形态为: 

     非线性SVM的拉格朗日函数和拉格朗日对偶函数也可得:

    最终的决策函数

     

    重要参数kernel

    而解决这些问题的数学方式,叫做“核技巧”(Kernel Trick),是一种能够使用数据原始空间中的向量计算来表示 升维后的空间中的点积结果的数学方式。具体表现为, 。而这个原始空间中的点积 函数 ——核函数

     案例:如何选取最佳核函数  

    探索核函数在不同数据集上的表现

    1. #导入所需的库和模块
    2. import numpy as np
    3. import matplotlib.pyplot as plt
    4. from matplotlib.colors import ListedColormap
    5. from sklearn import svm
    6. from sklearn.datasets import make_circles, make_moons, make_blobs,make_classification
    7. #创建数据集,定义核函数的选择
    8. n_samples = 100
    9. datasets = [
    10. make_moons(n_samples=n_samples, noise=0.2, random_state=0),
    11. make_circles(n_samples=n_samples, noise=0.2, factor=0.5, random_state=1),
    12. make_blobs(n_samples=n_samples, centers=2, random_state=5),
    13. make_classification(n_samples=n_samples,n_features =
    14. 2,n_informative=2,n_redundant=0, random_state=5)
    15. ]
    16. Kernel = ["linear","poly","rbf","sigmoid"]
    17. #四个数据集分别是什么样子呢?
    18. for X,Y in datasets:
    19. plt.figure(figsize=(5,4))
    20. plt.scatter(X[:,0],X[:,1],c=Y,s=50,cmap="rainbow")
    21. #构建子图
    22. nrows=len(datasets)
    23. ncols=len(Kernel) + 1
    24. fig, axes = plt.subplots(nrows, ncols,figsize=(20,16))
    25. #开始进行子图循环
    26. #第一层循环:在不同的数据集中循环
    27. for ds_cnt, (X,Y) in enumerate(datasets):
    28. #在图像中的第一列,放置原数据的分布
    29. ax = axes[ds_cnt, 0]
    30. if ds_cnt == 0:
    31. ax.set_title("Input data")
    32. ax.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,edgecolors='k')
    33. ax.set_xticks(())
    34. ax.set_yticks(())
    35. #第二层循环:在不同的核函数中循环
    36. #从图像的第二列开始,一个个填充分类结果
    37. for est_idx, kernel in enumerate(Kernel):
    38. #定义子图位置
    39. ax = axes[ds_cnt, est_idx + 1]
    40. #建模
    41. clf = svm.SVC(kernel=kernel, gamma=2).fit(X, Y)
    42. score = clf.score(X, Y)
    43. #绘制图像本身分布的散点图
    44. ax.scatter(X[:, 0], X[:, 1], c=Y
    45. ,zorder=10
    46. ,cmap=plt.cm.Paired,edgecolors='k')
    47. #绘制支持向量
    48. ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=50,
    49. facecolors='none', zorder=10, edgecolors='k')
    50. #绘制决策边界
    51. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    52. y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    53. #np.mgrid,合并了我们之前使用的np.linspace和np.meshgrid的用法
    54. #一次性使用最大值和最小值来生成网格
    55. #表示为[起始值:结束值:步长]
    56. #如果步长是复数,则其整数部分就是起始值和结束值之间创建的点的数量,并且结束值被包含在内
    57. XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
    58. #np.c_,类似于np.vstack的功能
    59. Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()]).reshape(XX.shape)
    60. #填充等高线不同区域的颜色
    61. ax.pcolormesh(XX, YY, Z > 0, cmap=plt.cm.Paired)
    62. #绘制等高线
    63. ax.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'],
    64. levels=[-1, 0, 1])
    65. #设定坐标轴为不显示
    66. ax.set_xticks(())
    67. ax.set_yticks(())
    68. #将标题放在第一行的顶上
    69. if ds_cnt == 0:
    70. ax.set_title(kernel)
    71. #为每张图添加分类的分数
    72. ax.text(0.95, 0.06, ('%.2f' % score).lstrip('0')
    73. , size=15
    74. , bbox=dict(boxstyle='round', alpha=0.8, facecolor='white')
    75. #为分数添加一个白色的格子作为底色
    76. , transform=ax.transAxes #确定文字所对应的坐标轴,就是ax子图的坐标轴本身
    77. , horizontalalignment='right' #位于坐标轴的什么方向
    78. )
    79. plt.tight_layout()
    80. plt.show()

    探索核函数的优势和缺陷

    1. from sklearn.datasets import load_breast_cancer
    2. from sklearn.svm import SVC
    3. from sklearn.model_selection import train_test_split
    4. import matplotlib.pyplot as plt
    5. import numpy as np
    6. from time import time
    7. import datetime
    8. data = load_breast_cancer()
    9. X = data.data
    10. y = data.target
    11. X.shape
    12. np.unique(y)
    13. plt.scatter(X[:,0],X[:,1],c=y)
    14. plt.show()
    15. Xtrain, Xtest, Ytrain, Ytest = train_test_split(X,y,test_size=0.3,random_state=420)
    16. Kernel = ["linear","poly","rbf","sigmoid"]
    17. for kernel in Kernel:
    18. time0 = time()
    19. clf= SVC(kernel = kernel
    20. , gamma="auto"
    21. # , degree = 1
    22. , cache_size=5000
    23. ).fit(Xtrain,Ytrain)
    24. print("The accuracy under kernel %s is %f" % (kernel,clf.score(Xtest,Ytest)))
    25. print(datetime.datetime.fromtimestamp(time()-time0).strftime("%M:%S:%f"))

     跑不出来,模型一直停留在线性核函数之后,就没有再打印结果了。这证明,多项式核函 数此时此刻要消耗大量的时间,运算非常的缓慢。让我们在循环中去掉多项式核函数,再试试看能否跑出结果: 

    1. Kernel = ["linear","rbf","sigmoid"]
    2. for kernel in Kernel:
    3. time0 = time()
    4. clf= SVC(kernel = kernel
    5. , gamma="auto"
    6. # , degree = 1
    7. , cache_size=5000
    8. ).fit(Xtrain,Ytrain)
    9. print("The accuracy under kernel %s is %f" % (kernel,clf.score(Xtest,Ytest)))
    10. print(datetime.datetime.fromtimestamp(time()-time0).strftime("%M:%S:%f"))

    如果数据是线性的,那如果我们把degree参数调整为1,多项式核函数应该也可以得到不错的结果: 

    1. Kernel = ["linear","poly","rbf","sigmoid"]
    2. for kernel in Kernel:
    3. time0 = time()
    4. clf= SVC(kernel = kernel
    5. , gamma="auto"
    6. , degree = 1
    7. , cache_size=5000
    8. ).fit(Xtrain,Ytrain)
    9. print("The accuracy under kernel %s is %f" % (kernel,clf.score(Xtest,Ytest)))
    10. print(datetime.datetime.fromtimestamp(time()-time0).strftime("%M:%S:%f"))

    真正的问题是数据的量纲问题。回忆一下我们如何求解决策边界,如何判断点是否在决策边界的一边? 是靠计算”距离“,虽然我们不能说SVM是完全的距离类模型,但是它严重受到数据量纲的影响。让我们来探索一下 乳腺癌数据集的量纲: 

    1. import pandas as pd
    2. data = pd.DataFrame(X)
    3. data.describe([0.01,0.05,0.1,0.25,0.5,0.75,0.9,0.99]).T

    我们来使用数据预处理中的标准化的类,对数据进行标准化: 

    1. from sklearn.preprocessing import StandardScaler
    2. X = StandardScaler().fit_transform(X)
    3. data = pd.DataFrame(X)
    4. data.describe([0.01,0.05,0.1,0.25,0.5,0.75,0.9,0.99]).T

    让SVC在核函数中遍历,此时我们把degree的数值设定为1,观察各个核函数在去量纲后的数 据上的表现:

    1. Xtrain, Xtest, Ytrain, Ytest = train_test_split(X,y,test_size=0.3,random_state=420)
    2. Kernel = ["linear","poly","rbf","sigmoid"]
    3. for kernel in Kernel:
    4. time0 = time()
    5. clf= SVC(kernel = kernel
    6. , gamma="auto"
    7. , degree = 1
    8. , cache_size=5000
    9. ).fit(Xtrain,Ytrain)
    10. print("The accuracy under kernel %s is %f" % (kernel,clf.score(Xtest,Ytest)))
    11. print(datetime.datetime.fromtimestamp(time()-time0).strftime("%M:%S:%f"))

    我们来试试看高斯径向基核函数 rbf的参数gamma在乳腺癌数据集上的表现:

    1. score = []
    2. gamma_range = np.logspace(-10, 1, 50) #返回在对数刻度上均匀间隔的数字
    3. for i in gamma_range:
    4. clf = SVC(kernel="rbf",gamma = i,cache_size=5000).fit(Xtrain,Ytrain)
    5. score.append(clf.score(Xtest,Ytest))
    6. print(max(score), gamma_range[score.index(max(score))])
    7. plt.plot(gamma_range,score)
    8. plt.show()

    对于多项式核函数来说,一切就没有那么容易了,因为三个参数共同作用在一个数学公式上影响它的效果,因此 我们往往使用网格搜索来共同调整三个对多项式核函数有影响的参数。依然使用乳腺癌数据集

    1. from sklearn.model_selection import StratifiedShuffleSplit
    2. from sklearn.model_selection import GridSearchCV
    3. time0 = time()
    4. gamma_range = np.logspace(-10,1,20)
    5. coef0_range = np.linspace(0,5,10)
    6. param_grid = dict(gamma = gamma_range
    7. ,coef0 = coef0_range)
    8. cv = StratifiedShuffleSplit(n_splits=5, test_size=0.3, random_state=420)
    9. grid = GridSearchCV(SVC(kernel = "poly",degree=1,cache_size=5000),
    10. param_grid=param_grid, cv=cv)
    11. grid.fit(X, y)
    12. print("The best parameters are %s with a score of %0.5f" % (grid.best_params_,
    13. grid.best_score_))
    14. print(datetime.datetime.fromtimestamp(time()-time0).strftime("%M:%S:%f"))

    重要参数C

     使用网格搜索或者学习曲线来调整C的值

    1. #调线性核函数
    2. score = []
    3. C_range = np.linspace(0.01,30,50)
    4. for i in C_range:
    5. clf = SVC(kernel="linear",C=i,cache_size=5000).fit(Xtrain,Ytrain)
    6. score.append(clf.score(Xtest,Ytest))
    7. print(max(score), C_range[score.index(max(score))])
    8. plt.plot(C_range,score)
    9. plt.show()
    10. #换rbf
    11. score = []
    12. C_range = np.linspace(0.01,30,50)
    13. for i in C_range:
    14. clf = SVC(kernel="rbf",C=i,gamma =
    15. 0.012742749857031322,cache_size=5000).fit(Xtrain,Ytrain)
    16. score.append(clf.score(Xtest,Ytest))
    17. print(max(score), C_range[score.index(max(score))])
    18. plt.plot(C_range,score)
    19. plt.show()
    20. #进一步细化
    21. score = []
    22. C_range = np.linspace(5,7,50)
    23. for i in C_range:
    24. clf = SVC(kernel="rbf",C=i,gamma =
    25. 0.012742749857031322,cache_size=5000).fit(Xtrain,Ytrain)
    26. score.append(clf.score(Xtest,Ytest))
    27. print(max(score), C_range[score.index(max(score))])
    28. plt.plot(C_range,score)
    29. plt.show()

  • 相关阅读:
    两个技巧教你怎么裁剪视频尺寸,手残党也能掌握
    云原生|kubernetes|静态pod和静态pod的应用
    SpringBoot实现百度文库文档上传,通俗易懂适合萌新
    linux常见命令-时间日期类、搜索查找类、压缩和解压类
    划词标注或打标签的实现方案
    Unity使用c#开发遇上的问题(十)(unity中使用自带体获得预制体阴影)
    Day1 初学机器学习:机器学习的概述、特征工程
    51单片机K型热电偶温度采集及控制温控模块MAX6675热电偶LCD1602
    【B/S架构】医院不良事件报告系统源码
    【Linux】进程终止
  • 原文地址:https://blog.csdn.net/weixin_44267765/article/details/126871553