【问题标题】:I cannot get the input shape right我无法正确输入形状
【发布时间】:2020-05-15 13:16:46
【问题描述】:

以下代码给我一个输入错误,我无法弄清楚。

import tensorflow as tf
import neural_structured_learning as nsl
.
.
.
b_size = 132
m = tf.keras.Sequential()
m.add(tf.keras.layers.Dense(980, activation = 'relu', input_shape = (2206,2,)))

m.add(tf.keras.layers.Dense(560, activation = 'relu'))
m.add(tf.keras.layers.Dense(10, activation = 'softmax'))

adv_config = nsl.configs.make_adv_reg_config(multiplier=0.2, adv_step_size=0.5)
adv_model = nsl.keras.AdversarialRegularization(m, adv_config=adv_config)

adv_model.compile(optimizer = "adam",
                 loss = "sparse_categorical_crossentropy",
                 metrics = ['accuracy'])
adv_model.fit({"feature" : x_Train, "label" : y}, epochs = 50, batch_size=b_size)

我的 x_Train 的形状为 (5002, 2206, 2)(大小为 (2206,2) 的 5002 个样本)。我试图在开头添加一个Flatten() 层,但它给了我一个object of type 'NoneType' has no len() 错误,即使这与 tf.keras 完美配合。我也尝试过不同的输入形状,但它们都不起作用。所以它抛出了以下错误之一

KeyError: 'dense_115_input'

ValueError: Input 0 of layer sequential_40 is incompatible with the layer: expected axis -1 of input shape to have value 2206 but received input with shape [None, 2206, 2]

TypeError: object of type 'NoneType' has no len()

【问题讨论】:

    标签: python machine-learning keras tensorflow2.0 nsl


    【解决方案1】:

    要使用输入字典(如您的 {"feature" : x_Train, "label" : y})训练 NSL 模型,基本模型必须知道要查看字典中的哪些特征。

    指定特征名称的一种方法是添加Input 层:

    m = tf.keras.Sequential()
    m.add(tf.keras.Input(name="feature", shape=(2206, 2)))
    

    也正如this answer 所指出的,输入特征在传递到密集层之前必须被展平:

    m.add(tf.keras.layers.Flatten())
    m.add(tf.keras.layers.Dense(...))
    

    【讨论】:

      【解决方案2】:

      如果你想使用密集层,输入应该是(5002, 2206*2),即矩阵。 也许最简单的解决方案是在“适合”之前重塑您的输入 x_train。

      或者,您可以使用TimeDistributed 层(see here),但这种层的使用取决于输入维度背后的物理含义。基本上,TimeDistributed 多次应用某个操作,在你的情况下是两次。

      希望对您有所帮助。

      【讨论】:

      • 当我尝试仅使用 keras 训练模型时,它确实可以使用形状 (2206*2, ) 并重塑 x_Train (但只需在开始时添加一个扁平层就足以处理 keras 中的 input_shape ),但是当我尝试使用 nsl 的对抗正则化时,错误KeyError: 'dense_115_input 会弹出。而且我无法弄清楚 TimeDistributed 层。
      猜你喜欢
      • 2020-09-04
      • 1970-01-01
      • 2019-01-29
      • 2018-12-28
      • 2020-11-27
      • 2021-11-01
      • 2022-07-26
      • 2019-06-04
      • 1970-01-01
      相关资源
      最近更新 更多