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

标准化缩放标签遇2D数组错误及后续形状问题求助

Fixing "Expected 2D array, got 1D array instead" and "bad input shape" Errors in SVR Feature Scaling

Hey there! Let's break down why you're hitting these shape-related issues and fix your code properly.

Why the First Error Occurred

Scikit-learn's StandardScaler expects input data to be a 2D array structured as [number_of_samples, number_of_features]. When you pulled y with y = dataset.iloc[:, 2].values, you ended up with a 1D array (shape (10,) for your 10-row dataset). That mismatch between what the scaler expects and what you provided caused the first error.

Why the Second Error Happened

When you tried y = sc_y.fit_transform([y]), you turned y into a 2D array but with the wrong dimensions: (1, 10) (1 sample, 10 features) instead of (10, 1) (10 samples, 1 feature). The SVR model needs y to match the number of samples in X (which is (10, 1)), so this flipped shape triggered the "bad input shape (1, 10)" error.

The Correct Fix

You need to reshape y into a 2D array with the right dimensions—(number_of_samples, 1)—before scaling. Use reshape(-1, 1) where -1 tells NumPy to automatically calculate the number of rows based on your data:

Here's the corrected code with key changes highlighted:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
# Fix 1: Reshape y to valid 2D array before scaling
y = sc_y.fit_transform(y.reshape(-1, 1))

# Fitting SVR to the dataset
from sklearn.svm import SVR
regressor = SVR(kernel = 'rbf')
regressor.fit(X, y)

# Predicting a new result
# Fix 2: Ensure the input for prediction matches X's 2D shape
y_pred = regressor.predict(sc_X.transform(np.array([[6.5]])))
y_pred = sc_y.inverse_transform(y_pred)

# Visualising the SVR results
plt.scatter(X, y, color = 'red')
plt.plot(X, regressor.predict(X), color = 'blue')
plt.title('Truth or Bluff (SVR)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

Quick Extra Tips

  • When predicting a new value like 6.5, wrap it in np.array([[6.5]]) to match the 2D structure of X the model was trained on.
  • After scaling, y will be a 2D array, but scikit-learn's SVR.fit() accepts both 1D and 2D arrays for y, so no extra adjustments are needed here.
  • The inverse_transform method handles both 1D and 2D inputs seamlessly, so your predicted salary will convert back to the original scale without issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:28:21