SVM实际应用代码案例
时间: 2024-01-22 07:03:42 浏览: 26
以下是一个SVM实际应用的代码案例,用于对手写数字进行分类。
首先,导入必要的库和数据集:
```python
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
digits = load_digits()
X, y = digits.data, digits.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
```
接下来,创建一个SVM分类器并进行训练:
```python
svm = SVC(kernel='linear', C=1, random_state=42)
svm.fit(X_train, y_train)
```
然后,用测试集数据评估分类器的准确性:
```python
accuracy = svm.score(X_test, y_test)
print('Accuracy:', accuracy)
```
最后,可以使用分类器对新的手写数字进行分类:
```python
new_digit = np.array([[0., 0., 0., 12., 13., 0., 0., 0.],
[0., 0., 0., 11., 16., 10., 0., 0.],
[0., 0., 3., 15., 16., 2., 0., 0.],
[0., 0., 8., 14., 16., 2., 0., 0.],
[0., 0., 1., 16., 16., 2., 0., 0.],
[0., 0., 0., 11., 16., 9., 0., 0.],
[0., 0., 0., 1., 16., 16., 3., 0.],
[0., 0., 0., 0., 12., 15., 14., 0.]])
new_digit = new_digit.reshape(1, -1)
prediction = svm.predict(new_digit)
print('Prediction:', prediction)
```
这个代码案例展示了SVM分类器在手写数字分类问题上的应用。