python - 如何使用 Tensorflow 功能 API 沿批量维度进行广播?
问题描述
在某些应用中,比如 slot attention(在Pytorch 中实现),有必要沿着批处理维度进行广播。但是,我看不到如何使用功能 API 执行此操作。例如,
import tensorflow as tf
const = tf.ones((1,4))
input = tf.keras.layers.Input((4))
const = tf.broadcast_to(const, input.shape)
引发以下错误:
ValueError: Cannot convert a partially known TensorShape to a Tensor: (None, 4)
因此,我求助于子类tf.keras.Model
化,但我想将我的代码保留在功能 API 中。有谁知道如何做到这一点?
解决方案
最后通过使用找到了答案tf.keras.backend.shape
:
const = tf.ones((1,4))
input = tf.keras.layers.Input((4))
const = tf.broadcast_to(const, [tf.keras.backend.shape(input)[0], 4] )
# Shape of const is now (None, 4)
推荐阅读
- c# - .NET Core - 使用参数创建自定义 AuthorizationAttribute
- google-apps-script - 使谷歌工作表复选框可切换但不可编辑
- python - 从多个打印语句打印到同一行
- javascript - 如何将事件附加到课程
- php - 在 php 中执行文件读取操作时面临问题
- objective-c - 如何跟踪属于另一个应用程序的窗口的位置
- azure - Azure Synapse Polybase/外部表 - 仅返回最新文件
- r - 如何引导非平稳时间序列包 R
- azure - 将 Azure 订阅移动到新的管理组
- macos - 如何调试 Microsoft Outlook for Mac(或 Windows)Web 加载项?