Home > Software engineering >  How do I make an array of matrices in R, like the data from dataset_mnist()? (keras)
How do I make an array of matrices in R, like the data from dataset_mnist()? (keras)

Time:09-23

I want to make my own array of (N x N) matrices that matches the keras-compatible format that is loaded with dataset_mnist(). As

mnist <- dataset_mnist()
x_train <- mnist$train$x
str (x_train)

yields

int [1:60000, 1:28, 1:28] 0 0 0 0 0 0 0 0 0 0 ...

I want to make my own data in this format. Let's say I have 2000 different 100x100 matrices of integers: mat1, mat2, mat3, mat4... mat2000. How can I combine them to produce an object with the structure:

int [1:2000, 1:100, 1:100] ...

that I can then use as input data for keras models?

I've tried:

as.vector (c(mat1, mat2))
as.array (c(mat1, mat2))
rbind (mat1, mat2)

But it does not produce the correctly structured data. Thank you for your help!

CodePudding user response:

concatenate your matrices and make array. Also concatenate matrix dimension and third dimension, which is the number of matrices. Example:

m1 <- matrix(1, 2, 3)
m2 <- matrix(2, 2, 3)
m3 <- matrix(3, 2, 3)

array(c(m1, m2, m3), c(dim(m1), 3))
# , , 1
# 
#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    1    1    1
# 
# , , 2
# 
#      [,1] [,2] [,3]
# [1,]    2    2    2
# [2,]    2    2    2
# 
# , , 3
# 
#      [,1] [,2] [,3]
# [1,]    3    3    3
# [2,]    3    3    3

CodePudding user response:

You can also take a look the package listarrays.

m <- matrix(1:4, ncol = 2)
listarrays::bind_as_rows(m, m, m) |> str()
# int [1:3, 1:2, 1:2] 1 1 1 2 2 2 3 3 3 4 ...
  • Related