keras中自定义loss层如何接受输入值的案例
导读:本文共2811字符,通常情况下阅读需要9分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: loss函数如何接受输入值keras封装的比较厉害,官网给的例子写的云里雾里,在stackoverflow找到了答案You can wrap the loss function as a inner function and pass your input tensor to it (as commonly done when passing additiona... ...
目录
(为您整理了一些要点),点击可以直达。loss函数如何接受输入值
keras封装的比较厉害,官网给的例子写的云里雾里,
在stackoverflow找到了答案
You can wrap the loss function as a inner function and pass your input tensor to it (as commonly done when passing additional arguments to the loss function).
You can verify that input_tensor and the loss value will change as different X is passed to the model.
fit_generator
fit_generator ultimately calls train_on_batch which allows for x to be a dictionary.
Also, it could be a list, in which casex is expected to map 1:1 to the inputs defined in Model(input=[in1, …], …)
补充知识:keras中自定义 loss损失函数和修改不同样本的loss权重(样本权重、类别权重)
首先辨析一下概念:
1. loss是整体网络进行优化的目标, 是需要参与到优化运算,更新权值W的过程的
2. metric只是作为评价网络表现的一种“指标”, 比如accuracy,是为了直观地了解算法的效果,充当view的作用,并不参与到优化过程
一、keras自定义损失函数
在keras中实现自定义loss, 可以有两种方式,一种自定义 loss function, 例如:
或者通过自定义一个keras的层(layer)来达到目的, 作为model的最后一层,最后令model.compile中的loss=None:
在keras中自定义metric非常简单,需要用y_pred和y_true作为自定义metric函数的输入参数 点击查看metric的设置
注意事项:
1. keras中定义loss,返回的是batch_size长度的tensor, 而不是像tensorflow中那样是一个scalar
2. 为了能够将自定义的loss保存到model, 以及可以之后能够顺利load model, 需要把自定义的loss拷贝到keras.losses.py 源代码文件下,否则运行时找不到相关信息,keras会报错
有时需要不同的sample的loss施加不同的权重,这时需要用到sample_weight,例如
discriminator.train_on_batch(imgs, [valid, labels], class_weight=class_weights)
二、keras中的样本权重
Note that the output of the class_weight.compute_class_weight() is an numpy array like this: [2.57569845 0.68250928].
keras中自定义loss层如何接受输入值的案例的详细内容,希望对您有所帮助,信息来源于网络。