【问题标题】:Cannot reshape array of size 0 into shape无法将大小为 0 的数组重塑为形状
【发布时间】:2020-10-15 19:16:25
【问题描述】:

对我正在使用的程序进行更正后,我的代码出现错误:

import numpy as np
import gzip
import struct


def load_images(filename):
    # Open and unzip the file of images :
    with gzip.open(filename, 'rb') as f:
        # read the header, information into a bunch of variables:
        _ignored, n_images, image_columns, image_rows = struct.unpack('>IIII', bytearray(f.read()[:16]))
        print(_ignored, n_images, image_columns, image_rows)
        print(f.read()[:16])
        # read all the pixels into a long numpy array :
        all_pixels = np.frombuffer(f.read(), dtype=np.uint8)
        print(all_pixels)
        print(all_pixels.shape)
        print(all_pixels.ndim)
        # reshape the array into a matrix where each line is an image:
        images_matrix = all_pixels.reshape(n_images, image_columns * image_rows)

我收到此错误:

load_images("\\MNIST\\train-images-idx3-ubyte.gz")
2051 60000 28 28
b''
[]
(0,)
1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 19, in load_images
ValueError: cannot reshape array of size 0 into shape (60000,784)

我试图定义数组,但还是不行......

【问题讨论】:

    标签: python arrays pandas


    【解决方案1】:

    您读取()文件两次。第一次读取后,光标位于底部。因此,如果您再次阅读,它不会返回任何内容。

    您的对象是空的,因此无法调整大小。

    更多信息请点击here

    【讨论】:

      【解决方案2】:

      问题在于,在应该从文件 (all_pixels = np.frombuffer(f.read(), dtype=np.uint8)) 中获取数据的行中,对 f.read() 的调用不会读取任何内容,从而导致一个空数组,您无法对其进行整形,显然原因。

      根本原因是file.read() 不带任何参数将读取/消耗打开文件中的所有字节。因此,在下一次 file.read() 调用时,您位于文件的末尾,并且没有获取任何内容。

      相反,您似乎希望将前 16 个字节作为标头读取,并将其余字节作为数据读取。

      为此,您应该将第一次调用 .read() 替换为您要为标头读取的字节数。

      这将确保您只读取前几个字节,其余的由后续的f.read() 调用读取:

      import numpy as np
      import gzip
      import struct
      
      
      def load_images(filename):
          # Open and unzip the file of images :
          with gzip.open(filename, 'rb') as f:
              header = f.read(16)  # read the header bytes
              # read the header, information into a bunch of variables:
              _ignored, n_images, image_columns, image_rows = struct.unpack('>IIII', bytearray(header))
              print(_ignored, n_images, image_columns, image_rows)
              print(header)
              # read all the pixels into a long numpy array:
              data = f.read()  # read the data bytes
              all_pixels = np.frombuffer(data, dtype=np.uint8)  
              print(all_pixels)
              print(all_pixels.shape)
              print(all_pixels.ndim)
              # reshape the array into a matrix where each line is an image:
              images_matrix = all_pixels.reshape(n_images, image_columns * image_rows)
      

      【讨论】:

        猜你喜欢
        • 2019-08-23
        • 2020-02-18
        • 2020-04-14
        • 2020-10-05
        • 2020-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多