简体   繁体   English

如何仅通过张量操作在张量流图中获取掩码

[英]How to get a mask in the tensorflow graph by only tensor operations

I have two tensors containing two groups of vectors d1 and d2. 我有两个张量,其中包含两组向量d1和d2。 Both of d1 and d2 contain 5 two-dimensional vectors [d1 and d2 are changing in training loop] d1和d2都包含5个二维向量[d1和d2在训练循环中正在变化]

import tensorflow as tf
import numpy as np
# random initialize
d1_np = np.random.rand(5,2) 
d2_np = np.random.rand(5,2) 

d1 = tf.Variable(initial_value = d1_np, dtype=tf.float32)
d2 = tf.Variable(initial_value = d2_np, dtype=tf.float32)

then I calculate the distance of them and getting a their cross distance matrix by cross_distance 然后我计算它们的距离并通过cross_distance得到它们的交叉距离矩阵

dist_1_2 = cross_distance(d1, d2)  

so it produces a matrix of size 5x5 (the diagonal value is set to a very large value). 因此会产生大小为5x5的矩阵(对角线值设置为非常大的值)。

Then for each vector in d1, I got the index of its closest vector in d2 by 然后对于d1中的每个向量,我得到d2中其最接近向量的索引为

ind_min = tf.argmin(dist_1_2,axis=1)

ind_min gets values like [2 0 0 1 0] during runing 在运行过程中,ind_min获得类似[2 0 0 1 0]的值

I then use tf.unique to get the unique index in ind_min 然后,我使用tf.unique在ind_min中获取唯一索引

yv,idx = tf.unique(ind_min)

now yv becomes [2 0 1]. 现在yv变成[2 0 1]。 I want to set a mask and see whether the corresponding vectors in d2 is a closet vector to some vector in d1. 我想设置一个遮罩,看看d2中的对应向量是否是d1中某些向量的壁橱向量。

mask = tf.cast(tf.ones(5),tf.bool)

Now I hope to set the value of mask to zero for those index in yv. 现在,我希望将yv中的那些索引的mask值设置为零。 I tried: 我试过了:

mask[yv] = 0

('Tensor' object does not support item assignment) and (“张量”对象不支持项目分配)和

for ind in tf.unstack(yv):
    mask[yv] = 0

(Cannot infer num from shape (?,)) and it does not work. (无法从形状(?,)推断num),它不起作用。

The point is d1 and d2 is changing during some training process, so ind_min is not fixed but changing with the training loop. 关键点是d1,而d2在某些训练过程中正在变化,因此ind_min不是固定的,而是随训练循环而变化。

Is there a way to get this mask dynamically? 有没有办法动态获得这个面具?

Creating one-hot encoding of indices and adding along the first dimension should give you the mask. 创建索引的一次性编码并沿第一个维度进行添加将为您提供掩码。 ie

mask = tf.reduce_sum(tf.one_hot(idx, 5), axis=0)

The mask size (hard-coded 5) can be replaced with d1.shape[0] . 掩码大小(硬编码5)可以替换为d1.shape[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM