使用sklearn实现SVR支持向量化完整代码(包括绘图)
时间: 2024-10-13 12:08:33 浏览: 28
在Python的scikit-learn库中,支持向量回归(Support Vector Regression, SVR)是一种用于预测连续数值的机器学习模型。以下是使用sklearn实现一个简单的线性SVR示例,以及如何绘制预测结果:
```python
# 导入所需的库
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.datasets import make_regression
# 创建模拟数据集
np.random.seed(0)
X, y = make_regression(n_samples=50, n_features=1, noise=20, random_state=42)
# 划分训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 初始化并训练SVR模型(这里选择线性核)
model = SVR(kernel='linear')
model.fit(X_train, y_train)
# 预测测试集
y_pred = model.predict(X_test)
# 绘制原始数据、真实值和预测值
plt.scatter(X_train, y_train, label='Train data', color='black')
plt.scatter(X_test, y_test, label='Test data', color='red')
plt.plot(X_train, model.predict(X_train), label='Linear SVR fit', color='blue')
plt.plot(X_test, y_pred, 'o', markersize=6, label='Predictions', color='green')
plt.xlabel('Feature')
plt.ylabel('Target')
plt.title('Linear Support Vector Regression Example')
plt.legend()
plt.show()
阅读全文