首页 > 解决方案 > 根据常量 python 列表设置张量值的优雅方法

问题描述

我有一个 const python 列表

listA = [1, 2, 3, 23, ...]

和一个张量

tensorA = [[1, 3, 5, 7, 23,...]]

现在我想修改tensorAlistA

对于 tensorA 中的每个元素x,如果x也在,listA则保持原样,否则使用默认值,就像-1.

在这个转变之后,tensorA就像

tensorB = [[1, 3, -1, -1, 23, ...]]

有什么优雅的方法来进行这种转换吗?

标签: pythontensorflow

解决方案


由于 TensorFlow 目前没有 NumPy 之类的东西isin,因此您需要进行全面比较:

import tensorflow as tf

listA = tf.constant([1, 2, 3, 23])
tensorA = tf.constant([[1, 3, 5, 7, 23]])

isInList = tf.reduce_any(tf.equal(tf.expand_dims(tensorA, axis=-1), listA), axis=-1)
tensorB = tf.where(isInList, tensorA, -1)
tf.print(tensorB)
# [[1 3 -1 -1 23]]

推荐阅读