KERAS 中的自身损失函数 [英] Own Loss Function in KERAS

查看:27
本文介绍了KERAS 中的自身损失函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 如何定义我自己的损失函数,它需要 Keras 中先前层的权重和偏差参数?

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆