python调用SVM
时间: 2023-09-05 15:09:57 浏览: 48
在Python中调用SVM,可以使用scikit-learn库中的SVM模块。以下是一个简单的例子:
```python
from sklearn import svm
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 生成数据集
X, y = make_classification(n_samples=100, random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
# 创建SVM分类器
clf = svm.SVC(kernel='linear')
# 使用训练集训练分类器
clf.fit(X_train, y_train)
# 使用测试集进行预测
y_pred = clf.predict(X_test)
# 输出模型的准确率
print("Accuracy:", clf.score(X_test, y_test))
```
在这个例子中,我们使用scikit-learn库中的make_classification函数生成了一个包含100个样本的二分类数据集。然后我们使用train_test_split函数将数据集划分为训练集和测试集。接下来,我们创建了一个SVM分类器,并使用训练集训练了这个分类器。最后,我们使用测试集进行预测,并输出模型的准确率。
需要注意的是,这个例子中使用的是线性核函数。如果需要使用其他核函数,可以在创建SVM分类器时指定kernel参数。例如,如果要使用高斯核函数,可以将kernel参数设置为'rbf'。