什么是引发错误"Expected 2D array, got 1D array instead..."?



我正在进行一个ML项目,当我运行随机梯度下降代码时,我一直收到这个错误代码。有人知道为什么会出现这个代码或者如何修复它吗?如果需要,我可以提供更多信息。

我的列车/测试拆分代码:

from sklearn.model_selection import train_test_split
data = mpsc["Sample location (Urban, Rural, Remote)"]
target = mpsc["Total Filament"]
X = data
y = target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
X_train

X_train:的输出

523 2
492 3
767 3
440 2
318 1
..
838 2
965 1
518 2
75 3
564 1 Name: Sample location (Urban, Rural, Remote), Length: 806, dtype: object

y_train:的输出

523 0
492 2
767 0
440 0
318 0
..
838 0
965 1
518 0
75 3
564 1 Name: Total Filament, Length: 806, dtype: int64

我的SGD代码:


from sklearn.linear_model import SGDRegressor
sgd_reg = SGDRegressor(max_iter=1000, tol=1e-3, penalty=None, eta0=0.1)
sgd_reg.fit(X, y.ravel())

我的错误代码:

ValueError: Expected 2D array, got 1D array instead: array=[1. 2. 1. ... 2. 2. 3.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

正如错误消息所建议的,您应该用X = X.reshape(-1, 1)重塑X

出现此错误是因为X是一个1D数组,您可以将其视为Python列表。把它想象成[row_1_x, row_2_x, ...]。但sklearn期望一个2D阵列,一个数据中每行多个特征的一维向量,[[row_1_x], [row_2_x], ...]

相关内容

最新更新