【问题标题】:ValueError: could not broadcast input array from shape (26000,1) into shape (26000) for sklearn preprocessing StandardScalerValueError:无法将输入数组从形状(26000,1)广播到形状(26000)以进行sklearn预处理StandardScaler
【发布时间】:2021-06-02 04:41:18
【问题描述】:

我正在开发具有多个功能(或列)的numpy array X

我正在尝试标准化数据集的第一个特征(列):

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()

X[:,0] = sc.fit_transform(X[:,0].reshape(-1,1))

我得到这个错误:

ValueError: could not broadcast input array from shape (26000,1) into shape (26000)

如果我删除 reshape(-1,1),则会收到此错误:

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.

我该如何解决这个问题?

提前致谢!

【问题讨论】:

  • 你试过用 (1, -1) 吗?
  • or array.reshape(1, -1) if it contains a single sample.

标签: python arrays numpy scikit-learn


【解决方案1】:

我将把这个答案分成两部分。先了解 StandardScaler 的 fit_tansform 函数的输入,再了解输出。

如果您遵循 fit_transform 函数的 StandardScaler 文档,它会说:

参数:X 类形状的数组 (n_samples, n_features) 输入样本。

返回 X_newndarray 形状数组 (n_samples, n_features_new)

理解输入:

在这里,当您执行 X[:,0] 时,您将获得整列,但在一行中。这是一个随机 3x2 数组的示例:

import numpy as np
X = np.random.random_sample((3,2))*10
print(X)
print(X[:,0])
print(X[:,0].shape)

给予

[[3.5782437  6.12481959]
 [9.2333248  8.49628361]
 [8.56447626 5.24588392]]

[3.5782437  9.2333248  8.56447626]

(3,)

这是我们的第一个问题。 StandardScaler 需要一个二维数组,其中行是每个样本,列是特征,在本例中是 1 个特征。因此,我们需要一个 (3x1) 二维数组,但我们有一个 (3,) 一维数组。这会导致您在没有重塑的情况下得到错误。要将我们的一维数组转换为函数期望的形状,我们使用reshape。该函数需要一个 shape 参数。我们想要一个 (3x1) 形状,因此,使用 reshape(-1,1) (-1 表示 numpy 将推断我们想要所有元素)。 要确认这一点:

print(X[:,0].reshape(-1,1))

给予

[[9.31648164]
 [6.74048286]
 [7.57667118]]

现在,我们准备将其输入到 StandardScaler 的 fit_transform 中。 二、fit_transform的输出: 让我们看看它的输出的形状:

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
print(sc.fit_transform(X[:,0].reshape(-1,1)))
print(sc.fit_transform(X[:,0].reshape(-1,1)).shape)

给予

[[ 1.34073239]
 [-1.06001668]
 [-0.28071571]]
(3, 1)

当 X[:,0] 实际上是一个 (3,) 一维数组时,我们得到一个 3x1 二维数组。我们想将此数组展平为一维数组。有多种方法可以做到这一点。我们可以再次使用 reshape,给一个值表示一维数组,-1 表示所有值:

temp = sc.fit_transform(X[:,0].reshape(-1,1)).reshape(-1)
print(temp)
print(temp.shape)

给予

[ 1.34073239 -1.06001668 -0.28071571]
(3,)

这意味着X[:,0] = sc.fit_transform(X[:,0].reshape(-1,1)).reshape(-1) 可以工作。

使用ravelflatten 也可以。

【讨论】:

  • 这是一个非常全面和彻底的答案,谢谢!
【解决方案2】:

sc.fit_transform(X[:,0].reshape(-1,1)) 是一个形状为(26000,1) 的二维数组,您不能将其分配给形状为(26000)1D 占位符X[:,0]

分配回来时尝试使配合变平:

X[:,0] = sc.fit_transform(X[:,0].reshape(-1,1)).ravel()

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 2018-06-08
    • 2020-01-21
    • 2020-10-18
    • 2018-09-25
    • 2018-04-21
    • 2020-10-09
    • 2021-03-30
    • 2021-08-24
    相关资源
    最近更新 更多