You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python sklearn中的SVR绘图问题?附拟合代码

Fixing SVR Plotting Issues in Scikit-Learn

Hey there! Let's get that SVR plot working properly. The most common causes of wonky SVR plots are missing continuous input data for smooth predictions, forgetting to inverse-transform your scaled values, or dimension mismatches. Here's a step-by-step fix:

Common Issues & Quick Context

First, let's break down what's likely throwing your plot off:

  • Your training data might be unordered or discrete, leading to a jagged/non-sensical curve
  • You scaled both X and Y, but plotting predictions without reversing that scaling will make values misalign with your original dataset
  • Shape mismatches between input arrays and predictions can break plotting entirely

Full Fixed Code with Plotting Logic

Let's update your existing code with proper plotting steps, explaining each key change:

from sklearn.svm import SVR
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Your original code (kept intact)
X_train_Occ = pd.DataFrame(X_train['occupancy'])
Y_train_Occ = Y_train

# Rescale (retain fitted scalers for later inverse transforms!)
sc_X = StandardScaler()
sc_Y = StandardScaler()
X_train_Occ_scaled = sc_X.fit_transform(X_train_Occ)
Y_train_Occ_scaled = sc_Y.fit_transform(Y_train_Occ.reshape(-1, 1))

# Fit SVR model (use ravel() to avoid shape warnings)
regressor = SVR(kernel='rbf')
regressor.fit(X_train_Occ_scaled, Y_train_Occ_scaled.ravel())

# --- Plotting Fixes Start Here ---
# 1. Generate a continuous range of X values for smooth curve plotting
# We cover the full min-max range of your original occupancy data
X_plot_range = pd.DataFrame({
    'occupancy': np.linspace(X_train_Occ['occupancy'].min(), X_train_Occ['occupancy'].max(), 100)
})

# 2. Scale this new range with the SAME scaler (never refit on new data!)
X_plot_scaled = sc_X.transform(X_plot_range)

# 3. Predict and inverse-transform to get back to original Y units
Y_pred_scaled = regressor.predict(X_plot_scaled)
Y_pred = sc_Y.inverse_transform(Y_pred_scaled.reshape(-1, 1))

# 4. Create the plot
plt.figure(figsize=(10,6))
# Plot raw training data points
plt.scatter(X_train_Occ, Y_train_Occ, color='navy', label='Training Data')
# Plot smooth SVR prediction curve
plt.plot(X_plot_range, Y_pred, color='crimson', linewidth=2, label='SVR Prediction')

plt.xlabel('Occupancy')
plt.ylabel('Target Value')
plt.title('SVR Model Fit to Occupancy Data')
plt.legend()
plt.show()

Key Fixes Explained

  • Continuous X Range: Using np.linspace creates 100 evenly spaced points across your data's full range, which gives us a smooth prediction curve instead of plotting only discrete training points.
  • Reusing Scalers: We never refit the scalers on new data—this ensures we apply the exact same transformation used during training, which is critical for valid predictions.
  • Inverse Transforming: Since we scaled our target variable, we need to reverse that scaling with sc_Y.inverse_transform to get predictions in your original data's units. Without this, your plot would show scaled values that don't align with your raw dataset.
  • Shape Handling: Using .ravel() when fitting avoids shape mismatch warnings, and .reshape(-1,1) ensures predictions are formatted correctly for inverse transformation.

If you were seeing issues like a flat line, jagged plot, or values that don't make sense relative to your data, these steps should resolve those problems.

内容的提问来源于stack exchange,提问作者brian4342

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:44:41