python-3.x - 在训练期间调试 keras 层的输出
问题描述
使用keras拟合模型时,遇到nans,想调试每一层的输出。
该代码有一个输入in1,它经过多个层,在最后一层中,我将元素与另一个输入in2相乘,然后进行预测。输入in2是稀疏的,用于屏蔽(一行类似于[0 0 0 1 0 0 1 0 1 0... 0])。标签矩阵包含 one-hot-encoded 行。输入in1是一个实数值向量。
in1 = Input(shape=(27,), name='in1')
in2 = Input(shape=(1000,), name='in2')
# Hidden layers
hidden_1 = Dense(1024, activation='relu')(in1)
hidden_2 = Dense(512, activation='relu')(hidden_1)
hidden_3 = Dense(256, activation='relu')(hidden_2)
hidden_4 = Dense(10, activation='linear')(hidden_3)
final = Dense(1000, activation='linear')(hidden_4)
# Ensure we do not overflow when we exponentiate
final2 = Lambda(lambda x: x - K.max(x))(final)
#Masked soft-max using Lambda and merge-multiplication
exponentiate = Lambda(lambda x: K.exp(x))(final2)
masked = Multiply()([exponentiate, in2])
predicted = Lambda(lambda x: x / K.sum(x))(masked)
# Compile with categorical crossentropy and adam
mdl = Model(inputs=[in1, in2],outputs=predicted)
mdl.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
tensorboard = TensorBoard(log_dir="/Users/somepath/tmp/{}".format(time()), write_graph=True,
write_grads=True)
mdl.fit({'in1': in1_matrix, 'in2': in2_matrix},
label_matrix, epochs=1, batch_size=32, verbose=2, callbacks=[tensorboard])
我想打印每一层的输出、训练期间的梯度以及调试时如何发送辅助输入( in2 )。
我试图打印每一层的输出,如下所示,直到 layer7:
get_layer_output = K.function([mdl.layers[0].input],[mdl.layers[7].output])
layer_output = get_layer_output([in1_matrix])
但是当我到达第 8 层时,我无法添加in2_matrix。使用以下代码打印时出现以下错误。
get_layer_output2 = K.function([mdl.layers[0].input],[mdl.layers[8].output])
layer_output2 = get_layer_output2([in1_matrix])
错误:
InvalidArgumentError:您必须使用 dtype float 和 shape [?,1000] 为占位符张量“in2”提供值
我不知道如何在 K.function 中提供in2,以及在get_layer_output2中提供in2_matrix。
(我检查了in1_matrix、in2_matrix和label_matrix。它们看起来都很好,没有 nans 或 inf。标签数组没有全为零的行或列。)
我是 Keras 的新手,任何关于如何调试 nans、回调甚至打印渐变的想法都将不胜感激。如果图层的组合方式有任何问题,也请告诉我。
解决方案
如果你打印出来mdl.layers[8]
,你会发现它是输入层,我猜你想要得到的输出mdl.layers[9]
,也就是乘法层。你可以这样,
get_layer_output2 = K.function([mdl.layers[0].input, mdl.layers[8].input],[mdl.layers[9].output])
layer_output2 = get_layer_output2([in1_matrix, in2_matrix])
推荐阅读
- python - 如何对数据透视表上的值进行分组?
- c++ - C++ MFC EditBox 处理双击
- javascript - 如何在页面加载之前保留或选择最后一个活动节点状态
- python - 在执行程序之前先检测文件是否存在
- linux-kernel - 如何在 beaglebone black 上找到 mini-usb 的串口?
- spring - Spring mvc 4 @PostMapping 或 @RequestMapping 暴露休息给出 415 响应
- java - 将值添加到 Java 中的列表是否会复制数据或创建引用?
- python - 如何在python中的特定单词之后替换下一个单词
- scala - 如何用分隔符在火花中爆炸
- regex - 基于 .htaccess 上的 IP 范围重定向