Keras 函数 api 多输出

Keras functional api multioutput

为什么我可以不出错:

model2 = keras.Sequential([
    layers.Flatten(input_shape=[28,28]),
    layers.Dense(124, activation='relu'),
    layers.Dense(124, activation='relu'),
    layers.Dense(10, activation='softmax'),
])

但不是函数 api?:

input_ = layers.Input(shape=(28, 28))
hidden_a = layers.Dense(300, activation='relu')(input_)
hidden_b = layers.Dense(100, activation='relu')(hidden_a)
concat = layers.concatenate([input_,hidden_b])
output = layers.Dense(10, activation="softmax")(concat)
model3 = keras.Model(inputs = [input_], outputs= [output])

在拟合模型的时候,给出的错误是这样的:

InvalidArgumentError:  assertion failed: [Condition x == y did not hold element-wise:] [x (sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/Shape_1:0) = ] [32 1] [y (sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/strided_slice:0) = ] [32 28]
     [[node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/assert_equal_1/Assert/Assert (defined at \AppData\Local\Temp\ipykernel_395649426950.py:1) ]] [Op:__inference_train_function_131704]

谢谢

我想到了解决方案: 因为你不能使用 layers.Flatten() 作为你的第一层,你使用它作为你的第二层(duh) 答案:

input_ = layers.Input(shape=(28,28))
flatten = keras.layers.Flatten()(input_)
hidden_a = layers.Dense(124, activation='relu')(flatten)
hidden_b = layers.Dense(124, activation='relu')(hidden_a)
concat = layers.concatenate([flatten,hidden_b])
output = layers.Dense(10, activation="softmax")(concat)
model3 = keras.Model(inputs = input_, outputs= output)