支持向量机(支持向量机断带)

2-4、支持向量机断带实例

import numpy as np

import matplotlib.pyplot as plt

from sklearn.svm import SVC

from sklearn.datasets import make_blobs

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['axes.unicode_minus'] = False

X, y = make_blobs(random_state=27)

fig, sub = plt.subplots(2, 1, figsize=(5, 8))

titles = ("向量机断带为假", "向量机断带为真")

for break_ties, title, ax in zip((False, True), titles, sub.flatten()):

    svm = SVC(

        kernel="linear", C=1, break_ties=break_ties, decision_function_shape="ovr"

    ).fit(X, y)

    xlim = [X[:, 0].min(), X[:, 0].max()]

    ylim = [X[:, 1].min(), X[:, 1].max()]

    xs = np.linspace(xlim[0], xlim[1], 1000)

    ys = np.linspace(ylim[0], ylim[1], 1000)

    xx, yy = np.meshgrid(xs, ys)

    pred = svm.predict(np.c_[xx.ravel(), yy.ravel()])

    colors = [plt.cm.Accent(i) for i in [0, 4, 7]]

    points = ax.scatter(X[:, 0], X[:, 1], c=y, cmap="Accent")

    classes = [(0, 1), (0, 2), (1, 2)]

    line = np.linspace(X[:, 1].min() - 5, X[:, 1].max() + 5)

    ax.imshow(

        -pred.reshape(xx.shape),

        cmap="Accent",

        alpha=0.2,

        extent=(xlim[0], xlim[1], ylim[1], ylim[0]),

    )

    for coef, intercept, col in zip(svm.coef_, svm.intercept_, classes):

        line2 = -(line * coef[1] + intercept) / coef[0]

        ax.plot(line2, line, "-", c=colors[col[0]])

        ax.plot(line2, line, "--", c=colors[col[1]])

    ax.set_xlim(xlim)

    ax.set_ylim(ylim)

    ax.set_title(title)

    ax.set_aspect("equal")

plt.show()


2-8、SVC 线性内核

import numpy as np

from sklearn import svm, datasets

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['axes.unicode_minus'] = False

iris = datasets.load_iris()

#输入数据集iris

X = iris.data[:, :2]

#使用前两个功能

y = iris.target

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1

y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1

h = (x_max / x_min)/100

#创建网格,用原始数据绘制支持向量机边界。

xx, yy = np.meshgrid(np.arange(x_min, x_max, h),

np.arange(y_min, y_max, h))

X_plot = np.c_[xx.ravel(), yy.ravel()]

C = 1.0#给出正则化参数的值。

clf = svm.SVC(kernel='linear',C=C, decision_function_shape = 'ovr').fit(X, y)

#创建SVM分类器

Z = clf.predict(X_plot)

Z = Z.reshape(xx.shape)

plt.figure(figsize = (15, 5))

plt.subplot(121)

plt.contourf(xx, yy, Z, cmap = plt.cm.tab10, alpha = 0.3)

plt.scatter(X[:, 0], X[:, 1], c = y, cmap = plt.cm.Set1)

plt.xlabel('萼片长度')

plt.ylabel('萼片宽度')

plt.xlim(xx.min(), xx.max())

plt.title('SVC 线性内核')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容