python-3.x - 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.
解决方案
您的输入与输出数组的元素数量不同。您的输入大小为 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,则需要将输入重新整形为一个不同大小的数组,以便正确匹配。
推荐阅读
- php - 使用 PHP 7.4 检测 fgetcsv 读入的行是否是 csv 文件的最后一行
- dart - 用飞镖刮html?
- flutter - Flutter,使用 Geolocator 包查找位置
- c# - 如何将标签绑定到 Xamarin.Forms 中的函数结果
- .net-core - 对象数组的 Avro 模式定义
- rest - 从 SoapUI 中的 REST 请求获取端点
- angular - 使用 Swagger 生成的 Angular API 客户端库通过 Angular 11 发布数据
- spring-data-jpa - 按 CriteriaBuilder 过滤标签
- java - Maven surefire-report 不在存储库中生成报告
- blazor - 如何遍历 Blazor 中的子组件