问题描述
如何定义我自己的损失函数,它需要 Keras 中先前层的权重和偏差参数?
How can I define my own loss function which required Weight and Bias parameters from previous layers in Keras?
如何从每一层获得 [W1, b1, W2, b2, Wout, bout]?在这里,我们需要传递比平常更多的变量 (y_true, y_pred).我附上了两张图片供您参考.
How can I get [W1, b1, W2, b2, Wout, bout] from every layer? Here, we need to pass few more variable than usual (y_true, y_pred). I have attached two images for your reference.
我需要实现这个损失函数.在此处输入图片描述
I need to implement this loss function. enter image description here
推荐答案
为了回答你的第二部分,我使用以下代码来获取模型中每一层的规范以用于可视化目的:
To answer your second part, I used the following code to get the norm of every layer in my model for visualization purposes:
for layer in model.layers:
if('Convolution' in str(type(layer))):
i+=1
layer_weight = []
for feature_map in layer.get_weights()[0]:
layer_weight.append(linalg.norm(feature_map) / np.sqrt(np.prod(feature_map.shape)))
l_weights.append((np.sum(layer_weight)/len(layer_weight), layer.name, i))
weight_per_layer.append(np.sum(layer_weight)/len(layer_weight))
conv_weights.append(layer_weight)
现在要在损失函数中使用它,我会尝试这样的事情:
Now to use this in a loss function I would try something like this:
def get_loss_function(weights):
def loss(y_pred, y_true):
return (y_pred - y_true) * weights # or whatever your loss function should be
return loss
model.compile(loss=get_loss_function(conv_weights), optimizer=SGD(lr=0.1))
这篇关于KERAS 中的自身损失函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!