如何使用KERAS(TensorFlow)限制神经网络回归中的预测输出总和(TensorFlow) [英] How to restrict the sum of predicted outputs in a neural network regression using Keras (tensorflow)
本文介绍了如何使用KERAS(TensorFlow)限制神经网络回归中的预测输出总和(TensorFlow)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在训练Keras(python,后端:TensorFlow)中的神经网络作为回归。因此,我的输出层不包含激活函数,并且我使用均方误差作为我的损失函数。
我的问题是:我希望确保所有产量估计的总和(几乎)等于所有实际标签的总和。
我的意思是:我不仅要确保每个训练示例i的(Y_Real)^i~(Y_Recast)^i,而且要保证sum(Y_Real)=sum(Y_Recast),对所有i求和。规则线性回归使添加此限制变得足够简单,但我没有看到任何类似的神经网络。我可以将最终结果乘以sum(Y_Real)/sum(Y_Recast),但如果我不想损害个人预测,恐怕这不是理想的方法。我还有什么其他选择?
(我不能共享我的数据,也不能很容易地用不同的数据重现问题,但这是按要求使用的代码:)
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(128, activation = 'relu', input_dim = 459))
model.add(Dense(32, activation = 'relu'))
model.add(Dense(1))
model.compile(loss = 'mean_squared_error',
optimizer = 'adam')
model.fit(X_train, Y_train, epochs = 5, validation_data = (X_val,
Y_val), batch_size = 128)
推荐答案
从优化的角度来看,您希望向问题引入相等约束。您正在寻找网络权重,以使预测y1_hat, y2_hat and y3_hat
最小化标签y1, y2, y3
的均方误差w.r.t。此外,您还希望保留以下内容:
sum(y1, y2, y3) = sum(y1_hat, y2_hat, y3_hat)
因为您使用的是神经网络,所以您希望以这样一种方式施加此约束,以便仍然可以使用反向传播来训练网络。
执行此操作的一种方法是向损失函数添加一项,以惩罚sum(y1, y2, y3)
和sum(y1_hat, y2_hat, y3_hat)
之间的差异。
最小工作示例:
import numpy as np
import keras.backend as K
from keras.layers import Dense, Input
from keras.models import Model
# Some random training data and labels
features = np.random.rand(100, 20)
labels = np.random.rand(100, 3)
# Simple neural net with three outputs
input_layer = Input((20,))
hidden_layer = Dense(16)(input_layer)
output_layer = Dense(3)(hidden_layer)
# Model
model = Model(inputs=input_layer, outputs=output_layer)
# Write a custom loss function
def custom_loss(y_true, y_pred):
# Normal MSE loss
mse = K.mean(K.square(y_true-y_pred), axis=-1)
# Loss that penalizes differences between sum(predictions) and sum(labels)
sum_constraint = K.square(K.sum(y_pred, axis=-1) - K.sum(y_true, axis=-1))
return(mse+sum_constraint)
# Compile with custom loss
model.compile(loss=custom_loss, optimizer='sgd')
model.fit(features, labels, epochs=1, verbose=1)
请注意,这以"软"方式施加约束,而不是作为硬约束。你仍然会得到偏差,但网络应该以这样一种方式来学习权重,即这些权重将会很小。
这篇关于如何使用KERAS(TensorFlow)限制神经网络回归中的预测输出总和(TensorFlow)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文