标准化缩放标签遇2D数组错误及后续形状问题求助
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 innp.array([[6.5]])to match the 2D structure ofXthe model was trained on. - After scaling,
ywill be a 2D array, but scikit-learn'sSVR.fit()accepts both 1D and 2D arrays fory, so no extra adjustments are needed here. - The
inverse_transformmethod handles both 1D and 2D inputs seamlessly, so your predicted salary will convert back to the original scale without issues.
内容的提问来源于stack exchange,提问作者James

