【发布时间】:2018-10-15 10:57:29
【问题描述】:
我有一个这样的张量
...
0
0
2
0
1
0
3
1
0
0
0
0
2
3
...
我必须找到一种方法来创建一个形状相同但只有 0 和 1 的张量。这个张量必须与特定数字处于相同的位置。这里是一个例子
# for number 2
...
0
0
1
0
0
0
0
0
0
0
0
0
1
0
...
有没有内置函数可以做到这一点?我在网上和文档中都找不到任何东西。
然后我必须将这个张量乘以这样的数字列表
l = [..., 1.3, 4.3, ...]
获得这个
...
0
0
1.3
0
0
0
0
0
0
0
0
0
4.3
0
...
有没有办法得到这个结果?
编辑
在我的案例中应用此方法时遇到问题。我解释一下。我的索引张量是这样的
points = tf.constant([[[0], [1], [0], [2], [1], [0], [2], [2], [0], [1]],
[[1], [2], [0], [0], [1], [0], [1], [2], [0], [2]],
[[0], [2], [1], [0], [2], [0], [1], [2], [0], [1]]], dtype=tf.float32)
# shape=(3, 10, 1)
我必须只取第一行的索引,所以我以这种方式取它们
idx = tf.cast(tf.where(tf.equal(tf.slice(points, [0, 0, 0], [1, 10, 1]), tf.constant([2], dtype=tf.float32))), dtype=tf.int32)
# shape=(3, 3)
idx = tf.expand_dims(idx, 0)
# shape=(1, 3, 3)
要输入的值在一个名为 vectors 的列表中,我将它们转换为具有相同的形状
to_feed = np.expand_dims(np.array(vectors), 0)
# shape=(1, 3, 3)
然后我以这种方式应用该方法
res = tf.scatter_nd(idx, to_feed, tf.shape(tf.slice(points, [0, 0, 0], [1, 10, 3])))
但我得到了这个错误
ValueError: The inner 0 dimensions of output.shape=[?,?,?] must match the inner 1 dimensions of updates.shape=[1,3,3]: Shapes must be equal rank, but are 0 and 1 for 'ScatterNd' (op: 'ScatterNd') with input shapes: [1,3,3], [1,3,3], [3].
我最后需要的是这样的张量
to_feed = [[[10, 10, 10], [11, 11, 11], [12, 12, 12]]] # shape=(1, 3, 3)
res = [[[0, 0, 0], [10, 10, 10], [0, 0, 0], [11, 11, 11], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [12, 12, 12], [0, 0, 0]]] # shape=(1, 10, 3)
([0, 0, 0] 随机放置只是为了有个想法)
【问题讨论】:
标签: python tensorflow