自定义数据集 使用scikit-learn中svm的包实现svm分类

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

# 定义数据
class1_points = np.array([[1.9, 1.2],
                          [1.5, 2.1],
                          [1.9, 0.5],
                          [1.5, 0.9],
                          [0.9, 1.2],
                          [1.1, 1.7],
                          [1.4, 1.1]])

class2_points = np.array([[3.2, 3.2],
                          [3.7, 2.9],
                          [3.2, 2.6],
                          [1.7, 3.3],
                          [3.4, 2.6],
                          [4.1, 2.3],
                          [3.0, 2.9]])

# 合并数据
X = np.vstack((class1_points, class2_points))
y = np.hstack((np.ones(class1_points.shape[0]), -np.ones(class2_points.shape[0])))

# 创建 SVM 模型
clf = svm.SVC(kernel='linear', C=1.0)
clf.fit(X, y)

# 获取模型参数
w = clf.coef_[0]
b = clf.intercept_[0]

# 绘制数据点
plt.scatter(class1_points[:, 0], class1_points[:, 1], c='red', label='Class 1')
plt.scatter(class2_points[:, 0], class2_points[:, 1], c='blue', label='Class 2')

# 绘制决策边界
x1_min, x1_max = 0, 6
x2_min = -(w[0] * x1_min + b) / w[1]
x2_max = -(w[0] * x1_max + b) / w[1]
plt.plot([x1_min, x1_max], [x2_min, x2_max], 'k-', label='Decision Boundary')

# 绘制支持向量
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100, facecolors='none', edgecolors='k', label='Support Vectors')

plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('SVM with scikit-learn')
plt.legend()
plt.show()

自定义数据集 使用scikit-learn中svm的包实现svm分类_第1张图片

你可能感兴趣的:(scikit-learn,支持向量机,分类)