我无法正确输入形状

I cannot get the input shape right

下面的代码给我一个输入错误,我无法理解。

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)(5002 个大小为 (2206,2) 的样本)。我试图在开头添加一个 Flatten() 层,但它给了我一个 object of type 'NoneType' has no len() 错误,即使这与 tf.keras 完美配合。我也为输入尝试了不同的形状,但其中 none 有效。所以它抛出以下错误之一

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()

如果你想使用密集层,输入应该是 (5002, 2206*2),即矩阵。 也许最简单的解决方案是在 "fit".

之前重塑输入 x_train

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

希望对您有所帮助。

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

指定要素名称的一种方法是添加 Input 图层:

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

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

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