在tensorflow高级索引中更新矩阵变量的值

2024-09-26 18:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个函数,对于给定数据X的每一行,只对一些抽样类应用softmax函数,比如说2个,总共K个类。在简单的python中,代码如下所示:

def softy(X,W, num_samples):
    N = X.shape[0]
    K = W.shape[0]
    S = np.zeros((N,K)) 
    ar_to_sof = np.zeros(num_samples)
    sampled_ind = np.zeros(num_samples, dtype = int)
    for line in range(N):        
        for samp in range(num_samples):
            sampled_ind[samp] = randint(0,K-1)
            ar_to_sof[samp] = np.dot(X[line],np.transpose(W[sampled_ind[samp]])) 
        ar_to_sof = softmax(ar_to_sof)
        S[line][sampled_ind] = ar_to_sof 

    return S

最后,S将在数组“samped_ind”为每一行定义的索引中包含零和非零值。 我想用Tensorflow实现这个。问题是它包含“高级”索引,我无法找到使用这个库创建它的方法。在

我试着用这个代码:

^{pr2}$

在这里之前,一切都正常,但是我无法在矩阵S中找到我想要的更新,在python代码“S[line][sampled_ind]=ar_to_-of”。在

我该怎么做?在


Tags: to函数代码nplinezerosnumar
1条回答
网友
1楼 · 发布于 2024-09-26 18:15:37

this problem的解决方案的注释中找到了我问题的答案。建议将my matrix S重塑为一维向量。这样,代码就可以工作了,它看起来像:

S = tf.Variable(tf.zeros(shape=(N*K)))
W = tf.Variable(tf.random_uniform((K,D)))
tfx = tf.placeholder(tf.float32,shape=(None,D))
sampled_ind = tf.random_uniform(dtype=tf.int32, minval=0, maxval=K-1, shape=[num_samps])
ar_to_sof = tf.matmul(tfx,tf.gather(W,sampled_ind),transpose_b=True)
updates = tf.reshape(tf.nn.softmax(ar_to_sof),shape=(num_samps,))
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for line in range(N):
    inds_new = sampled_ind + line*K
    sess.run(tf.scatter_update(S,inds_new,updates), feed_dict={tfx: X[line:line+1]})

S = tf.reshape(S,shape=(N,K))

这将返回我期望的结果。现在的问题是这个实现太慢了。比numpy版本慢得多。也许是for循环。有什么建议吗?在

相关问题 更多 >

    热门问题