簡體   English   中英

張量流中的稀疏矩陣乘以密集向量

[英]Multiplying a dense vector by a sparse matrix in 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 = tf.get_variable('vec', initializer = tf.zeros(dense_vec.shape, dense_vec.dtype))將vec轉換為變量會產生相同的錯誤。 是否有一種不太占用內存的方式來執行此操作?

您應該使用為此目的而發明的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() ,該函數有些令人困惑地將兩個稠密矩陣相乘,但是它是針對具有許多零值的矩陣專門設計的算法 它將阻塞sparse_tensor參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM