连接 numpy 数组时出现值错误

Value error while concatenating the numpy arrays

我正在加载 mnist 数据集如下,

(X_train, y_train), (X_test, y_test) = mnist.load_data()

然而,由于我需要加载和训练我自己的数据集,我编写了如下小脚本,它将给出准确的训练和测试值

def load_train(path):
X_train = []
y_train = []
print('Read train images')
for j in range(10):
    files = glob(path + "*.jpeg")
    for fl in files:
        img = get_im(fl)
        print(fl)
        X_train.append(img)
        y_train.append(j)

return np.asarray(X_train), np.asarray(y_train)

相关模型在训练时生成一个大小为 (64, 28, 28, 1) 的 numpy 数组。我从生成的图像中连接 image_batch,如下所示,

    X = np.concatenate((image_batch, generated_images))

但是我收到以下错误,

ValueError: all the input arrays must have same number of dimensions

img_batch 大小为 (64, 28, 28) generated_images 大小为 (64, 28, 28, 1)

如何扩展 X_train 中 img_batch 的维度以便与 generated_images 连接?还是有其他方法可以代替 loadmnist 加载自定义图像?

image_batch = image_batch.reshape(64, 28, 28, 1)

python 中有一个名为 np.expand_dims() 的函数,它可以沿着参数中提供的轴扩展任何数组的维度。在您的情况下使用 img_batch = np.expand_dims(img_batch, axis=3).

另一种方法是使用@Ioannis Nasios 建议的 reshape 函数。 img_batch = img_batch.reshape(64,28,28,1)