【问题标题】:Construct a new tensor from two existing ones in tensorflow从张量流中的两个现有张量构造一个新张量
【发布时间】:2018-07-05 17:47:44
【问题描述】:

我想从现有的张量 xm<n 和一个索引张量 idx 和形状 (b,m) 构造一个新的张量 idx 和形状 (b,m),这告诉我x(长度c)中的每一行将其放在y中的什么位置。

以 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,除了idx 给出的插入x 的值的位置之外,它的所有位置都为零。

我需要帮助将这段代码“翻译”成 tensorflow。

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

【问题讨论】:

  • tf.scatter 可能会有所帮助。
  • 我宁愿不想创建一个变量,而是一个常量张量。我应该澄清一下。

标签: python tensorflow


【解决方案1】:

你需要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]]]

【讨论】:

    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2017-12-01
    • 1970-01-01
    相关资源
    最近更新 更多