gpt4 book ai didi

python - 当为具有多个输出的模型尝试 train_on_batch 时,Keras 中的 sample_weight 出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:43 27 4
gpt4 key购买 nike

我正在使用 Keras 训练深度神经网络。我使用 train_on_batch 函数来训练我的模型。我的模型有两个输出。我打算做的是通过每个样本的某个特定值来修改每个样本的损失。所以由于 Keras 文档 here

我需要为 sample_weight 参数分配两个不同的权重。这是我的代码的样子,其中每批,我有四个训练示例:

wights=[12,10,31,1];  
mod_loss = mymodel.train_on_batch([X_train], [Y1, Y2],sample_weight=[wights,[1.0,1.0,1.0,1.0]])

我使用 sample_weight 仅对第一个输出进行加权,而不对第二个输出进行加权。当我运行代码时,出现此错误:

  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 1211, in train_on_batch
class_weight=class_weight)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 801, in _standardize_user_data
feed_sample_weight_modes)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 799, in <listcomp>
for (ref, sw, cw, mode) in
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training_utils.py", line 470, in standardize_weights
if sample_weight is not None and len(sample_weight.shape) != 1:
AttributeError: 'list' object has no attribute 'shape'

它给了我一个想法,如果我将分配给 sample_weight 的值更改为 numpy 数组,问题就会得到解决。所以我把代码改成了这个:

wights=[12,10,31,1];  
mod_loss = mymodel.train_on_batch([X_train], [Y1, Y2],sample_weight=numpy.array([wights,[1.0,1.0,1.0,1.0]]))

我遇到了这个错误:

  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 1211, in train_on_batch
class_weight=class_weight)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training.py", line 794, in _standardize_user_data
sample_weight, feed_output_names)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training_utils.py", line 200, in standardize_sample_weights
'sample_weight')
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/keras/engine/training_utils.py", line 188, in standardize_sample_or_class_weights
str(x_weight))
TypeError: The model has multiple outputs, so `sample_weight` should be either a list or a dict. Provided `sample_weight` type not understood: [[12.0 10.0 31.0 1.0]
[ 1. 1. 1. 1. ]]

我有点困惑,我不确定这是否是 Keras 实现中的错误。我在网上几乎找不到与此相关的任何工作或问题。有什么想法吗?

最佳答案

我已经用另一种方式解决了这个问题。如果输出是 Y1 和 Y2,它们的层名称是 y1_layernamey2_layername 假设你想应用一个权重向量,只对 y2(其中 y2 是向量例如长度 4),你可以这样写你的代码:

wights=[12,10,31,1];  
mod_loss = mymodel.train_on_batch([X_train], [Y1, Y2],sample_weight={"y2_layername":wights})

我测试了一下,可以正常使用

关于python - 当为具有多个输出的模型尝试 train_on_batch 时,Keras 中的 sample_weight 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54918386/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com