KERAS中的自身损失功能 [英] Own Loss Function in KERAS
问题描述
-
如何定义自己的损失函数,该函数需要Keras先前各层的Weight和Bias参数?
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中的自身损失功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!