首页 > 解决方案 > 创建 tf.constant 给定的索引和值

问题描述

我想改进我当前的代码以提高我的 GPU 上的执行性能,所以我正在替换它不支持的操作以避免将它们委托给 CPU。

其中一项操作是 tf.sparse_to_dense。那么,有没有办法从它的索引和值创建一个张量(常量),就好像它是一个稀疏张量一样?

我使它与解决方法一起工作,例如使用 numpy 获取数组,然后使用它创建它,tensor = tf.constant(numpyarray)但我正在寻找一种“唯一的 Tensorflow”方法。

标签: pythontensorflow

解决方案


tf.constant当前不支持坐标格式(索引和值)的实例化,因此 numpy/scipy 解决方法实际上并不是一个糟糕的解决方法:

import scipy.sparse as sps

A = sps.coo_matrix((values, (indices[0,:], indices[1,:])), shape=your_shape)
tensor_A = tf.constant(A.to_dense())

如果可以选择不可训练tf.Variable(请参阅此处了解与 的区别tf.constant),您可以使用tf.sparse_to_dense

tensor_A = tf.Variable( \
              tf.sparse_to_dense(indices, your_shape, values), \
              trainable=False \
           )

推荐阅读