tensorflow 在损失函数中使用输入

tensorflow use input in loss function

我正在使用tensorflow/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.

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

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