在渴望模式下将输入传递给损失函数

这里窃取示例代码:

def custom_loss_wrapper(input_tensor):    def custom_loss(y_true, y_pred):        return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor)    return custom_lossinput_tensor = Input(shape=(10,))hidden = Dense(100, activation='relu')(input_tensor)out = Dense(1, activation='sigmoid')(hidden)model = Model(input_tensor, out)model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam')X = np.random.rand(1000, 10)y = np.random.rand(1000, 1)model.train_on_batch(X, y)

在最近的Tensorflow版本中,这不再有效。我看到的主要解决方案是禁用渴望执行,但这会破坏我正在做的其他事情。

如何在保持渴望模式的同时维持这种功能?也就是说,将输入传递给损失函数?我能想到的最好方法是修改网络,将输入连接到输出,然后在损失中拆分它。不过这非常笨拙。


回答:

你可以使用add_loss将外部层传递给你的损失,在你的例子中就是输入张量。

这是一个例子:

def CustomLoss(y_true, y_pred, input_tensor):    return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor)X = np.random.uniform(0,1, (1000,10))y = np.random.randint(0,2, (1000,1))inp = Input(shape=(10,))hidden = Dense(100, activation='relu')(inp)out = Dense(1, activation='sigmoid')(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)

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

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注