首页 > 解决方案 > Cannot reshape array of size into shape

问题描述

I am following a machine learning video on youtube at https://www.youtube.com/watch?v=lbFEZAXzk0g. The tutorial is in python2 so I need to convert it into python3. Here is the section of the code I am having an error with:

def load_mnist_images(filename):
    if not os.path.exists(filename):
        download(filename)
    with gzip.open(filename,'rb') as file:
        data = numpy.frombuffer(file.read(),numpy.uint8, offset=16)
        data = data.reshape(-1,1,28,28)
        return data/numpy.float32(256)

I am getting this error: ValueError: cannot reshape array of size 9992 into shape (1,28,28). How do I fix this? In the tutorial it was working. Also, if I have any other errors please tell me.

标签: python-3.xnumpypython-2.x

解决方案


您的输入与输出数组的元素数量不同。您的输入大小为 9992。您的输出大小为 [? x 1 x 28 x 28],因为 -1 表示 reshape 命令应确定沿此维度需要多少个索引才能适合您的数组。28x28x1 是 784,所以任何你想重塑到这个大小的输入都必须能被 784 整除,这样它才能适应输出形状。9992 不能被 784 整除,因此会抛出 ValueError。这是一个最小的例子来说明:

import numpy as np

data = np.zeros(2352) # 2352 is 784 x 3
out = data.reshape((-1,1,28,28)) # executes correctly -  out is size [3,1,28,28]

data = np.zeros(9992) # 9992 is 784 x 12.745 ... not integer divisible
out = data.reshape((-1,1,28,28)) # throws ValueError: cannot reshape array of size 9992 into shape (1,28,28)

因此,如果您不想要 ValueError,则需要将输入重新整形为一个不同大小的数组,以便正确匹配。


推荐阅读