【问题标题】:tensorflow use input in loss function张量流在损失函数中使用输入
【发布时间】:2021-10-15 15:47:43
【问题描述】:

我正在使用 tensorflow/keras,我想在损失函数中使用输入

按照这里的答案

Custom loss function in Keras based on the input data

我就这样创建了我的损失函数

def custom_Loss_with_input(inp_1):
    def loss(y_true, y_pred):
        b = K.mean(inp_1)
        return y_true - b
    return loss
    

并设置具有层的模型,所有结束都像这样


    model = Model(inp_1, x)    
    model.compile(loss=custom_Loss_with_input(inp_1), optimizer= Ada)   
    return model

但是,我收到以下错误:

TypeError: Cannot convert a symbolic Keras input/output to a numpy array. This error may indicate that you're trying to pass a symbolic value to a NumPy call, which is not supported. Or, you may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model.

关于如何消除此错误的任何建议? 提前致谢

【问题讨论】:

    标签: python python-3.x tensorflow keras tensorflow2.0


    【解决方案1】:

    您可以使用add_loss 将外部层传递给您的损失,在您的情况下是输入张量。

    这里是一个例子:

    def CustomLoss(y_true, y_pred, input_tensor):
        b = K.mean(input_tensor)
        return K.mean(K.square(y_true - y_pred)) + b
    
    X = np.random.uniform(0,1, (1000,10))
    y = np.random.uniform(0,1, (1000,1))
    
    inp = Input(shape=(10,))
    hidden = Dense(32, activation='relu')(inp)
    out = Dense(1)(hidden)
    target = Input((1,))
    model = Model([inp,target], out)
    
    model.add_loss( CustomLoss( target, out, inp ) )
    model.compile(loss=None, optimizer='adam')
    model.fit(x=[X,y], y=None, epochs=3)
    

    如果您的损失由不同的部分组成,并且您想跟踪它们,您可以添加与损失部分相对应的不同损失。这样,损失会在每个 epoch 结束时打印出来,并存储在model.history.history 中。请记住,训练期间最小化的最终损失是各个损失部分的总和。

    def ALoss(y_true, y_pred):
        return K.mean(K.square(y_true - y_pred))
    
    def BLoss(input_tensor):
        b = K.mean(input_tensor)
        return b
    
    X = np.random.uniform(0,1, (1000,10))
    y = np.random.uniform(0,1, (1000,1))
    
    inp = Input(shape=(10,))
    hidden = Dense(32, activation='relu')(inp)
    out = Dense(1)(hidden)
    target = Input((1,))
    model = Model([inp,target], out)
    
    model.add_loss(ALoss( target, out ))
    model.add_metric(ALoss( target, out ), name='a_loss')
    model.add_loss(BLoss( inp ))
    model.add_metric(BLoss( inp ), name='b_loss')
    model.compile(loss=None, optimizer='adam')
    model.fit(x=[X,y], y=None, epochs=3) 
    

    要在推理模式下使用模型(从输入中删除目标):

    final_model = Model(model.input[0], model.output)
    final_model.predict(X)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2017-09-02
      • 2019-02-11
      • 2018-09-18
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      相关资源
      最近更新 更多