线性支持向量机代码实现
时间: 2024-10-17 10:01:26 浏览: 30
线性支持向量机(Linear Support Vector Machine, SVM)是一种监督学习算法,它通过找到数据中最能隔开不同类别的最大边界(即“间隔”),来进行分类任务。下面是一个简单的Python代码示例,使用Scikit-learn库实现线性SVM:
```python
from sklearn import svm
from sklearn.model_selection import train_test_split
import numpy as np
# 假设你已经有了特征数据X和标签y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建线性SVM模型
svm_model = svm.LinearSVC()
# 使用训练集拟合模型
svm_model.fit(X_train, y_train)
# 预测测试集
predictions = svm_model.predict(X_test)
# 可视化决策边界(仅适用于低维度数据)
if len(X.shape) == 2 and X.shape[1] <= 3:
import matplotlib.pyplot as plt
plot_decision_regions(X, y, classifier=svm_model)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('SVM Decision Boundaries')
plt.show()
# 模型评估
accuracy = svm_model.score(X_test, y_test)
print(f"Accuracy: {accuracy}")
阅读全文