TensorFlow:numpy.repeat() 替代方案 [英] TensorFlow: numpy.repeat() alternative
问题描述
我想以成对的方式比较来自我的神经网络的预测值 yp
,所以我使用了(回到我旧的 numpy 实现中):
I want to compare the predicted values yp
from my neural network in a pairwise fashion, and so I was using (back in my old numpy implementation):
idx = np.repeat(np.arange(len(yp)), len(yp))
jdx = np.tile(np.arange(len(yp)), len(yp))
s = yp[[idx]] - yp[[jdx]]
这基本上创建了一个索引网格,然后我使用它.idx=[0,0,0,1,1,1,...]
而 jdx=[0,1,2,0,1,2...]
代码>.不知道有没有更简单的方法...
This basically create a indexing mesh which I then use. idx=[0,0,0,1,1,1,...]
while jdx=[0,1,2,0,1,2...]
. I do not know if there is a simpler manner of doing it...
无论如何,TensorFlow 有一个 tf.tile()
,但它似乎缺少一个 tf.repeat()
.
Anyhow, TensorFlow has a tf.tile()
, but it seems to be lacking a tf.repeat()
.
idx = np.repeat(np.arange(n), n)
v2 = v[idx]
我得到了错误:
TypeError: Bad slice index [ 0 0 0 ..., 215 215 215] of type <type 'numpy.ndarray'>
使用 TensorFlow 常量进行索引也不起作用:
It also does not work to use a TensorFlow constant for the indexing:
idx = tf.constant(np.repeat(np.arange(n), n))
v2 = v[idx]
-
TypeError: Bad slice index Tensor("Const:0", shape=TensorShape([Dimension(46656)]), dtype=int64) of type <class 'tensorflow.python.framework.ops.Tensor'>
这个想法是转换我的RankNet 实现到 TensorFlow.
The idea is to convert my RankNet implementation to TensorFlow.
推荐答案
使用tf.tile()
和 tf.reshape()
:
idx = tf.range(len(yp))
idx = tf.reshape(idx, [-1, 1]) # Convert to a len(yp) x 1 matrix.
idx = tf.tile(idx, [1, len(yp)]) # Create multiple columns.
idx = tf.reshape(idx, [-1]) # Convert back to a vector.
您可以使用 tf.tile()
简单地计算 jdx
:
You can simply compute jdx
using tf.tile()
:
jdx = tf.range(len(yp))
jdx = tf.tile(jdx, [len(yp)])
对于索引,您可以尝试使用 tf.gather()
从 yp
张量中提取非连续切片:
For the indexing, you could try using tf.gather()
to extract non-contiguous slices from the yp
tensor:
s = tf.gather(yp, idx) - tf.gather(yp, jdx)
这篇关于TensorFlow:numpy.repeat() 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!