tensorflow:使用 tf.matmul

问题描述 投票:0回答:1

在下面的代码中,我想要密集矩阵

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.

我的代码有什么问题?

我是按照文档来做这件事的,它说我们应该使用

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/mypath/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)]]

谢谢大家对我的帮助!

python tensorflow sparse-matrix
1个回答
1
投票

tf.matmul
中,标志
a_is_sparse
b_is_sparse
并不指示操作数为
SparseTensors
,相反,它们是算法提示,用于调用更有效的方法来计算两个稠密张量的乘法。在你的代码中应该是:

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

要对

SparseTensor
dense
张量进行矩阵相乘,您也可以使用
tf.sparse_tensor_dense_matmul()
代替。

© www.soinside.com 2019 - 2024. All rights reserved.