在稀疏变量上做梯度的tensorflow

在稀疏变量上做梯度的tensorflow,tensorflow,sparse-matrix,Tensorflow,Sparse Matrix,我试图在tensorflow中训练一个稀疏变量,据我所知,当前的tensorflow不允许稀疏变量 我发现有两个线程在讨论类似的问题:和。我不完全理解答案,如果有任何示例代码就好了 我尝试过的一种方法是: # initialize the sparse variable sp_weights # assuming w_s is the input sparse matrix contains indices information dim=20 identity = tf.constant(np

我试图在tensorflow中训练一个稀疏变量,据我所知,当前的tensorflow不允许稀疏变量

我发现有两个线程在讨论类似的问题:和。我不完全理解答案,如果有任何示例代码就好了

我尝试过的一种方法是:

# initialize the sparse variable sp_weights
# assuming w_s is the input sparse matrix contains indices information
dim=20
identity = tf.constant(np.identity(dim), dtype=tf.float32)
A=tf.sparse_tensor_dense_matmul(w_s, identity)  # convert w_s to dense
w_init = tf.random_normal([dim, dim], mean=0.0, stddev=0.1) 
w_tensor = tf.mul(A, w_init) # random initialize sparse tensor
vars['sp_weights'] = tf.Variable(w_tensor)

# doing some operations...
计算梯度时,根据使用
tf.indexedlices

grad = opt.compute_gradients(loss)
train_op = opt.apply_gradients(
    [tf.IndexedSlices(grad, indices)]) # indices is extracted from w_s

上面的代码当然不起作用,我在这里感到困惑。tf.indexedlices使输入成为indexedlices实例,如何使用它更新给定索引的渐变?此外,许多人提到使用tf.scatter\u add/sub/update。官方文档中没有任何关于如何使用以及在何处使用渐变更新的示例代码。我应该使用tf.indexedlices还是tf.scatter?如果有任何示例代码,这将非常有用。谢谢大家!

我不熟悉indexedlices或稀疏变量,但我收集到的信息是,您试图只对变量的某些片段应用渐变更新。如果这就是您正在做的,那么有一个简单的解决方法:使用

weights_copy = tf.Variable(weights_var.initialized_value()) # Copies the current value

,然后对整个变量应用渐变更新,然后使用tf.scatter()合并这两个变量,将原始/更新的部分合并到任何地方。

您能把收到的错误消息放在哪里?