- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试使用从 tf.nn.top_k 返回的索引从第二个张量中提取值。
我试过使用 numpy 类型索引,以及直接使用 tf.gather_nd,但我注意到索引是错误的。
# temp_attention_weights of shape [I, B, 1, J]
top_values, top_indices = tf.nn.top_k(temp_attention_weights, k=top_k)
# top_indices of shape [I, B, 1, top_k], base_encoder_transformed of shape [I, B, 1, J]
# I now want to extract from base_encoder_transformed top_indices
base_encoder_transformed = tf.gather_nd(base_encoder_transformed, indices=top_indices)
# base_encoder_transformed should be of shape [I, B, 1, top_k]
我注意到 top_indices 的格式错误,但我似乎无法将其转换为在 tf.gather_nd 中使用,其中最内层的维度用于索引来自 base_encoder_transformed 的每个对应元素。有人知道将 top_indices 转换为正确格式的方法吗?
最佳答案
top_indices
只会在最后一个轴上建立索引,您也需要为其余轴添加索引。使用 tf.meshgrid
很容易:
import tensorflow as tf
# Example input data
I = 4
B = 3
J = 5
top_k = 2
x = tf.reshape(tf.range(I * B * J), (I, B, 1, J)) % 7
# Top K
top_values, top_indices = tf.nn.top_k(x, k=top_k)
# Make indices for the rest of axes
ii, jj, kk, _ = tf.meshgrid(
tf.range(I),
tf.range(B),
tf.range(1),
tf.range(top_k),
indexing='ij')
# Stack complete index
index = tf.stack([ii, jj, kk, top_indices], axis=-1)
# Get the same values again
top_values_2 = tf.gather_nd(x, index)
# Test
with tf.Session() as sess:
v1, v2 = sess.run([top_values, top_values_2])
print((v1 == v2).all())
# True
关于python - 如何将来自 tf.nn.top_k 的索引与 tf.gather_nd 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54196149/
我正在遵循this link中的教程并尝试改变模型的评估方法(底部)。我想要获得前 5 名的评估,并且我正在尝试使用以下代码: topFiver=tf.nn.in_top_k(y, y_, 5, na
我想在 pytorch 中实现 tf.nn.in_top_k。这是tf.nn.in_top_k的链接, tf.math.in_top_k( targets, predictions, k, n
对于像这样的任何二维张量 [[2,5,4,7],[7,5,6,8]], 我想对每一行中的前 k 元素进行 softmax,然后通过将所有其他元素替换为 0 来构造一个新的张量。 结果应该是获取每行 [
我有两个多维张量a和b。我想按 a 的值对它们进行排序。 我找到了tf.nn.top_k能够对张量进行排序并返回用于对输入进行排序的索引。如何使用 tf.nn.top_k(a, k=2) 返回的索引对
我在使此自定义损失函数(它检查 y_pred 数据的排序是否与 y_true 提供的实际排序索引)工作时遇到了一些问题: def custom_objective(y_true, y_pred):
我正在尝试在 tensorflow 中编写一个仅传播每个特征图的前 k 个值的操作。 例子: k=1,输入大小是[batch_size, x, y, channels] 假设它是[1,2,2,3] 输
我正在尝试预测给予患者的药物。对于每种药物,我在预测中有一列(通过 softmax)指示患者获得这种药物的概率。 但显然人们可以同时服用多种药物,因此我有另一个模型来尝试预测给予的不同药物的数量。 我
我正在尝试使用从 tf.nn.top_k 返回的索引从第二个张量中提取值。 我试过使用 numpy 类型索引,以及直接使用 tf.gather_nd,但我注意到索引是错误的。 # temp_atte
我有一个形状为 (10, 32, 32, 128) 的 4-D 张量。我想为所有前 N 个元素生成一个二进制掩码。 arr = tf.random_normal(shape=(10, 32, 32,
Pytorch 提供 torch.topk(input, k, dim=None, largest=True, sorted=True) 函数来计算给定 的 k 最大元素>input 沿给定维度 di
我是一名优秀的程序员,十分优秀!