我想在我创建并存储在list()
中的张量列表中使用tf$reduce_mean()
。如何获得一个张量列表,并制作一个更高阶的张量,将这些单独的张量作为新张量axis=0
位置的条目?我认为在Python中,您可以使用列表并使用np.newaxis
来实现这一点(tf$newaxis
(。
我想更大的问题是:当Python中的TensorFlow将列表传递给它的函数时,比如:
tf.concat([a, b, c], 0)
R Keras中的平行结构是什么?正如你将在下面看到的,包装list()
不适用于我尝试的方式
以下是我如何使用array()
和apply()
:在基本R中做一个简单的例子
## reduce_mean() behavior I want -- mean across the matrix elements:
a <- matrix(1:4)
b <- matrix(5:8)
c <- matrix(9:12)
## How to do this in base R
(abc <- array(c(a, b, c), dim = c(2, 2, 3)))
#> , , 1
#>
#> [,1] [,2]
#> [1,] 1 3
#> [2,] 2 4
#>
#> , , 2
#>
#> [,1] [,2]
#> [1,] 5 7
#> [2,] 6 8
#>
#> , , 3
#>
#> [,1] [,2]
#> [1,] 9 11
#> [2,] 10 12
apply(abc, MARGIN = c(1,2), FUN = mean)
#> [,1] [,2]
#> [1,] 5 7
#> [2,] 6 8
由reprex包于2020-04-14创建(v0.3.0(
关于TensorFlow中应该是什么样子的猜测:
library(tensorflow)
a <- tf$constant(array(1:4, dim=c(2,2)))
b <- tf$constant(array(5:8, dim=c(2,2)))
c <- tf$constant(array(9:12, dim=c(2,2)))
## Does not work
abc <- list(a, b, c)
# tf$reduce_mean(abc, axis=0)
您可以使用tf$stack
:
a <- tf$constant(array(1:4, dim=c(2,2)))
b <- tf$constant(array(5:8, dim=c(2,2)))
c <- tf$constant(array(9:12, dim=c(2,2)))
abc <- tf$stack(list(a, b, c), axis=0L)
#> tf.Tensor(
#> [[[ 1 3]
#> [ 2 4]]
#>
#> [[ 5 7]
#> [ 6 8]]
#>
#> [[ 9 11]
#> [10 12]]], shape=(3, 2, 2), dtype=int32)
tf$reduce_mean(abc, axis=0L)
#> tf.Tensor(
#> [[5 7]
#> [6 8]], shape=(2, 2), dtype=int32)
注意:不要忘记将L
放在轴号后面,将其转换为整数。