【问题标题】:how to manipulate array in array如何在数组中操作数组
【发布时间】:2026-01-07 18:55:02
【问题描述】:

我有一个形状为(1433, 1)X_train np.array。第一个维度(1433)是训练图像的数量。第二个维度 (1) 是一个 np.array,它本身的形状为 (224, 224, 3)。我可以通过X_train[0][0].shape 确认。我需要将X_train 拟合到模型中:

model.fit([X_train, y_train[:,1:]], y_train[:,0], epochs=50, batch_size=32,  verbose=1)

错误输出不言自明:

    Traceback (most recent call last):
  File "/home/combined/file_01.py", line 97, in <module>
    img_output = Flatten()(x_1)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/base_layer.py", line 414, in __call__
    self.assert_input_compatibility(inputs)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/base_layer.py", line 327, in assert_input_compatibility
    str(K.ndim(x)))
ValueError: Input 0 is incompatible with layer flatten_1: expected min_ndim=3, found ndim=2

y_train[:,1:] 似乎可以使用 (1433, 9) 的形状。

model.fit 中的X_train 需要做什么才能成功输入为 (1433, 224, 224, 3)?

【问题讨论】:

  • 您能展示一下您是如何创建模型的吗?或模型摘要
  • @Sreeram TP 我能够解决这个问题,谢谢

标签: python arrays numpy numpy-ndarray


【解决方案1】:

你的情况好像是这样的:

import numpy as np
x_train = np.zeros((1433, 1), dtype=object)
for i in range(x_train.shape[0]):
    x_train[i, 0] = np.random.random((224, 224, 3))

x_train.shape        # (1433, 1)
x_train[0, 0].shape  # (224, 224, 3)

其中x_trainobject 数组(如嵌套列表)而不是numeric 数组。

您需要将x_train 更改为纯numeric 数组:

x_train = np.array([x for x in x_train.flatten()], dtype=float)
x_train.shape       # (1433, 224, 224, 3)
x_train[0].shape    # (224, 224, 3)

【讨论】:

  • 感谢您的帮助,它确实有助于匹配尺寸,但同样的错误继续发生。
  • 您好,经过一番查找后,我解决了这个问题,这是由于我的错误(将已经扁平化的输出变平),并且猜测您的答案起了重要作用。我会接受你的回答。