线性和非线性支持向量机算法代码实现
时间: 2023-10-04 21:07:12 浏览: 57
以下是使用Python实现线性和非线性支持向量机算法的示例代码。代码使用了scikit-learn库中的SVM模块。
线性支持向量机代码:
```python
from sklearn import svm
import numpy as np
# 创建数据集
X = np.array([[1, 2], [2, 3], [3, 3], [2, 1], [3, 2]])
y = np.array([1, 1, 1, -1, -1])
# 创建支持向量机分类器
clf = svm.SVC(kernel='linear')
# 训练模型
clf.fit(X, y)
# 预测分类结果
print(clf.predict([[2, 2]]))
```
非线性支持向量机代码:
```python
from sklearn import svm
import numpy as np
# 创建数据集
X = np.array([[1, 2], [2, 3], [3, 3], [2, 1], [3, 2]])
y = np.array([1, 1, 1, -1, -1])
# 创建支持向量机分类器
clf = svm.SVC(kernel='rbf')
# 训练模型
clf.fit(X, y)
# 预测分类结果
print(clf.predict([[2, 2]]))
```
以上代码中,我们使用SVM模块中的SVC类创建支持向量机分类器,并指定kernel参数为‘linear’和‘rbf’分别对应线性核函数和径向基核函数。我们还使用fit()函数训练模型,并使用predict()函数对新的数据点进行分类预测。