首页 > 解决方案 > 从张量流中的两个现有张量构造一个新张量

问题描述

我想从现有的张量构造一个新的张量,形状y为with和一个索引张量,其形状告诉我(length ) 中的每一行将其放入何处。(b,n,c)x(b,m,c)m<nidx(b,m)xcy

使用 numpy 的示例:

import numpy as np
b=2
n=100
m=4
c=3
idx=np.array([[0,31,5,66],[1,73,34,80]]) # shape b x m
x=np.random.random((b,m,c))
y=np.zeros((b,n,c))
for i,cur_idx in enumerate(idx):
    y[i,cur_idx]=x[i]

这导致一个数组,除了插入值y的位置给定的位置之外,所有位置都为零。idxx

我需要帮助将这个代码片段“翻译”成张量流。

编辑:我不想创建一个变量,而是一个常量张量,所以 tf.scatter_update 不能使用。

标签: pythontensorflow

解决方案


你需要tf.scatter_nd

import tensorflow as tf
import numpy as np

b = 2
n = 100
m = 4
c = 3

# Synthetic data
x = tf.reshape(tf.range(b * m * c), (b, m, c))
# Arbitrary indices: [0, 25, 50, 75], [1, 26, 51, 76]
idx = tf.convert_to_tensor(
    np.stack([np.arange(0, n, n // m) + i for i in range(b)], axis=0))

# Add index for the first dimension
idx = tf.concat([
    tf.tile(tf.range(b, dtype=idx.dtype)[:, tf.newaxis, tf.newaxis], (1, m, 1)),
    idx[:, :, tf.newaxis]], axis=2)

# Scatter operation
y = tf.scatter_nd(idx, x, (b, n, c))
with tf.Session() as sess:
    y_val = sess.run(y)
    print(y_val[:, 20:30, :])

输出:

[[[ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [ 3  4  5]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]]

 [[ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]
  [15 16 17]
  [ 0  0  0]
  [ 0  0  0]
  [ 0  0  0]]]

推荐阅读