在tensorflow中,是否有一种简单的方法来乘稀疏矩阵和稠密张量?我试过了
def sparse_mult(sparse_mat,dense_vec):
vec = tf.zeros(dense_vec.shape, dense_vec.dtype)
indices = sparse_mat.indices
values = sparse_mat.values
with tf.Session() as sess:
num_vals = sess.run(tf.size(values))
for i in range(num_vals):
vec[indices[i,0]] += values[i] * dense_vec[indices[i,1]]
return vec但我得到"TypeError:‘张量’对象不支持项分配。“我试过了
def sparse_mult(sparse_mat,dense_vec):
vec = tf.zeros(dense_vec.shape, dense_vec.dtype)
indices = sparse_mat.indices
values = sparse_mat.values
with tf.Session() as sess:
num_vals = sess.run(tf.size(values))
for i in range(num_vals):
vec = vec[indices[i,0]].assign(vec[indices[i,0]] + values[i] * dense_vec[indices[i,1]])
return vec并得到"ValueError:切片赋值仅支持变量“。使用vec = tf.get_variable('vec', initializer = tf.zeros(dense_vec.shape, dense_vec.dtype))将vec转换为变量会产生同样的错误。是否有一种不太需要记忆的方法来做到这一点?
发布于 2018-05-14 21:19:43
您应该使用tf.sparse_tensor_dense_matmul(),它正是为了这个目的而发明的。您不需要创建自己的函数。该代码(经过测试):
import tensorflow as tf
a = tf.SparseTensor( indices = [ [ 0, 0 ], [ 3, 4 ] ],
values = tf.constant( [ 1.0, 10 ] ),
dense_shape = [ 5, 5 ] )
vec = tf.constant( [ [ 2.0 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ] ] )
c = tf.sparse_tensor_dense_matmul( a, vec )
with tf.Session() as sess:
res = sess.run( c )
print( res )将产出:
[ 2 ]。 0。 0.]
作为参考,我的第一个回答是指tf.sparse_matmul(),它有点令人困惑的 matrices but with a specially designed algorithm for matrices with many zero values。它将被sparse_tensor参数所扼杀。
https://stackoverflow.com/questions/50339131
复制相似问题