gpt4 book ai didi

python - 如何为 4d 张量中的 k 个最大元素创建一个单热张量?

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:47 25 4
gpt4 key购买 nike

给定一个形状张量(2,3,3,1),其中批量大小为 2,每个矩阵的形状为(3,3,1)。如何从每个矩阵中找到 k 个最大元素并创建一个 one-hot 矩阵,使得这 k 个位置的条目为 1,其他位置为 0。示例:(请注意,为了简单起见,每个条目都是 float ,使用整数)

input_tensor=[[[1, 5, 7],
[2, 8, 1],
[3, 9, 1],
],
[[0, 9, 5],
[6, 0, 4],
[3, 0, 8]
]
]

k=3 的单热张量:

output_tensor=[[[0, 0, 1],
[0, 1, 0],
[0, 1, 0],
],
[[0, 1, 0],
[1, 0, 0],
[0, 0, 1]
]
]

tf.nn.top_k 将仅返回最后一个维度中的 k 个最大元素。如何从 3d 张量中获取 k 个最大元素 ex:(3,3,1)。此外 tf.one_hot 会在指定深度和给定索引的每一行中放置一个 1,但此处情况并非如此。

最佳答案

如果你想从每个矩阵中找到k个最大的元素,可以使用以下方法。

import tensorflow as tf

input_tensor = tf.constant([[[1, 5, 7],[2, 8, 1],[3, 9, 1]],
[[0, 9, 5],[6, 0, 4],[3, 0, 8]]],dtype=tf.int32)

k_tf = tf.placeholder(shape=(),dtype=tf.int32)

temp = tf.reshape(input_tensor,shape=(input_tensor.shape[0],-1))
# [[1 5 7 2 8 1 3 9 1]
# [0 9 5 6 0 4 3 0 8]]
result = tf.reduce_sum(tf.one_hot(indices=tf.nn.top_k(temp,k=k_tf)[1], depth=temp.shape[1]), axis=1)
# [[0. 0. 1. 0. 1. 0. 0. 1. 0.]
# [0. 1. 0. 1. 0. 0. 0. 0. 1.]]
result = tf.reshape(result,input_tensor.shape)

with tf.Session() as sess:
print('k=2:')
print(sess.run(result, feed_dict={k_tf: 2}))
print('k=3:')
print(sess.run(result,feed_dict={k_tf:3}))

k=2:
[[[0. 0. 0.]
[0. 1. 0.]
[0. 1. 0.]]

[[0. 1. 0.]
[0. 0. 0.]
[0. 0. 1.]]]
k=3:
[[[0. 0. 1.]
[0. 1. 0.]
[0. 1. 0.]]

[[0. 1. 0.]
[1. 0. 0.]
[0. 0. 1.]]]

关于python - 如何为 4d 张量中的 k 个最大元素创建一个单热张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55665304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com