簡體   English   中英

預期的2D陣列,取而代之的是1D陣列

[英]Expected 2-D array, got 1-D array instead

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.]])

但是,當我試圖像這樣傳遞一維數組時,

b = np.random.random(10)
stan.fit_tranform(b)
mima.fit_transform(b)

我有這樣的錯誤

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上也有一個線程,但是很久以前就關閉了。 有什么辦法可以解決這個問題。

首先嘗試了解MinMaxScalar和StandardScalar的功能。 它們基於各個列對數據值進行標准化(或縮放)。 因此,如果您的數據有3列:

1)MinMaxScalar將分別從每個列中找到最大值和最小值,並根據那些最小值和最大值縮放該列的其他值。 所有列均相同。 2)StandardScalar將類似地分別找到每列的均值和標准差,然后進行縮放。

然后,在這里查看我的答案以解釋為什么它不接受一維數組。

現在,您正在這些標量中傳遞一維數組。 他們將如何知道要擴展什么。 有幾列? 您是否希望將所有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列的單行,請執行以下操作:

b = b.reshape(1, -1) 

然后,您可以執行以下操作:

stan.fit_tranform(b)

但是請注意,每種情況下的結果都會有所不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM