无法将大小数组重塑为形状 [英] Cannot reshape array of size into shape

查看:51
本文介绍了无法将大小数组重塑为形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 youtube 上观看机器学习视频,网址为 https://www.youtube.com/watch?v=lbFEZAXzk0g.该教程在python2中,所以我需要将其转换为python3.这是我遇到错误的代码部分:

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)

我收到此错误:ValueError:无法将大小为 9992 的数组重塑为形状 (1,28,28). 我该如何解决这个问题?在教程中它正在工作.另外,如果我有任何其他错误,请告诉我.

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.

推荐答案

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

Your input does not have the same number of elements as your output array. Your input is size 9992. Your output is size [? x 1 x 28 x 28] since the -1 indicates that the reshape command should determine how many indices along this dimension are necessary to fit your array. 28x28x1 is 784, so any input you want to reshape to this size must be neatly divisible by 784 so it fits in the output shape. 9992 is not divisible by 784, so it is throwing a ValueError. Here is a minimal example to illustrate:

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,则需要将输入重新整形为不同大小的数组,以使其正确匹配.

So, if you don't want a ValueError, you need to reshape the input into a differently sized array where it fits correctly.

这篇关于无法将大小数组重塑为形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆