【问题标题】:Implementing 3-Tensor (NHW) CNN in TensorFlow / Keras在 TensorFlow / Keras 中实现 3-Tensor (NHW) CNN
【发布时间】:2021-06-14 13:55:45
【问题描述】:

我想用 Keras 实现一个 CNN 模型。我的数据分别具有形状 NHW (N, 40, 4)。您可以将其视为 40x4 大小的灰度图像。我想跨过高度轴大小为 (3, 4) 的内核,因此它应该计算 3 个完整行的结果。如您所见,没有通道(这意味着我有一个 3-Tensor),但 Keras Conv2D 层需要 NHWC(4-Tensor)的形状。我无论如何通过以下命令尝试了它,但它显然会导致错误:

tf.keras.layers.Conv2D(8, kernel_size=(3, 4), activation="relu", input_shape=(40, 4)

ValueError:层顺序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:(1, 40, 4)

因此,我尝试将一个新轴附加到我的输入数据中,它应代表通道。

np.expand_dims(input_data, axis=3)

...

tf.keras.layers.Conv2D(1, kernel_size=(3, 4), activation="relu", input_shape=(40, 4, 1), data_format="channels_last")

这会导致不同的错误消息:

ValueError: Shape mismatch: The shape of labels (received (1,)) should equal the shape of logits except for the last dimension (received (40, 5)).

你知道我如何实现这样一个输入形状为 NHW 的 CNN 模型吗?

【问题讨论】:

  • This 的问题与我的类似,解决了我的问题。

标签: python tensorflow keras conv-neural-network


【解决方案1】:

Conv2D 期望 4D 张量,形状为:batch_shape + (channels, rows, cols) if data_format='channels_first' 或 4+D 张量,形状:batch_shape + (rows, cols, channels) if data_format='channels_last'

灰度图像通道值为 1,RGB 图像值为 3。

import tensorflow as tf
input_shape = (4, 28, 28, 1)
x = tf.random.normal(input_shape)
y = tf.keras.layers.Conv2D(
2, 3, activation='relu', input_shape=input_shape[1:])(x)
print(y.shape)

输出

(4, 26, 26, 2)

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 2017-04-13
    • 2017-01-27
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 2019-09-14
    相关资源
    最近更新 更多