Tensorflow:如何计算张量和稀疏张量之间的平方误差

Tensorflow: How to compute the square error between a tensor and a sparse tensor

我在tensorflow中有两个张量,一个是稀疏张量,叫A,一个是张量,叫B。我想计算 AB 之间的平方误差。

当我执行:

import tensorflow as tf
tf.reduce_sum(tf.square( B - A))

然后我收到一条错误消息:

TypeError: Expected float32 passed to parameter 'y' of op 'Sub', got <tensorflow.python.framework.sparse_tensor.SparseTensor object at 0x7f42a10bdf90> of type 'SparseTensor' instead.

然后我测试了:

tf.reduce_sum(tf.sparse_add(layer_Bi_12, - Bi))

错误说:

TypeError: bad operand type for unary -: 'SparseTensor'

然后我测试了:

tf.reduce_sum(tf.square(tf.sparse_add(layer_Bi_12, - Bi)))

错误说:

TypeError: bad operand type for unary -: 'SparseTensor'

我怎样才能做到这一点?

您不能添加稀疏张量和密集张量。您需要先将稀疏张量转换为密集张量,例如

dense_A = tf.sparse_tensor_to_dense(A)
tf.reduce_sum(tf.square(B - dense_A))