首页 > 解决方案 > 张量流在损失函数中使用输入

问题描述

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

根据这里的答案

Keras 中基于输入数据的自定义损失函数

我因此创建了我的损失函数

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.

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

标签: pythonpython-3.xtensorflowkerastensorflow2.0

解决方案


您可以使用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)

推荐阅读