svm分类python
时间: 2023-09-03 19:12:04 浏览: 115
使用支持向量机(SVM)进行分类的Python代码如下:
首先,导入必要的库:
```python
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
接着,定义训练数据和标签:
```python
X = np.array([[2, 0], [1, 1], [2, 3], [3, 2]])
y = np.array([0, 0, 1, 1])
```
然后,将数据集划分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,定义SVM分类器:
```python
clf = svm.SVC(kernel='linear', C=1.0)
```
这里使用线性核函数,C为正则化参数。
然后,使用训练数据训练SVM分类器:
```python
clf.fit(X_train, y_train)
```
最后,使用测试数据进行预测并计算精度:
```python
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
完整代码如下:
```python
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 训练数据和标签
X = np.array([[2, 0], [1, 1], [2, 3], [3, 2]])
y = np.array([0, 0, 1, 1])
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义SVM分类器
clf = svm.SVC(kernel='linear', C=1.0)
# 训练SVM分类器
clf.fit(X_train, y_train)
# 预测并计算精度
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
输出结果为:
```
Accuracy: 1.0
```
这说明SVM分类器对测试数据分类的精度为100%。
阅读全文