【问题标题】:Tensorflow Keras ValueError on input shape输入形状上的 Tensorflow Keras ValueError
【发布时间】:2021-08-18 18:31:31
【问题描述】:

我正在使用 TensorFlow Keras 做一个简单的 Conv1D 来尝试时间序列数据集。

数据:

train_df = dff[:177] #get train data
tdf = train_df.shape #get shape = (177,4)
test = tf.convert_to_tensor(train_df)

型号:

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv1D(filters=32,
                           kernel_size=1,
                           strides=1,
                           padding="causal",
                           activation="relu",
                           input_shape=tdf),
    tf.keras.layers.MaxPooling1D(pool_size=2, strides=1, padding="valid")
])

lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(5e-4,
                                                             decay_steps=1000000,
                                                             decay_rate=0.98,
                                                             staircase=False)
model.compile(loss=tf.keras.losses.MeanSquaredError(),
              optimizer=tf.keras.optimizers.SGD(learning_rate=lr_schedule, momentum=0.8),
              metrics=['mae'])
model.summary()

总结:

Model: "sequential_13"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv1d_16 (Conv1D)           (None, 177, 32)           160       
_________________________________________________________________
max_pooling1d_8 (MaxPooling1 (None, 176, 32)           0         
=================================================================
Total params: 160
Trainable params: 160
Non-trainable params: 0

适合:

trainedModel = model.fit(test,
                    epochs=100,
                    steps_per_epoch=1,
                    verbose=1)

@Fit 引发错误:

ValueError: Input 0 of layer sequential_13 is incompatible with the layer: : expected min_ndim=3, found ndim=2. Full shape received: (2, 1)

从各种 SO 来看,据说这是由于输入数据的形状造成的。所以我在 SO 中尝试了一个建议来重塑我的数据并重新输入它

重塑:

X_train=np.reshape(test,(test.shape[0], test.shape[1],1))

重塑后@Fit 引发错误:

ValueError: Input 0 of layer sequential_14 is incompatible with the layer: expected axis -1 of input shape to have value 4 but received input with shape (177, 4, 1)

我在这里不知所措。有什么办法解决这个问题?

【问题讨论】:

  • 您能否包含来自train_df 的几行数据,以便我们可以在我们的机器上重现这些数据以提供更好的帮助?

标签: python tensorflow machine-learning keras conv-neural-network


【解决方案1】:

当前参数值:

  1. tdf = (177,4) 我的假设 - “177 个训练样本有 4 个特征”。

当前错误的原因 - 模型假设每个样本的形状为 (177,4),但是当您尝试将其传递给模型时,就会出现错误

ValueError: Input 0 of layer sequential_13 is incompatible with the layer: :
expected min_ndim=3, found ndim=2. Full shape received: (2, 1)

此错误表示模型期望输入具有 3D 维度,在这种情况下,模型需要批量大小。说一组 16 张高度 = 177 和宽度 = 4 的图像。 (尽管您没有图像,但模型期望您指定输入形状的原因)。这意味着输入应该有一个形状 - (batch_size, 177, 4)。

这可以通过在model.fit 中传递参数batch_size=1 来解决。如下(不重塑数据)

trainedModel = model.fit(data,
                    epochs=100,
                    steps_per_epoch=1,
                    batch_size=16,
                    verbose=1)

但这会产生另一个错误,如下所示

ValueError: Input 0 of layer sequential_1 is incompatible with the layer: : 
expected min_ndim=3, found ndim=2. Full shape received: (None, 4)

现在这个错误意味着传递给模型的输入有一些由None 表示的batch_size 和一个形状为4 的特征向量,但模型希望输入的形状为(batch_size, height, width)。这里 batch_size 是所有模型所期望的,但其余 2 个由我们在定义输入形状时指定。我们在这里定义了这个:

tf.keras.layers.Conv1D(filters=32,
                           kernel_size=1,
                           strides=1,
                           padding="causal",
                           activation="relu",
                           input_shape=tdf), # Here We save input_shape = (177,4)

如您所见,input_shape 已定义为height=177, width=4。 (为了便于解释,我使用了高度和宽度,否则没有高度/宽度,只有尺寸编号)。但是,我们希望模型接受4 特征的输入。因此,现在我们必须将其更改为以下内容:

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv1D(filters=32,
                           kernel_size=1,
                           strides=1,
                           padding="causal",
                           activation="relu",
                           input_shape=(4,)),
    tf.keras.layers.MaxPooling1D(pool_size=2, strides=1, padding="valid")
])

但是现在当你尝试运行它时,你会得到另一个错误,如下所示:

ValueError: Input 0 of layer conv1d_10 is incompatible with the layer: : 
expected min_ndim=3, found ndim=2. Full shape received: (None, 4)

需要注意的是 Conv1D 引起的错误,这是因为该层需要 3D 输入,包括 batch_size,但我们在创建模型时从未指定 batch_size参数input_shape 应该具有类似input_shape = (dim1, dim2) 的值,但如果我们只有4 功能,因此只有dim1 而不是dim2。在这种情况下,我们将重塑我们的输入,使4 成为(4,1)。这样,我们将拥有dim1 = 4dim2 = 1。我们将更新我们的model 如下:

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv1D(filters=32,
                           kernel_size=1,
                           strides=1,
                           padding="causal",
                           activation="relu",
                           input_shape=(4,1)),
    tf.keras.layers.MaxPooling1D(pool_size=2, strides=1, padding="valid")
])

现在我们还重塑我们的输入,使其具有如下形状 (177,4, 1)

train_df = dff[:177]
train_df = train_df.values.reshape(177, 4, 1)
test = tf.convert_to_tensor(train_df)

现在我们可以使用它来传递给模型了。

trainedModel = model.fit(test,
                    epochs=100,
                    steps_per_epoch=1,
                    verbose=1)

遗憾的是,这会产生另一个错误,如下所示。

ValueError: No gradients provided for any variable: ['conv1d_14/kernel:0',
'conv1d_14/bias:0'].

这是因为模型没有得到任何与您的输入 X 相对应的 Y,因此它无法使用 loss function 计算 gradients,因此无法训练。但它仍然可以用来获得如下输出:

preds = model(test)
preds.shape # Result -> TensorShape([177, 3, 32])

【讨论】:

    猜你喜欢
    • 2017-08-14
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2016-06-23
    • 2020-03-16
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多