Skip to main content
 首页 » 编程设计

python之在 TensorFlow 中传递和使用稀疏矩阵

2024年08月16日28dflying

假设我有一个矩阵:

X = [ 
    [0, 0, 0, 0, 0], 
    [0, 0, 1, 0, 0], 
    [0, 0, 0, 0, 0], 
    [2, 0, 0, 3, 0], 
    [0, 0, 0, 0, 0], 
    [0, 0, 0, 0, 0], 
    [0, 4, 0, 0, 0] 
] 

但它以稀疏格式存储:

# [row, column, value] 
X_sparse = [ 
    [1, 2, 1], 
    [3, 0, 2], 
    [3, 3, 3] 
    [6, 1, 4], 
] 

我也有一个向量

b = [1,2,3,4,5] 

我想将 X_sparse 作为数据传递给 TensorFlow,并将其与 b 相乘(即 np.dot(X, b)) .在 TensorFlow 中执行此操作的正确方法是什么?此外,这是一个玩具示例,而在现实生活中 X 有很多行和列,所以我不想将其转换为非稀疏格式。

请您参考如下方法:

如果不使用密集张量表示 (tf.sparse_tensor_to_dense()),我看不出有一种简单的方法可以做到这一点。然而,Tensorflow 是为大型矩阵的操作而构建的,因此在许多情况下这应该不是问题......

一个简单的例子:

import tensorflow as tf 
import numpy as np 
 
X_sparse_np = np.array([ 
    [1, 2, 1], 
    [3, 0, 2], 
    [3, 3, 3], 
    [6, 1, 4], 
])   
b_np = np.array([1,2,3,4,5]) 
b = tf.constant(b_np) 
 
# Converting your input data into a SparseTensor: 
indices = X_sparse_np[:, :2].reshape((-1, 2)) 
values = X_sparse_np[:, 2] 
dense_shape = [7, 5] 
X_sparse = tf.SparseTensorValue(indices, values, dense_shape) 
 
# Performing your operation on its dense representation: 
res = tf.sparse_tensor_to_dense(X_sparse) * b 
 
# opt. Re-obtaining the sparse representation of your result: 
sparse_res = tf.SparseTensor(indices, tf.gather_nd(res, indices), dense_shape) 
 
with tf.Session() as sess: 
    print(sess.run(res)) 
    # [[ 0  0  0  0  0] 
    #  [ 0  0  3  0  0] 
    #  [ 0  0  0  0  0] 
    #  [ 2  0  0 12  0] 
    #  [ 0  0  0  0  0] 
    #  [ 0  0  0  0  0] 
    #  [ 0  8  0  0  0]] 
    print(sess.run(sparse_res)) 
    # SparseTensorValue( 
    #       indices=array([[1, 2], 
    #                      [3, 0], 
    #                      [3, 3], 
    #                      [6, 1]]),  
    #       values=array([ 3,  2, 12,  8]),  
    #       dense_shape=array([7, 5]))