我是机器学习编码的新手,也是使用Tensorflow编码的新手。
我正面临在Tensorflow中使用索引的问题。在简单的python和numpy中,这很容易,但在Tensorflow库中,我不知道如何制作它。
我想在一个例子的每个类中应用softmax函数,而不是在每一行的两个随机类中应用,并在特定索引(之前采取的随机类)的所有类的大矩阵(最初为零)中返回这些值。numpy中的算法更简单,因为可以使用简单的索引,但在tensorflow中我是这样认为的:
给定一个矩阵X:(NxD)和一个矩阵W:(KxD),以及一个包含0到K-1之间两个随机数的数组rem_cl
S is an empty matrix
for every line in X
take Wsamp = W[rem_cl]
mult = X[line] * Wsamp.T
apply softmax on mult
put those numbers in an array "s" of zeros (1xK) in the indexes of rem_cl
append s in S
矩阵S的最终形状为(NxK)
到目前为止我所做的tensorflow代码是:
Xnp = np.array([[1,0,0,0,0],[1,0,1,0,0],[1,0,1,1,2],[4,2,1,0,0],[3,0,1,1,2],[1,2,1,0,0]], np.float32)
K = 4
W = tf.Variable(tf.random_uniform((K,5)))
rand = tf.random_uniform((),0,K-1, tf.int32)
s = tf.Variable(tf.zeros((K)))
S = tf.Variable(tf.zeros((K)))
for line in range(4):
rem_cl = tf.constant([sess.run(rand),sess.run(rand)])
Wsampled = (tf.gather(W,rem_cl))
mult = (tf.matmul(Xnp[line:line+1],Wsampled,transpose_b=True))
mult = (tf.nn.softmax(mult))
rem_cl = tf.reshape(rem_cl,(2,1))
rem_cl = tf.transpose(rem_cl)
k = sess.run(tf.scatter_update(s,rem_cl,mult))
sess.run(s.assign(tf.zeros(K)))
S = tf.pack([S,k], axis=0)
最后一行给出如下错误
形状必须是等号的,但是是2和1从合并形状0到其他形状。
我的问题是:1)首先,在Tensorflow中是否有更简单的方法来更新矩阵的数组指定值?2)如果不是,为什么会出现错误,或者更好地说,如何在现有矩阵上添加新行?
如果您使用Python循环,我会使用Python张量列表。如果你最终使用TensorFlow while_loop(有助于保持图形较小),我会考虑使用TensorArray(或隐式使用它的高级循环结构之一,如scan())。
至于为了完成而出现的错误,我认为您需要concat,并为vector使用expand_dims。Pack添加一个维度,并要求其参数具有相同的形状。