R重塑数组以将矩阵列表中的数据包含两次作为keras的准备

时间:2018-07-30 02:06:56

标签: arrays r reshape keras-2

我正在尝试创建一个3D数组,该数组复制元素(数据的副本),并使两者的行保持相同。最终这将是一个时间序列的keras / tensorflow lstm输入数组(样本,时间步长,特征),出于各种原因,我确定我的时间步长也是我的特征,并且样本是固定的(行)。

一些数据:

perhaps <- matrix(sample(c(0:1), 20, replace = TRUE), nrow = 4, 
ncol = 5)
print(perhaps)
perhaps
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    1    0    1
[2,]    0    0    0    0    1
[3,]    0    1    1    0    1
[4,]    1    0    0    1    1

perhaps_2_lst <- list(perhaps, perhaps)
all.equal(perhaps_2_lst[[1]], perhaps_2_lst[[2]])
[1] TRUE

#construct array from SOF inquestion:15213463
perhaps_arr <- array(
data = do.call(rbind, lapply(perhaps_2_lst, as.vector)),
dim = c(dim = c(dim(perhaps_2_lst[[1]])[1], 
dim(perhaps_2_lst[[1]])[2], dim(perhaps_2_lst[[1]])[2]))

dim(perhaps_arr)
[1] 4 5 5

令人鼓舞。

print(perhaps_arr)
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    0    0    1    1
[3,]    0    1    0    0    0
[4,]    0    1    0    0    0

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    1    1
[2,]    1    0    0    1    1
[3,]    0    0    1    1    1
[4,]    0    0    1    1    1

, , 3

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    0    0    1    1
[3,]    0    1    0    0    0
[4,]    0    1    0    0    0

, , 4

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    1    1
[2,]    1    0    0    1    1
[3,]    0    0    1    1    1
[4,]    0    0    1    1    1

, , 5

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    1    1
[2,]    0    0    0    1    1
[3,]    0    1    0    0    0
[4,]    0    1    0    0    0

糟糕。我猜并不是很熟悉数组。我期待着这样的事情:

, , 1
#perhaps
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    1    0    1
[2,]    0    0    0    0    1
[3,]    0    1    1    0    1
[4,]    1    0    0    1    1
, , 2
#perhaps
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    1    0    1
[2,]    0    0    0    0    1
[3,]    0    1    1    0    1
[4,]    1    0    0    1    1

即。重复相同的数据。现在难过了。对理解此处发生的事情的建议和澄清非常感谢。

1 个答案:

答案 0 :(得分:1)

我们可以使用replicate

n <- 2
replicate(n, perhaps)
#, , 1

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    1    0    1
#[2,]    0    0    0    0    1
#[3,]    0    1    1    0    1
#[4,]    1    0    0    1    1

#, , 2

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    1    0    1
#[2,]    0    0    0    0    1
#[3,]    0    1    1    0    1
#[4,]    1    0    0    1    1