svm分类python
时间: 2023-09-03 11:12:07 浏览: 94
在Python中使用SVM分类器的步骤如下:
1. 导入必要的库
```python
from sklearn import svm
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
2. 准备数据
```python
X, y = make_classification(n_samples=1000, n_features=4, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
这里使用了`make_classification()`函数生成了一个包含1000个样本和4个特征的数据集,并将其分为训练集(80%)和测试集(20%)。
3. 训练SVM分类器
```python
clf = svm.SVC(kernel='linear')
clf.fit(X_train, y_train)
```
这里使用了`svm.SVC()`函数来创建一个SVM分类器,并使用`fit()`函数训练它。
4. 预测并评估准确率
```python
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
使用`predict()`函数对测试集进行预测,并使用`accuracy_score()`函数计算准确率。
完整代码如下:
```python
from sklearn import svm
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 生成数据
X, y = make_classification(n_samples=1000, n_features=4, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 训练SVM分类器
clf = svm.SVC(kernel='linear')
clf.fit(X_train, y_train)
# 预测并评估准确率
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
注意:上述代码中使用的是线性SVM分类器,如果需要使用其他核函数,可以将`kernel`参数设置为`'poly'`、`'rbf'`等。
阅读全文
相关推荐
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)