python - 从张量流中的两个现有张量构造一个新张量
问题描述
我想从现有的张量构造一个新的张量,形状y
为with和一个索引张量,其形状告诉我(length ) 中的每一行将其放入何处。(b,n,c)
x
(b,m,c)
m<n
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
我需要帮助将这个代码片段“翻译”成张量流。
编辑:我不想创建一个变量,而是一个常量张量,所以 tf.scatter_update 不能使用。
解决方案
你需要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]]]
推荐阅读
- spring-boot - 使用 Spring Zuul 和 Spring Initializer 进行正确的依赖管理
- json.net - Newtonsoft 不隐藏空值
- azure-cosmosdb-sqlapi - Sql string for this result?
- c - 使用位运算符返回 C 中最负的二进制补数
- telerik - RadTelerik Datepicker showing above the control
- java - Scroll bars / scrollpane disappearing upon image upload and zoom in JavaFX
- java - Find if a node exists in XStream api
- c - stand alone explanation of sigsetjmp
- python - Python Dynamic Inheritance and Attributes
- chromium - 是否可以使用 Puppeteer 加载 chrome://gpu?