支持向量回归python代码
时间: 2023-11-08 18:59:13 浏览: 60
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error, r2_score
# 源数据
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]) # 特征矩阵
y = np.array([3, 7, 9, 11, 13]) # 目标向量
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建SVM回归模型
svr = SVR(kernel='linear', C=1.0)
# 拟合训练数据
svr.fit(X_train, y_train)
# 预测测试数据
y_pred = svr.predict(X_test)
# 计算模型评估指标
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# 打印结果
print("均方误差 (MSE): {:.2f}".format(mse))
print("决定系数 (R2): {:.2f}".format(r2))
相关问题
最小二乘支持向量回归python代码
下面是使用Python实现最小二乘支持向量回归(LSSVR)的示例代码:
```python
import numpy as np
from sklearn.svm import SVR
# 生成测试数据
x = np.sort(5 * np.random.rand(40, 1), axis=0)
y = np.sin(x).ravel()
# 创建LSSVR模型
model = SVR(kernel='linear', C=1e3, epsilon=0.2)
# 训练模型
model.fit(x, y)
# 绘制结果
import matplotlib.pyplot as plt
plt.scatter(x, y, color='darkorange', label='data')
plt.plot(x, model.predict(x), color='navy', label='LSSVR')
plt.xlabel('data')
plt.ylabel('target')
plt.title('LSSVR')
plt.legend()
plt.show()
```
在上面的示例代码中,我们使用了Scikit-learn库中的SVR类来创建LSSVR模型。其中,`kernel`参数指定了使用线性核函数,`C`参数指定了惩罚因子的大小,`epsilon`参数指定了允许的误差范围。训练模型后,我们使用Matplotlib库来绘制结果。
支持向量机python回归代码
支持向量机(SVM)是一种常用于回归问题的机器学习模型。下面是一个简单的支持向量机回归的Python代码示例:
```python
from sklearn.svm import SVR
# 创建SVR模型对象
svr = SVR(kernel='rbf', C=1.0, epsilon=0.2)
# 训练模型
svr.fit(X_train, y_train)
# 使用模型进行预测
y_pred = svr.predict(X_test)
```
这个代码示例使用了sklearn库中的SVR类来创建一个支持向量机回归模型。在创建模型对象时,需要指定参数,比如核函数(这里使用了径向基函数rbf)、正则化参数C和ϵ。