Python数组整形

2024-04-25 13:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个数组(1000,28,28)重塑成一个数组(1000784),其中两个28相乘,得到一个784,然后卡住了。如有任何建议,将不胜感激。在

抱歉,更具体地说,我正在尝试导入MNIST数据集,如下所示:

import numpy as np
import struct
import io
def read_idx(filename):
with open(filename,'rb',)as f:
    zero, data_type, dims = struct.unpack('>HBB', f.read(4))
    shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))

    return np.fromstring(f.read(), dtype=np.uint8).reshape(shape)
data= read_idx("t10k-images.idx3-ubyte")
x=data
len(x)
a=np.array(x)
print(a.shape)
a= np.reshape(x,(1000,784))

Tags: importreaddataasnp数组filename建议
2条回答

我很蠢,错过了一个零这个修正了一切:

a= np.reshape(a,(10000,784))

如果我可以在解的基础上再加一点,这样你就可以得到同样的答案,而不必注意数组的确切形状。如果明天尺寸发生变化,下面的代码仍然有效;只要它仍然是三维的。干杯!在

arr = np.zeros((1000,28,28))
new_arr = arr.reshape(*arr.shape[:1], -1)
print(new_arr.shape)

相关问题 更多 >