svm支持向量机python
时间: 2023-10-06 12:04:44 浏览: 36
在 Python 中使用 SVM(支持向量机)模型可以使用 scikit-learn 库。以下是一个简单的示例:
首先,导入必要的库和数据集:
```python
from sklearn import datasets
from sklearn import svm
import numpy as np
iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target
```
然后,将数据集分为训练集和测试集:
```python
# 将数据集分为训练集和测试集
np.random.seed(0)
indices = np.random.permutation(len(X))
X_train = X[indices[:-10]]
y_train = y[indices[:-10]]
X_test = X[indices[-10:]]
y_test = y[indices[-10:]]
```
接着,使用 SVM 模型进行训练和预测:
```python
# 使用 SVM 模型进行训练和预测
clf = svm.SVC(kernel='linear')
clf.fit(X_train, y_train)
# 预测测试集的结果
y_pred = clf.predict(X_test)
```
最后,计算模型的准确率:
```python
# 计算模型的准确率
accuracy = np.mean(y_pred == y_test)
print("Accuracy:", accuracy)
```
这个简单的示例使用 SVM 模型对鸢尾花数据集进行分类。你可以修改代码中的数据集和参数来适应你的需求。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)