python实现SVM
时间: 2023-12-04 19:00:06 浏览: 86
以下是一个简单的Python实现SVM的例子:
1. 导入必要的库和数据集
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
# 导入数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
```
2. 训练SVM模型
```
# 创建SVM模型
clf = svm.SVC(kernel='linear', C=1)
# 训练模型
clf.fit(X_train, y_train)
```
3. 用测试集测试模型
```
# 预测测试集
y_pred = clf.predict(X_test)
# 输出准确率
print("Accuracy:", clf.score(X_test, y_test))
```
完整的代码如下:
```
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
# 导入数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0)
# 创建SVM模型
clf = svm.SVC(kernel='linear', C=1)
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 输出准确率
print("Accuracy:", clf.score(X_test, y_test))
```
输出结果:
```
Accuracy: 0.9666666666666667
```
阅读全文