支持向量机python语言程序
时间: 2024-06-21 17:01:48 浏览: 84
python支持向量机
支持向量机(Support Vector Machine, SVM)是一种监督学习的机器学习算法,主要用于分类和回归分析。在Python中,SVM通常使用scikit-learn库来实现。以下是使用scikit-learn实现SVM的基本步骤:
1. 导入所需的库:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import accuracy_score
```
2. 加载数据集(这里以鸢尾花数据集为例):
```python
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
3. 划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
4. 创建并训练SVM模型:
```python
clf = svm.SVC(kernel='linear') # 选择线性内核(其他选项如'poly', 'rbf'等)
clf.fit(X_train, y_train)
```
5. 预测和评估:
```python
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文