【问题标题】:What is the internal mechanism when a Keras custom loss function access a global variable of python?Keras自定义损失函数访问python全局变量时的内部机制是什么?
【发布时间】:2019-05-23 21:23:56
【问题描述】:

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

我正在构建自己的 Keras 自定义损失函数,它只接受 y_truey_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构建它的计算图时会发生什么? 我知道使用全局变量不是一个很好的做法。也推荐更好的建议。

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    “我的 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]
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 2017-12-18
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多