gpt4 book ai didi

python - Keras自定义损失函数访问python全局变量时的内部机制是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:59 26 4
gpt4 key购买 nike

Keras 自定义损失函数是否接受全局 python 变量?

我正在构建自己的 Keras 自定义损失函数,它只接受 y_true 和 y_pred 作为参数。但是损失函数非常复杂,并且取决于其他变量。目前在我的实现中,损失函数只是直接使用同一个Python代码脚本中的全局变量。在训练模型后,如果我想使用模型进行预测,那么Python环境中的那些全局变量将被更改。我的问题是,我是否需要再次编译模型,以保证模型已使用这些外部全局变量的最新版本进行更新?

Rlist=....

def custom_loss(y_true,y_pred):
z = 0.0
#Rlist is the global variable
for j in Rlist:
z = z +K.log(K.sum(K.exp(K.gather(y_pred,j[0])))) \
- K.log(K.sum(K.exp(K.gather(y_pred,j))))
z = -z
return z
#below build the model and compile it with loss=custom_loss
model=...
model.compile(loss=custom_loss,....
model.fit(x=train_x,y=train_y,...)
#Rlist=... update Rlist which is adaptive to test dataset
#Do I need to recompile in the code below,or whether Rlist is updated
#in custom_loss when it is called?
model.predict(x=test_x,y=test_y,...)

在我的损失函数中(实际上这是cox比例风险模型的损失函数),损失不是每个样本的损失值之间的累加。Rlist 是我的 Keras 代码的 python 环境中的全局变量我的问题是,在训练模型后,如果我将这个 Rlist 更改为测试数据集,Keras会自动更新Rlist,还是在编译和构建计算图时使用该变量Rlist的旧版本?

是否有任何解释,如果我在损失函数中直接引用Python环境中的全局变量,那么当Tensorflow构建其计算图时会发生什么?我知道使用全局变量不是一个好的做法。还建议更好的建议。

最佳答案

“我的 Keras 代码的 python 环境”到底是什么意思?如果在训练时将代码中的 Rlist 变量设置为 [1,2,3]。然后在预测/生产模式下将其更改为[3,2,1],您的自定义损失将看到[3,2,1]变量。

我不确定你想要实现什么,我想这可以工作:A)用RList创建一个真正的ENV_VariableB) 使用 RList 创建 JSON 文件(这样,您就可以在服务器或云上的生产模式下使用 RList 数据)。C)在代码中创建一个字典,例如

RList={
'train': [1,2,3],
'test':[3,2,1],
'production':[4,5,6]
}

关于python - Keras自定义损失函数访问python全局变量时的内部机制是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53918084/

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