使用svm算法实现代码
时间: 2024-11-22 09:28:13 浏览: 6
PSOSVM的Matlab代码.zip
SVM (支持向量机) 是一种监督学习模型,主要用于分类和回归分析。以下是使用Python的scikit-learn库实现线性SVM的基本步骤:
1. 导入所需库:
```python
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import numpy as np
```
2. 准备数据集(假设有一个名为data的数据矩阵,目标变量是y):
```python
X = data[:, :-1] # 特征
y = data[:, -1] # 目标值
```
3. 数据预处理(归一化或标准化,这里使用StandardScaler):
```python
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
```
4. 划分训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
```
5. 创建并训练SVM模型(线性核):
```python
model = svm.LinearSVC()
model.fit(X_train, y_train)
```
6. 预测测试集:
```python
y_pred = model.predict(X_test)
```
7. 评估模型性能(例如,计算准确率):
```python
accuracy = model.score(X_test, y_test)
print(f"Accuracy: {accuracy}")
```
阅读全文