[英]How can I access to content of Tensor in custom loss of Keras model
I am building an Autoencoder using Keras model.我正在使用 Keras model 构建自动编码器。 I want to built a custom loss in the form of
alpha* L2(x, x_pred) + beta * L1(day_x, day_x_pred)
.我想以
alpha* L2(x, x_pred) + beta * L1(day_x, day_x_pred)
的形式构建自定义损失。 The second term of L1 loss to penalize regarding to time (day_x is a day number). L1损失的第二项关于时间的惩罚(day_x是天数)。 The day is the first feature in my input data.
这一天是我输入数据中的第一个特征。 my input data is of the form
['day', 'beta', 'sigma', 'gamma', 'mu']
.我的输入数据格式为
['day', 'beta', 'sigma', 'gamma', 'mu']
。
the input x is of shape (batch_size, number of features) and I have 5 features.输入 x 的形状(batch_size,特征数),我有 5 个特征。 So my question is how to extract the first feature from
x and x_pred
to compute L1(t_x, t_x_pred)
.所以我的问题是如何从
x and x_pred
中提取第一个特征来计算L1(t_x, t_x_pred)
。 This is my current loss function:这是我目前的损失 function:
def loss_function(x, x_predicted):
#with tf.compat.v1.Session() as sess: print(x.eval())
return 0.7 * K.square(x- x_predicted) + 0.3 * K.abs(x[:,1]-x_predicted[:,1])
but this didn't work for me.但这对我不起作用。
this is the loss you need...这是你需要的损失...
you have to compute the means of your errors你必须计算你的错误的手段
def loss_function(x, x_predicted):
get_day_true = x[:,0] # get day column
get_day_pred = x_predicted[:,0] # get day column
day_loss = K.mean(K.abs(get_day_true - get_day_pred))
all_loss = K.mean(K.square(x - x_predicted))
return 0.7 * all_loss + 0.3 * day_loss
otherwise, you have to insert a dimensionality否则,您必须插入一个维度
def loss_function(x, x_predicted):
get_day_true = x[:,0] # get day column
get_day_pred = x_predicted[:,0] # get day column
day_loss = K.abs(get_day_true - get_day_pred)
all_loss = K.square(x - x_predicted)
return 0.7 * all_loss + 0.3 * tf.expand_dims(day_loss, axis=-1)
use the loss when you compile your model编译 model 时使用损失
model.compile('adam', loss=loss_function)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.