面向 R TensorFlow 用户的 NumPy 风格广播

广播,就像 Python 的科学计算库 NumPy 所做的那样,涉及动态扩展形状,以便可以将不同大小的数组传递给需要一致性的操作 - 例如逐元素添加或乘法。在 NumPy 中,广播的工作方式是精确指定的;同样的规则适用于 TensorFlow 操作。对于偶尔查阅 Python 代码的任何人,这篇文章都力求解释清楚。

来源:RStudio AI博客

我们从 R 开发、训练和部署 TensorFlow 模型。但这并不意味着我们不使用用 Python 编写的文档、博客文章和示例。我们在官方 TensorFlow API 文档中查找特定功能;我们从其他人的代码中获得灵感。

官方 TensorFlow API 文档

根据您对 Python 的熟悉程度,存在一个问题。例如:您应该知道广播的工作原理。也许,您会说您对它有点熟悉:所以当数组具有不同的形状时,某些元素会被重复,直到它们的形状匹配并且……而且 R 不是矢量化的吗?

广播

虽然这种全局概念可能在一般情况下有效,例如在浏览博客文章时,但不足以理解 TensorFlow API 文档中的示例。在这篇文章中,我们将尝试更准确地理解,并通过具体示例进行检查。

说到例子,这里有两个激励人心的例子。

广播的实际应用

第一个使用 TensorFlow 的 matmul 将两个张量相乘。您想猜一下结果吗 - 不是数字,而是它通常如何产生?这是否运行无误 - 矩阵不应该是二维的(用 TensorFlow 的话来说,是 2 阶张量)吗?

matmul 等级
a <- tf$constant(keras::array_reshape(1:12, dim = c(2, 2, 3)))a # tf.Tensor(# [[[ 1. 2. 3.]# [ 4. 5. 6.]]# # [[ 7. 8. 9.]# [10. 11. 12.]]], shape=(2, 2, 3), dtype=float64)b <- tf$constant(keras::array_reshape(101:106, dim = c(1, 3, 2)))b # tf.Tensor(# [[[101. 102.]# [103. 104.]# [105. 106.]]], shape=(1, 3, 2), dtype=float64)c <- tf$matmul(a, b)
a <- tf$constant(keras::array_reshape(1:12, dim = c(2, 2, 3)))a # tf.Tensor(# [[[ 1. 2. 3.]# [ 4. 5. 6.]]# # [[ 7. 8. 9.]# [10. 11. 12.]]], shape=(2, 2, 3), dtype=float64)b <- tf$constant(keras::array_reshape(101:106, dim = c(1, 3, 2)))b # tf.Tensor(# [[[101. 102.]# [103. 104.]# [105. 106.]]], shape=(1, 3, 2), dtype=float64)c <- tf$matmul(a, b) a <- tf $ 常量 ( keras :: 重塑 ( 1 : 12 = c c ( 2 2 3 ) ) ) a a #