如何在Tensorflow中动态创建列表

时间:2018-10-23 18:22:48

标签: python tensorflow

如何无需创建变量即可从任务列表(self.prediction)动态创建损失列表:

当前

loss0 = tf.losses.softmax_cross_entropy( logits = self.prediction[0], onehot_labels = self.Y[0] ) # task 0
loss1 = tf.losses.softmax_cross_entropy( logits = self.prediction[1], onehot_labels = self.Y[1] ) # task 1
loss2 = tf.losses.softmax_cross_entropy( logits = self.prediction[2], onehot_labels = self.Y[2] ) # task 2

self.losses = tf.reduce_sum( [ loss0, loss1, loss2 ] )

目标:

list_loss = ?
self.losses = tf.reduce_sum( list_loss )

1 个答案:

答案 0 :(得分:0)

如果我明白您的意思,您就是要

def calculate_loss(prediction, label, idx):
    return tf.losses.softmax_cross_entropy(logits = prediction[idx], 
                                           onehot_labels = label[idx])

losses = []
for i in range(3):
    losses.append(calculate_loss(self.prediction, self.Y, i)
self.losses = tf.reduce_sum(losses)