統計學習作業4:SVM

題目

在這裏插入圖片描述

代碼

import numpy as np
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

def svm_c(x, y):
    svc = SVC(kernel='linear')
    svc.fit(x, y)
    w = svc.coef_[0]
    a = -w[0] / w[1]
    return svc, w, a

if __name__ == '__main__':
    # data prepare
    x = np.array([[1, 2], [2, 3], [3, 3], [2, 1], [3, 2]])
    y = np.array([[1], [1], [1], [-1], [-1]])
    # svm
    svc, w, a = svm_c(x, y)
    # plot
    xx = np.linspace(0, 4)
    yy = a * xx - (svc.intercept_[0]) / w[1]
    plt.plot(xx, yy)
    plt.scatter(x[:3, 0], x[:3, 1], color='red')
    plt.scatter(x[3:, 0], x[3:, 1], color='blue')
    plt.show()

結果展示

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章