svm算法python实现
时间: 2023-07-26 20:24:53 浏览: 121
svm.zip_SVM算法代码_python实现svm_svm python实现_svm python
5星 · 资源好评率100%
使用Python实现SVM算法可以使用scikit-learn库。以下是一个简单的SVM分类器的例子:
首先,导入必要的库:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
```
然后,加载数据集:
```python
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=123)
```
创建SVM分类器:
```python
clf = svm.SVC(kernel='linear', C=1)
```
使用训练集训练分类器:
```python
clf.fit(X_train, y_train)
```
使用测试集预测:
```python
y_pred = clf.predict(X_test)
```
计算分类器的准确率:
```python
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
这就是一个简单的SVM分类器的Python实现。
阅读全文