tensorflow:使用tf.matmul将稀疏矩阵与密集矩阵相乘时出错

时间:2017-08-17 11:56:06

标签: python tensorflow sparse-matrix

在下面的代码中,我希望密集矩阵B与稀疏矩阵A相乘,但我得到了错误。

import tensorflow as tf
import numpy as np

A = tf.sparse_placeholder(tf.float32)
B = tf.placeholder(tf.float32, shape=(5,5))
C = tf.matmul(B,A,a_is_sparse=False,b_is_sparse=True)
sess = tf.InteractiveSession()
indices = np.array([[3, 2], [1, 2]], dtype=np.int64)
values = np.array([1.0, 2.0], dtype=np.float32)
shape = np.array([5,5], dtype=np.int64)
Sparse_A = tf.SparseTensorValue(indices, values, shape)
RandB = np.ones((5, 5))
print sess.run(C, feed_dict={A: Sparse_A, B: RandB})

错误消息如下:

TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> 
to Tensor. Contents: SparseTensor(indices=Tensor("Placeholder_4:0", shape=(?, ?), dtype=int64), values=Tensor("Placeholder_3:0", shape=(?,), dtype=float32), dense_shape=Tensor("Placeholder_2:0", shape=(?,), dtype=int64)). 
Consider casting elements to a supported type.

我的代码出了什么问题?

我在documentation之后执行此操作,它表示我们应该使用a_is_sparse来表示第一个矩阵是否稀疏,并且与b_is_sparse类似。为什么我的代码错了?

正如vijay所建议的,我应该使用C = tf.matmul(B,tf.sparse_tensor_to_dense(A),a_is_sparse=False,b_is_sparse=True)

我尝试了这个,但我遇到了另一个错误说:

Caused by op u'SparseToDense', defined at:
  File "a.py", line 19, in <module>
    C = tf.matmul(B,tf.sparse_tensor_to_dense(A),a_is_sparse=False,b_is_sparse=True)
  File "/home/fengchao.pfc/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/sparse_ops.py", line 845, in sparse_tensor_to_dense
    name=name)
  File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/sparse_ops.py", line 710, in sparse_to_dense
    name=name)
  File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gen_sparse_ops.py", line 1094, in _sparse_to_dense
    validate_indices=validate_indices, name=name)
  File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/mypath/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): indices[1] = [1,2] is out of order
[[Node: SparseToDense = SparseToDense[T=DT_FLOAT, Tindices=DT_INT64, validate_indices=true, _device="/job:localhost/replica:0/task:0/cpu:0"](_arg_Placeholder_4_0_2, _arg_Placeholder_2_0_0, _arg_Placeholder_3_0_1, SparseToDense/default_value)]]

谢谢大家的帮助!

1 个答案:

答案 0 :(得分:1)

tf.matmul中,标记a_is_sparseb_is_sparse并不表示操作数为SparseTensors,而是它们是算法提示,用于调用更有效的方法来计算乘法两个密集的张量。在您的代码中应该是:

C = tf.matmul(B,tf.sparse_tensor_to_dense(A),a_is_sparse=False,b_is_sparse=True)

要匹配SparseTensordense张量,您也可以使用tf.sparse_tensor_dense_matmul()代替。