将密集向量乘以张量流中的稀疏矩阵

时间:2018-05-14 21:16:34

标签: python 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:'Tensor'对象不支持项目分配。”我试过了

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转换为vec = tf.get_variable('vec', initializer = tf.zeros(dense_vec.shape, dense_vec.dtype))的变量会产生相同的错误。有没有太过记忆密集的方式吗?

1 个答案:

答案 0 :(得分:0)

您应该使用为此目的而发明的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.]
   [60]
   [0。]]

作为参考,我的第一个答案是指tf.sparse_matmul(),这有点令人困惑multiplies two dense matrices but with a specially designed algorithm for matrices with many zero values。它会阻塞sparse_tensor参数。