python - 损失字典中的未知条目:仅预期以下键 ['conv1d_4', 'conv1d_4']
问题描述
我有一个具有多个输出的模型。我想为每个损失函数和指标分配不同的标签。代码如下:
input_img = Input(shape=(n_states,n_features))
x = Conv1D(32, kernel_size=5, activation='relu', padding='same')(input_img)
x = Conv1D(32, kernel_size=5, activation='relu', padding='same')(x)
x = Conv1D(32, kernel_size=5, activation='relu', padding='same')(x)
decoded = Conv1D(n_outputs, kernel_size=3, activation='linear', padding='same')(x)
model = Model(inputs=input_img, outputs=[decoded,decoded])
model.compile(loss={'regression': 'mean_squared_error',
'diffusion': 'mean_absolute_error'},
loss_weights={'regression': 1.0,
'diffusion': 0.5},
optimizer='adam',
metrics={'regression': coeff_determination,
'diffusion': coeff_determination})
model.summary()
history_callback = model.fit(x_train,
{'regression': y_train, 'diffusion': y_train},
batch_size=batch_size,
epochs=epochs,
validation_data= (x_valid, {'regression': y_valid, 'diffusion': y_valid}),
verbose=1)
如果我运行上述模型,我会在损失字典中收到未知条目的错误。具体来说,错误是Unknown entries in loss dictionary: ['diffusion', 'regression']. Only expected following keys: ['conv1d_4', 'conv1d_4']
。
如何为每个损失函数赋予不同的名称?谢谢你。
解决方案
您需要将输出名称与损失字典键匹配。在这里,您没有命名输出,因此它们默认conv1d_4
位于名称空间中。尝试:
decoded1 = Conv1D(n_outputs, kernel_size=3, activation='linear',
padding='same', name='diffusion')(x)
decoded2 = Conv1D(n_outputs, kernel_size=3, activation='linear',
padding='same', name='regression')(x)
我将您的输出加倍,因为我认为您不能将两种不同的损失应用于相同的输出。
这是匹配输出/损失字典键的最小示例:
from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Dense
import numpy as np
x_train = np.random.rand(1000, 10)
y_train = np.random.rand(1000)
inputs = Input(shape=(10,))
x = Dense(32, activation='relu')(inputs)
out1 = Dense(1, name='first_output')(x)
out2 = Dense(1, name='second_output')(x)
model = Model(inputs=inputs, outputs=[out1, out2])
model.compile(loss={'first_output': 'mean_squared_error',
'second_output': 'mean_absolute_error'},
optimizer='adam')
history_callback = model.fit(x_train,
{'first_output': y_train, 'second_output': y_train},
batch_size=8, epochs=1)
请注意,损失字典键与输出键匹配。指标、损失权重、验证数据等也应该这样做。
推荐阅读
- javascript - Javascript Onclick 滚动和高亮示例
- android - 一起使用 ARCore 和 Vision SDK Android
- django - Django 应用 + 第 3 方的模板目录
- javascript - 检索子路由时的 Node.js 404
- perl - Apache Spark 的 perl API?
- clang - Clang 构建失败并失败:lib/libLTO.so.7
- python - 无法安装任何软件包 - EnvironmentError [Errno 2]
- django - How to check new posts since users last login Django
- google-cloud-platform - Request Denied forever - 请求增加 Google Cloud 中的 gpu 配额
- javascript - 需要 Javascript(或 JQuery)长字符串搜索和 CSS 插入帮助