Python 无法将大小为0的数组重塑为形状
对我正在使用的程序进行更正后,我的代码出现错误:Python 无法将大小为0的数组重塑为形状,python,arrays,pandas,Python,Arrays,Pandas,对我正在使用的程序进行更正后,我的代码出现错误: 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:
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)
load_图像(\\MNIST\\train-images-idx3-ubyte.gz”)
2051 60000 28 28
b“
[]
(0,)
1.
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
加载图像中第19行的文件“”
ValueError:无法将大小为0的数组重塑为形状(60000784)
我试图定义数组,但仍然无法工作….您将()文件读取了两次。第一次读取后,光标被放置在底部。因此,如果您再次阅读,它不会返回任何内容
对象为空,因此无法调整大小
有关详细信息,请单击问题在于,在本应从文件中获取数据的行中(
all\u pixels=np.frombuffer(f.read(),dtype=np.uint8)
),对f.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)