当占位符提供形状时,Tensorflow 稀疏到密集操作失败

Tensorflow sparse to dense operations failing when placeholder provided shape

我在 Tensorflow 中将稀疏张量(稀疏占位符)乘以密集张量时遇到问题。我也遇到了将稀疏张量直接转换为密集张量的问题。我已经搜索过,但到目前为止还没有找到这个问题的例子。

TL;DR

如果稀疏占位符将其 shape 参数设置为 None,则计算有效,但如果我提供类似 (3,3) 的形状,则计算失败。

这是有效的代码:

import tensorflow as tf
import numpy as np

matrix_place = tf.placeholder(tf.float32, name="foo", shape=(3,2))
sparse_place = tf.sparse_placeholder(tf.float32, name="bar", shape=None) # Note shape is None

mul_result = tf.sparse_tensor_dense_matmul(sparse_place, matrix_place)

matrix_input = np.ones((3,2))
sparse_input = tf.SparseTensorValue([[0,0], [1,1], [2,2]], [1, 2, 3], (3, 3))

with tf.Session() as sess:
    result = sess.run(mul_result, feed_dict={sparse_place: sparse_input, matrix_place: matrix_input})
    print(result)

输出(如预期):

[[1. 1.]
 [2. 2.]
 [3. 3.]]

现在,如果我更改此行:

sparse_place = tf.sparse_placeholder(tf.float32, name="bar", shape=None)

对此:

sparse_place = tf.sparse_placeholder(tf.float32, name="bar", shape=(3,3))

(与我输入的 tf.SparseTenorValue(...) 的形状匹配),我收到以下错误:

Traceback (most recent call last):
  File "testing_sparse3.py", line 13, in <module>
    result = sess.run(mul_result, feed_dict={sparse_place: sparse_input, matrix_place: matrix_input})
  File "C:\Anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\client\session.py", line 905, in run
    run_metadata_ptr)
  File "C:\Anaconda3\envs\tensorflow-cpu\lib\site-packages\tensorflow\python\client\session.py", line 1115, in _run
    raise ValueError('Tensor %s may not be fed.' % subfeed_t)
ValueError: Tensor Tensor("bar/shape:0", shape=(2,), dtype=int64) may not be fed.

我尝试过的事情

如果我从矩阵乘法(涉及 2 个张量)切换:

sparse_place = tf.sparse_placeholder(tf.float32, name="bar", shape=(3,3))

mul_result = tf.sparse_tensor_dense_matmul(sparse_place, matrix_place)

对稀疏张量的元素进行简单求和(只涉及稀疏张量):

sparse_place = tf.sparse_placeholder(tf.float32, name="bar", shape=(3,3))

mul_result = tf.sparse_tensor_reduce_sum(sparse_place)

它不会产生错误并给出正确的结果。但是如果我尝试将稀疏张量转换为密集张量(一个也只涉及稀疏张量的操作):

sparse_place = tf.sparse_placeholder(tf.float32, name="bar", shape=(3,3))

mul_result = tf.sparse_tensor_to_dense(sparse_place)

错误 returns。

我已经看到 related issue but it appears to have been merged 了。我尝试将传递给 tf.SparseTensorValue 的 indices/values/shape 分别转换为 dtypes int64/float32/int64 的 numpy 数组,但问题仍然存在。我还尝试将传递给稀疏占位符的 (3,3) 形状转换为 numpy int64 数组,但也失败了。

有什么想法吗?我错过了一些非常明显的东西吗?我在 Windows.

上使用 Python 3.5 和 Tensorflow v1.6.0 (CPU)

谢谢!

当您说 shape = (3, 3) 时,TensorFlow 将该形状视为形状推断的常量,并且不允许提供该形状张量。我们可能应该检测到您正在提供它的实际值并让它通过。提交 github 问题。