TensorFlow:numpy.repeat()替代方案

Ric*_*ruz 40 tensorflow

我想以yp成对的方式比较我的神经网络中的预测值,所以我正在使用(回到我原来的numpy实现中):

idx = np.repeat(np.arange(len(yp)), len(yp))
jdx = np.tile(np.arange(len(yp)), len(yp))
s = yp[[idx]] - yp[[jdx]]
Run Code Online (Sandbox Code Playgroud)

这基本上创建了一个索引网格,然后我使用它.idx=[0,0,0,1,1,1,...]jdx=[0,1,2,0,1,2...].我不知道是否有更简单的做法...

无论如何,TensorFlow有一个tf.tile(),但似乎缺乏一个tf.repeat().

idx = np.repeat(np.arange(n), n)
v2 = v[idx]
Run Code Online (Sandbox Code Playgroud)

我收到错误:

TypeError: Bad slice index [  0   0   0 ..., 215 215 215] of type <type 'numpy.ndarray'>
Run Code Online (Sandbox Code Playgroud)

使用TensorFlow常量进行索引也无效:

idx = tf.constant(np.repeat(np.arange(n), n))
v2 = v[idx]
Run Code Online (Sandbox Code Playgroud)

-

TypeError: Bad slice index Tensor("Const:0", shape=TensorShape([Dimension(46656)]), dtype=int64) of type <class 'tensorflow.python.framework.ops.Tensor'>
Run Code Online (Sandbox Code Playgroud)

我的想法是将我的RankNet实现转换为TensorFlow.

mrr*_*rry 36

您可以实现np.repeat()使用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.
Run Code Online (Sandbox Code Playgroud)

您可以jdx使用tf.tile()以下方法进

jdx = tf.range(len(yp))
jdx = tf.tile(jdx, [len(yp)])
Run Code Online (Sandbox Code Playgroud)

对于索引,您可以尝试使用tf.gather()yp张量中提取非连续切片:

s = tf.gather(yp, idx) - tf.gather(yp, jdx)
Run Code Online (Sandbox Code Playgroud)


小智 6

根据 tf api文档tf.keras.backend.repeat_elements()np.repeat(). 例如,

x = tf.constant([1, 3, 3, 1], dtype=tf.float32)
rep_x = tf.keras.backend.repeat_elements(x, 5, axis=0)
# result: [1. 1. 1. 1. 1. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 1. 1. 1. 1. 1.]
Run Code Online (Sandbox Code Playgroud)