【问题标题】:ValueError: Input 0 of layer sequential_4 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: (None, 1188, 6)ValueError: 层序号_4 的输入 0 与层不兼容:预期 ndim=4,发现 ndim=3。收到的完整形状:(无,1188,6)
【发布时间】:2023-03-17 15:07:02
【问题描述】:

我已经使用以下代码实现了一个模型。


model=models.Sequential()
model.add(tf.keras.layers.DepthwiseConv2D((3, 5), padding='valid', depth_multiplier=10, input_shape=(1188,1188,1)))


model.add(layers.MaxPooling2D((3,3), strides=(1, 1)))
model.add(layers.Dropout(.2))
model.add(tf.keras.layers.DepthwiseConv2D((2, 4), padding='valid', depth_multiplier=2))
model.add(layers.MaxPooling2D((2,2), strides=(1, 1)))
model.add(layers.Dropout(.2))
model.add(tf.keras.layers.DepthwiseConv2D((2, 2), padding='valid', depth_multiplier=2))
model.add(layers.MaxPooling2D((3,2), strides=(1, 2)))
model.add(layers.Dropout(.2))
model.add(layers.Flatten())

model.add(layers.Dense(5))

model.summary()

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(f1, labels1,batch_size=20,epochs=10)

f1labels1的形状分别是(1188, 1188, 6)(1188, 1188, 1)

运行后,我得到这个错误-: ValueError: Input 0 of layer sequential_4 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: (None, 1188, 6)

我还尝试在模型中使用input shape=(1188,1188)

但我在运行模型时出错-:ValueError: Input 0 of layer depthwise_conv2d is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: (None, 1188, 1188)

我在选择输入形状时是否犯了错误?

如果是,我应该做什么样的修改?

谢谢

【问题讨论】:

    标签: python tensorflow keras deep-learning


    【解决方案1】:

    我认为您需要将数据以 4 个维度分批传递给您的模型。例如,如果您的批量大小为 1,则以以下形状传递输入:(1,1188,1188,6)。

    编辑:

    在 TensorFlow 中训练模型时,应将训练数据批量传递给模型。批处理是一组图像(例如 64 张图像),其第一个维度是批处理大小。

    假设您的数据集有 6400 张图像,大小为 28*28*3,并且您将批量大小设置为 64,那么您应该将训练输入提供给形状为 (64,28,28,3) 的模型。为了实现这一点,您可以执行以下操作:

    import random
    import numpy as np
    
    for i in range(int(x_train.shape[0]/batch_size)):
              if len(list_of_samples) < batch_size:
                list_of_samples = [i for i in range(0, x_train.shape[0])]
              indexes = random.sample(list_of_samples, batch_size)
              for j in indexes:
                list_of_samples.remove(j)
              x_batch = x_train[indexes, :]
              y_true_batch = y_train[indexes]
              feed_dict = {x: x_batch, y_true: y_true_batch}
              session.run(optimizer, feed_dict=feed_dict)
    
    

    【讨论】:

    • 你能再解释一下吗?我应该应用这个还是这只是一个例子?
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2020-11-15
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2021-08-01
    • 2020-11-16
    • 2021-01-24
    • 2021-10-08
    相关资源
    最近更新 更多