Tensorflow,使用元素操作定义损失函数的正确方法

Tensorflow, proper way to define a loss function with element-wise operations

我有一批 n 个训练样本。每个训练示例都会为我生成一个向量 a(长度为 k)和一个向量 c(长度也为 k)。

在tensorflow中我的输出是p.

我想定义如下损失函数:

\sum_(i = 0)^(i=n) c_i ( (a_i - p)^2 )

我已经阅读了各种可用的 tf 操作,但似乎无法为此找到合适的实现。我尝试使用 tf.tile 将 p 复制为 k 长度张量并执行 tf.subtract,但这似乎过分了。

如有任何帮助,我们将不胜感激。

p的形状是什么? TensorFlow 原生支持不同形状的张量相减:

import tensorflow as tf

a = tf.Variable([[1, 2, 3], [2, 3, 4], [3, 4, 5]])

x_1 = a - tf.Variable([1, 1, 1])
x_2 = a - tf.Variable([1])
x_3 = a - tf.Variable(1)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(x_1))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]
    print(sess.run(x_2))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]
    print(sess.run(x_3))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]

你可以定义你的损失函数如下:

a = tf.Variable([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
c = tf.Variable([[4, 5, 6], [5, 6, 7], [6, 7, 8]])

p = tf.Variable(1)

loss_1 = tf.reduce_mean(tf.reduce_sum(tf.multiply(c, tf.pow(tf.subtract(a, p), 2)), axis=1))  # 112
loss_2 = tf.reduce_mean(tf.reduce_sum(c * (a-p)**2, axis=1))  # 112