sklearn svm实现
时间: 2023-09-07 08:14:31 浏览: 103
要使用Scikit-learn库实现SVM,需要进行以下步骤:
1.导入所需的库:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
```
2.加载数据集:
```python
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
3.将数据集分成训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
4.创建SVM分类器对象:
```python
svm = SVC(kernel='linear')
```
5.训练模型:
```python
svm.fit(X_train, y_train)
```
6.使用训练好的模型进行预测:
```python
y_pred = svm.predict(X_test)
```
7.计算模型的准确率:
```python
acc = accuracy_score(y_test, y_pred)
print('Accuracy:', acc)
```
完整的代码如下所示:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
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.3, random_state=42)
svm = SVC(kernel='linear')
svm.fit(X_train, y_train)
y_pred = svm.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print('Accuracy:', acc)
```
阅读全文