美文网首页
支持向量机SVM代码实践

支持向量机SVM代码实践

作者: 万州客 | 来源:发表于2022-04-27 08:38 被阅读0次

    传统机器学习的最后一类算法了,接下来要进入神经网络了。

    一,代码

    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn import  svm
    from sklearn.datasets import make_blobs
    from sklearn.datasets import load_wine
    
    '''
    X, y = make_blobs(n_samples=50, centers=2, random_state=6)
    clf = svm.SVC(kernel='rbf', C=1000)
    clf.fit(X, y)
    plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired)
    ax = plt.gca()
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    
    xx = np.linspace(xlim[0], xlim[1], 30)
    yy = np.linspace(ylim[0], ylim[1], 30)
    YY, XX = np.meshgrid(yy, xx)
    xy = np.vstack([XX.ravel(), YY.ravel()]).T
    Z = clf.decision_function(xy).reshape(XX.shape)
    
    ax.contour(XX, YY, Z, color='k', levels=[-1, 0, 1],
               alpha=0.5, linestyles=['--', '-', '--'])
    ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
               s=100, linewidth=1, facecolors='none')
    plt.show()
    '''
    
    # 定义一个函数来画图
    def make_meshgrid(x, y, h=.02):
        x_min, x_max = x.min() - 1, x.max() + 1
        y_min, y_max = y.min() - 1, y.max() + 1
        xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                             np.arange(y_min, y_max, h))
        return xx, yy
    
    # 定义一个绘制等高线函数
    def plot_contours(ax, clf, xx, yy, **params):
        Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        out = ax.contourf(xx, yy, Z, **params)
        return out
    
    # 使用酒的数据集,选取数据集的前两个特征
    wine = load_wine()
    X = wine.data[:, :2]
    y = wine.target
    
    # 设定正则化参数
    C = 1.0
    '''
    
    models = (svm.SVC(kernel='linear', C=C),
              svm.LinearSVC(C=C),
              svm.SVC(kernel='rbf', gamma=0.7, C=C),
              svm.SVC(kernel='poly', degree=3, C=C))
    models = (clf.fit(X, y) for clf in models)
    
    titles = ('SVC with linear kernel',
              'LinearSVC (linear kernel)',
              'SVC with RBF kernel',
              'SVC with polynomial (degree 3) kernel')
    '''
    models = (svm.SVC(kernel='rbf', gamma=0.1, C=C),
              svm.SVC(kernel='rbf', gamma=1, C=C),
              svm.SVC(kernel='rbf', gamma=10, C=C))
    models = (clf.fit(X, y) for clf in models)
    
    titles = ('gamma = 0.1',
              'gamma = 1',
              'gamma = 10')
    # 设定一个子图形的个数和排列方式
    # fig, sub = plt.subplots(2, 2)
    # plt.subplots_adjust(wspace=0.4, hspace=0.4)
    fig, sub = plt.subplots(1, 3, figsize=(10, 3))
    # 使用前面定义的函数画图
    X0, X1 = X[:, 0], X[:, 1]
    xx, yy = make_meshgrid(X0, X1)
    
    for clf, title, ax in zip(models, titles, sub.flatten()):
        plot_contours(ax, clf, xx, yy, cmap=plt.cm.plasma, alpha=0.8)
        ax.scatter(X0, X1, c=y, cmap=plt.cm.plasma, s=20, edgecolors='k')
        ax.set_xlim(xx.min(), xx.max())
        ax.set_ylim(yy.min(), yy.max())
        ax.set_xlabel('Feature 0')
        ax.set_ylabel('Feature 1')
        ax.set_xticks(())
        ax.set_yticks(())
        ax.set_title(title)
    
    plt.show()
    

    二,效果


    2022-04-26 11_42_17-MessageCenterUI.png 2022-04-26 11_25_05-MessageCenterUI.png 2022-04-26 10_55_25-MessageCenterUI.png

    相关文章

      网友评论

          本文标题:支持向量机SVM代码实践

          本文链接:https://www.haomeiwen.com/subject/wgvcyrtx.html