支持向量机模型Python代码
时间: 2023-10-07 14:08:47 浏览: 49
以下是一个简单的支持向量机模型的Python代码示例:
```python
# 导入必要的库
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
# 创建一个模拟数据集
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=0, random_state=42)
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建一个支持向量机模型
clf = svm.SVC(kernel='linear')
# 训练模型
clf.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = np.mean(y_pred == y_test)
print("Accuracy:", accuracy)
```
在这个示例中,我们使用`make_classification()`函数创建了一个模拟数据集,然后将其分为训练集和测试集。我们使用`svm.SVC()`函数创建了一个支持向量机模型,并使用`fit()`方法在训练集上拟合了模型。最后,我们使用`predict()`方法在测试集上进行了预测,并计算了模型的准确率。