应为2D数组,而应为1D数组

2024-10-03 11:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

from sklearn import MinMaxScaler, StandardScaler
import numpy as np

a = ([1,2,3],[4,5,6])
stan = StandardScaler()
mima = MinMaxScaler()
stan.fit_tranform(a)
mima.fit_transform(a)

results after runnin stan and mima

array([[-1., -1., -1.],
   [ 1.,  1.,  1.]])

array([[0., 0., 0.],
   [1., 1., 1.]])

但是,当我试图通过这样的一维数组时

^{pr2}$

我遇到了这样一个错误

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/anaconda3/lib/python3.6/site-packages/sklearn/base.py", line 517, in  fit_transform
return self.fit(X, **fit_params).transform(X)
File "/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/data.py",  line 308, in fit
return self.partial_fit(X, y) 
File "/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/data.py", line 334, in partial_fit
estimator=self, dtype=FLOAT_DTYPES)
File "/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py", line 441, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[0.05808361 0.86617615 0.60111501 0.70807258 0.02058449 0.96990985
0.83244264 0.21233911 0.18182497 0.18340451].
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.

GitHub上也有一个线程,但它早就关闭了。有什么办法解决这个问题吗。在


Tags: inpydatalibpackageslinesitetransform
1条回答
网友
1楼 · 发布于 2024-10-03 11:21:35

首先尝试了解MinMaxScalar和standardscalular在做什么。它们基于单个列标准化(或缩放)数据值。如果你的数据有3个列:-在

1)MinMaxScalar将分别从每列中找到最大值和最小值,并根据这些最小值和最大值缩放该列的其他值。所有列都相同。 2) StandardScalar同样会分别找到每列的平均值和标准差,然后进行缩放。在

然后,在这里查看我的答案,the explanation为什么它不接受一维数组。在

现在,您将以这些标量传递一个一维数组。他们怎么知道要缩放什么。有多少列?您是希望所有10个值都是一列,还是将所有10个值视为10列,这些列将彼此分开处理。不管是哪种情况,都是您必须相应地重塑数据,而scikit不会处理这些问题。在

1)如果希望它们是一个单独的列,请按如下方式重塑:

# Here first value -1 is for rows and second 1 for column
# This means you want the columns to be 1 and -1 
# will be configured automatically (10 in this case)
b = b.reshape(-1, 1) 

2)如果希望这10个值是10列的单行,请执行以下操作:

^{pr2}$

然后你可以这样做:

stan.fit_tranform(b)

但请注意,每种情况下的结果都会有所不同。在

相关问题 更多 >