Python 从tensorflow中的另一个列表中选择elemetn
我正在研究tensorflow,我有以下问题Python 从tensorflow中的另一个列表中选择elemetn,python,tensorflow,indexing,tensorflow2.0,Python,Tensorflow,Indexing,Tensorflow2.0,我正在研究tensorflow,我有以下问题 import tensorflow as tf import numpy as np from tensorflow.keras import losses from tensorflow import nn #2*3 label = np.array([[2, 0, 1], [0, 2, 1]]) #2*3*3 logit = np.array([[[.9, .5, .05], [.35, .01, .3], [.45, .91, .94]],
import tensorflow as tf
import numpy as np
from tensorflow.keras import losses
from tensorflow import nn
#2*3
label = np.array([[2, 0, 1], [0, 2, 1]])
#2*3*3
logit = np.array([[[.9, .5, .05], [.35, .01, .3], [.45, .91, .94]],
[[.05, .2, .4], [.05, .29, .6], [.35, .01, .02]]])
#find the value corresponding to label index by row
output = nn.log_softmax(logit)
我有
output = tf.Tensor(
[[[-0.74085818 -1.14085818 -1.59085818]
[-0.97945321 -1.31945321 -1.02945321]
[-1.43897936 -0.97897936 -0.94897936]]
[[-1.27561467 -1.12561467 -0.92561467]
[-1.38741927 -1.14741927 -0.83741927]
[-0.88817684 -1.22817684 -1.21817684]]], shape=(2, 3, 3), dtype=float64)
我想通过标签
中的索引从输出
中选择元素。也就是说,我的最终结果应该是
[[1.59085822 0.97945321 0.97897935] #2, 0, 1
[1.27561462 0.83741927 1.22817683]], #0, 2, 1
shape=(2, 3), dtype=float64)
你不能直接这样做。实现这一目标的正确方法是首先在标签上涂抹。然后使用
tf.boolean\u mask
从输出日志中进行选择
以下是一个例子:
将tensorflow导入为tf
将numpy作为np导入
来自tensorflow.keras进口损失
从tensorflow导入nn
#2*3
label=np.array([[2,0,1],[0,2,1]]
#2*3*3
logit=np.array([.9,5,05],.35,01,3],.45,91,94],
[[.05, .2, .4], [.05, .29, .6], [.35, .01, .02]]])
#按行查找标签索引对应的值
输出=nn.log\u softmax(logit)
one_hot=tf.one_hot(标签,3,数据类型=tf.int32)
#
结果_vec=tf.boolean_mask(输出,一个热)#结果是一个向量
#
结果=tf.重塑(结果向量,标签.形状)
结果会是:(你是否错过了问题中的消极迹象?)
您好,请查看我的答案,看看这是否解决了您的问题