机器学习之支持向量回归
【代码】机器学习之支持向量回归。
·
支持向量回归是支持向量机(SVM)在回归问题上的应用,主要特点如下:
1.基本原理
- 与传统回归不同,SVR的目标是在误差ε范围内找到最"平坦"的函数
- 使用ε-不敏感损失函数
- 允许一定程度的误差,只要误差不超过ε
-
2.核心概念
- ε-间隔带:预测值与实际值的误差在±ε范围内
- 支持向量:位于ε-间隔带边界上的样本点
- 核函数:处理非线性问题时使用的映射函数
3. 数学表达
# 线性SVR的优化目标
min 1/2 ||w||² + C∑(ξi + ξi*)
s.t. yi - (w·xi + b) ≤ ε + ξi
(w·xi + b) - yi ≤ ε + ξi*
ξi, ξi* ≥ 0
4.常用核函数
- 线性核:K(x,y) = x·y
- 多项式核:K(x,y) = (γx·y + r)^d
- RBF核:K(x,y) = exp(-γ||x-y||²)
- Python实现示例
from sklearn.svm import SVR from sklearn.preprocessing import StandardScaler # 数据预处理 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 创建SVR模型 svr = SVR(kernel='rbf', C=100, epsilon=0.1) # 训练模型 svr.fit(X_scaled, y) # 预测 y_pred = svr.predict(X_scaled)5.1线性SVR
对于给定的训练数据集 {(x₁,y₁), ..., (xₙ,yₙ)},线性SVR试图找到函数:
-
f(x) = <w,x> + b
-
其中:
- w 是权重向量
- b 是偏置项
- <w,x> 表示内积
-
5.2 优化目标的完整数学表达
-
min 1/2 ||w||² + C∑(ξᵢ + ξᵢ*) subject to: yᵢ - (<w,xᵢ> + b) ≤ ε + ξᵢ (<w,xᵢ> + b) - yᵢ ≤ ε + ξᵢ* ξᵢ, ξᵢ* ≥ 05.3详细的Python实现
-
import numpy as np from sklearn.svm import SVR from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error, r2_score import matplotlib.pyplot as plt # 1. 数据准备 def prepare_data(X, y): # 数据标准化 scaler_X = StandardScaler() scaler_y = StandardScaler() X_scaled = scaler_X.fit_transform(X.reshape(-1, 1)) y_scaled = scaler_y.fit_transform(y.reshape(-1, 1)).ravel() # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split( X_scaled, y_scaled, test_size=0.2, random_state=42 ) return X_train, X_test, y_train, y_test, scaler_X, scaler_y # 2. SVR模型训练和评估 def train_svr_model(X_train, y_train, kernel='rbf'): # 创建不同核函数的SVR模型 models = { 'linear': SVR(kernel='linear', C=100, epsilon=0.1), 'poly': SVR(kernel='poly', C=100, epsilon=0.1, degree=2), 'rbf': SVR(kernel='rbf', C=100, epsilon=0.1, gamma='scale') } # 选择并训练模型 model = models[kernel] model.fit(X_train, y_train) return model # 3. 模型评估 def evaluate_model(model, X_test, y_test): y_pred = model.predict(X_test) mse = mean_squared_error(y_test, y_pred) r2 = r2_score(y_test, y_pred) return y_pred, mse, r2 # 4. 网格搜索最优参数 def grid_search_svr(X_train, y_train): from sklearn.model_selection import GridSearchCV param_grid = { 'C': [0.1, 1, 10, 100], 'epsilon': [0.01, 0.1, 0.2], 'gamma': ['scale', 'auto', 0.1, 0.01] } svr = SVR(kernel='rbf') grid_search = GridSearchCV( svr, param_grid, cv=5, scoring='neg_mean_squared_error', n_jobs=-1 ) grid_search.fit(X_train, y_train) return grid_search.best_params_ # 5. 可视化结果 def plot_results(X_test, y_test, y_pred): plt.figure(figsize=(10, 6)) plt.scatter(X_test, y_test, color='black', label='Actual') plt.scatter(X_test, y_pred, color='red', label='Predicted') plt.legend() plt.title('SVR Prediction Results') plt.xlabel('X') plt.ylabel('y') plt.show() # 完整示例 def main(): # 生成示例数据 np.random.seed(42) X = np.sort(5 * np.random.rand(100, 1), axis=0) y = np.sin(X).ravel() + np.random.normal(0, 0.1, X.shape[0]) # 准备数据 X_train, X_test, y_train, y_test, scaler_X, scaler_y = prepare_data(X, y) # 找到最优参数 best_params = grid_search_svr(X_train, y_train) print("Best parameters:", best_params) # 训练模型 model = train_svr_model(X_train, y_train, kernel='rbf') # 评估模型 y_pred, mse, r2 = evaluate_model(model, X_test, y_test) print(f"MSE: {mse:.4f}") print(f"R2 Score: {r2:.4f}") # 可视化结果 plot_results(X_test, y_test, y_pred) if __name__ == "__main__": main()6.核函数详解
6.1 线性核
K(x,y) = x·y
适用于线性可分的数据。
6.2 多项式核
K(x,y) = (γx·y + r)^d
- γ:核系数
- r:常数项
- d:多项式次数
6.3 RBF(高斯)核
K(x,y) = exp(-γ||x-y||²)
- γ:决定影响的范围
7. 参数调优指南
7.1 重要参数
- C参数
- 较大的C:更注重减小误差,可能过拟合
- 较小的C:更注重模型简单性,可能欠拟合
- 建议范围:[0.1, 1, 10, 100, 1000]
- epsilon参数
- 控制ε-管道的宽度
- 较大的ε:更少的支持向量,模型更简单
- 较小的ε:更多的支持向量,模型更复杂
- 建议范围:[0.01, 0.1, 0.2]
- gamma参数(RBF核)
- 控制径向基函数的形状
- 较大的γ:高方差,低偏差
- 较小的γ:低方差,高偏差
- 建议范围:['scale', 'auto', 0.1, 0.01]
8. 性能优化建议
1. 数据预处理
- 特征标准化很重要
- 处理异常值
- 特征选择
-
2.模型选择
- 对于小数据集:尝试线性核
- 对于中等数据集:RBF核通常表现最好
- 对于特殊关系:可以考虑多项式核
-
3.计算效率
- 使用增量学习处理大数据集
- 考虑使用LinearSVR代替带线性核的SVR
- 适当使用并行计算
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)