gpt4 book ai didi

python-3.x - 无法将大小数组 reshape 为形状

转载 作者:行者123 更新时间:2023-12-04 12:10:36 24 4
gpt4 key购买 nike

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

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: cannot reshape array of size 9992 into shape (1,28,28).我该如何解决?在教程中它正在工作。另外,如果我有任何其他错误,请告诉我。

最佳答案

您的输入与输出数组的元素数量不同。您的输入大小为 9992。您的输出大小为 [? x 1 x 28 x 28] 因为 -1 表示 reshape 命令应该确定沿着这个维度需要多少个索引来适应你的数组。 28x28x1 是 784,所以任何你想 reshape 到这个尺寸的输入都必须能被 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,则需要将输入重新整形为不同大小的数组,以使其正确适合。

关于python-3.x - 无法将大小数组 reshape 为形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60028853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com