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

标签 python tensorflow keras

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_Variable B) 使用 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/

相关文章:

python - 为什么DNN的acc小于1%

deep-learning - 如何使用keras微调inception v3做多类分类?

python - 使用故意弱私钥解密消息无限期挂起

python - Pip:如何覆盖requirements.txt中的子依赖版本?

machine-learning - 为什么我无法恢复这个模型?

python - 如何从保存的graph.pb中获取Session的Graph对象

python - keras中的因果填充

python - 验证 Django 中是否存在电子邮件

python - Django:未找到字段?

tensorflow - 使用张量板绘制单独的学习曲线