【问题标题】:Reshaping a numpy array results in TypeError重塑一个 numpy 数组会导致 TypeError
【发布时间】:2020-08-08 02:53:29
【问题描述】:

我正在关注 YouTube (https://www.youtube.com/watch?v=y1ZrOs9s2QA&feature=youtu.be) 上的教程,代码可以在这里找到:https://github.com/murtazahassan/Digits-Classification/blob/master/OCR_CNN_Trainning.py

但是当我尝试运行下面的代码时,我得到了错误:TypeError: only integer scalar arrays can be convert to a scalar index.

x_train = np.array(list(map(preprocess, x_train)))
x_test = np.array(list(map(preprocess, x_test)))
x_validation = np.array(list(map(preprocess, x_validation)))

x_train = x_train.reshape(x_train[0], x_train[1], x_train[2], 1)
x_test = x_test.reshape(x_test[0], x_test[1], x_test[2], 1)
x_validation = x_validation.reshape(x_validation[0], x_validation[1], x_validation[2], 1)

我找到了这个 (TypeError: only integer scalar arrays can be converted to a scalar index , while trying kfold cv) 和这个 (TypeError when indexing a list with a NumPy array: only integer scalar arrays can be converted to a scalar index),但它对我没有帮助。我做错了什么?

【问题讨论】:

  • 使用 numpy,如果你对所有数组都执行name.dtype,你会得到什么?
  • @duckboycool 我得到 float64

标签: python numpy


【解决方案1】:

您正在向reshape 传递不属于int 类型的值:

x_train = x_train.reshape(x_train[0], x_train[1], x_train[2], 1)

在这里,例如,x_train[0] 需要是 int 类型(其他类型也是如此)。如果您打算使用它们的形状而不是它们的值,请使用:

x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1)

否则,您有两种选择:

  1. 如果您知道 x_trainx_testx_validation 中的值是整数,请将它们的 dtype 设置为 int(并确保它在 ML 操作期间保持不变:

    x_train = np.array(list(map(preprocess, x_train)), dtype=np.int)
    x_test = np.array(list(map(preprocess, x_test)), dtype=np.int)
    x_validation = np.array(list(map(preprocess, x_validation)), dtype=np.int)
    
  2. 如果您需要它们为float 但又想将它们称为int,请使用:

    x_train = x_train.reshape(int(x_train[0]), int(x_train[1]), int(x_train[2]), 1)
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 2011-10-01
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2016-02-10
    相关资源
    最近更新 更多