python - 根据常量 python 列表设置张量值的优雅方法
问题描述
我有一个 const python 列表
listA = [1, 2, 3, 23, ...]
和一个张量
tensorA = [[1, 3, 5, 7, 23,...]]
现在我想修改tensorA
为listA
:
对于 tensorA 中的每个元素
x
,如果x
也在,listA
则保持原样,否则使用默认值,就像-1
.
在这个转变之后,tensorA
就像
tensorB = [[1, 3, -1, -1, 23, ...]]
有什么优雅的方法来进行这种转换吗?
解决方案
由于 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]]
推荐阅读
- android - 确认并测试是否从 android studio 上的服务器接收数据
- rest - Guzzle HTTP 发送文件流抛出错误-“json_encode 错误:不支持类型”
- php - 使用 CSV 文件更新 MySQL 中已插入的数据
- keras - 重复部分 Keras 模型,取决于输入的数量
- vue.js - 如何在 VueJs 中重置选择下拉菜单
- linux - 守护程序中的线程未运行
- javascript - PHP 将文件文本附加到所有 JavaScript 文件
- wpf - Visual Studio 设计窗口中的 XAML 标记错误
- php - 带有 JQuery AJAX 的搜索功能
- angular - 为什么我在 Angular 6 中的服务出现错误?