python - 创建 tf.constant 给定的索引和值
问题描述
我想改进我当前的代码以提高我的 GPU 上的执行性能,所以我正在替换它不支持的操作以避免将它们委托给 CPU。
其中一项操作是 tf.sparse_to_dense。那么,有没有办法从它的索引和值创建一个张量(常量),就好像它是一个稀疏张量一样?
我使它与解决方法一起工作,例如使用 numpy 获取数组,然后使用它创建它,tensor = tf.constant(numpyarray)
但我正在寻找一种“唯一的 Tensorflow”方法。
解决方案
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 \
)
推荐阅读
- python - 如何使用 SquareSpace 登录 Python 程序
- javascript - Firestore (web) 添加简单集合
- wso2 - 如何为 wso2 身份服务器权利创建策略
- apache - 使用 Apache 列出目录内容
- c - 发送带有 XML 内容的 POST http 请求
- javascript - 电子无法收到通知
- wordpress - 如何在wordpress帖子中显示html结果视图
- angular - ngrx 实体应该存储在功能级别还是应用级别?
- python - 在 python 的单个窗口上显示刷新 RGB 矩阵的好方法是什么?
- python - Draw over image in a QLabel with PyQt5