支持向量机处理回归问题代码
时间: 2023-05-25 22:04:00 浏览: 44
下面是使用支持向量机处理回归问题的代码示例:
```python
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
#创建训练数据
X_train = np.sort(5 * np.random.rand(200, 1), axis=0)
y_train = np.sin(X_train).ravel()
#添加噪声
y_train[::5] += 3 * (0.5 - np.random.rand(X_train.shape[0] // 5))
#创建测试数据
X_test = np.arange(0.0, 5.0, 0.01)[:, np.newaxis]
y_test = np.sin(X_test).ravel()
#训练模型
svm_model = svm.SVR(kernel='rbf', C=100, gamma=0.1)
svm_model.fit(X_train, y_train)
#预测
y_pred = svm_model.predict(X_test)
#可视化结果
plt.plot(X_test, y_test, color='black', label='True')
plt.plot(X_test, y_pred, color='red', label='Prediction')
plt.scatter(X_train, y_train, facecolor='', edgecolor='blue', label='Training Samples')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()
```
解析:
1. 导入必要的库与模块。
2. 创建训练数据,使用`np.sort`对数据按照升序排列。使用`np.sin`函数生成与训练数据相对应的标签。
3. 在一定比例上添加噪声。
4. 创建测试数据,使用`np.arange`生成0到5的一维数组,然后运用 `[:, np.newaxis]`将数据升为二维数据。
5. 使用`svm.SVR`模型,进行训练,设定核函数类型为高斯核函数, $C=100$, $gamma=0.1$。
6. 对测试数据进行预测。
7. 将预测结果与真实标签用可视化的方式表示出来,其中真实标签用黑色线条表示,预测结果用红色线表示,训练数据用蓝色点表示。图例也被放在了右下角。