在 TensorFlow 中使用 coo_matrix

Use coo_matrix in TensorFlow

我在 TensorFlow 中进行矩阵分解,我想使用 Spicy.sparse 中的 coo_matrix,因为它使用的内存更少,并且可以轻松地将我的所有数据放入我的矩阵中进行训练数据.

是否可以使用coo_matrix在tensorflow中初始化一个变量?

或者我是否必须创建一个会话并将我使用 sess.run() 和 feed_dict.

获得的数据输入 tensorflow

我希望你理解我的问题和我遇到的问题,否则请发表评论,我会尽力解决。

TensorFlow 最接近 scipy.sparse.coo_matrix is tf.SparseTensor, which is the sparse equivalent of tf.Tensor 的东西。在您的程序中输入 coo_matrix 可能是最简单的。

A tf.SparseTensor 是 COO 矩阵的轻微推广,其中张量表示为三个密集的 tf.Tensor 对象:

  • indicestf.int64 值的 N x D 矩阵,其中每一行代表非零值的坐标。 N 是非零的个数,D 是等效稠密张量的秩(在矩阵的情况下为 2)。
  • values:一个长度为 N 的值向量,其中元素 i 是其坐标在 [= 的第 i 行给出的元素的值18=].
  • dense_shapetf.int64的长度-D向量,表示等效稠密张量的形状

例如,您可以使用以下代码,它使用 tf.sparse_placeholder() to define a tf.SparseTensor that you can feed, and a tf.SparseTensorValue 来表示被馈送的实际值:

sparse_input = tf.sparse_placeholder(dtype=tf.float32, shape=[100, 100])
# ...
train_op = ...

coo_matrix = scipy.sparse.coo_matrix(...)

# Wrap `coo_matrix` in the `tf.SparseTensorValue` form that TensorFlow expects.
# SciPy stores the row and column coordinates as separate vectors, so we must 
# stack and transpose them to make an indices matrix of the appropriate shape.
tf_coo_matrix = tf.SparseTensorValue(
    indices=np.array([coo_matrix.rows, coo_matrix.cols]).T,
    values=coo_matrix.data,
    dense_shape=coo_matrix.shape)

coo_matrix 转换为 tf.SparseTensorValue 后,您可以直接用 tf.SparseTensorValue 喂养 sparse_input

sess.run(train_op, feed_dict={sparse_input: tf_coo_matrix})