I'm having some problem :
I have this matrix array :
The dimension is : [1] 27455 784
I want to transform the 2nd Dimension into 28 x 28 array
Basically I want to change it into Convolution2D Input Shape (n_samples, height, width, channels) for TensorFlow The channels number is 1 because the image is in grayscale How can I transform the 784 into 28x28 array and add another array as channels = 1 ?
Thanks a lot!
I try this :
# reshape 1-D data into 3-D data
train_x_img <- train_x
dim(train_x_img) <- c(27455, 28,28)
test_x_img <- test_x
dim(test_x_img) <- c(7172, 28,28,)
# check the dimensions of the 3-D data
dim(train_x_img)
But I guess it is wrong, because the value is not inserted in a correct order.
CodePudding user response:
When R handles indexing for arrays or matrices, it assumes that the ordering as primarily on the columns. You, however, appear to want to create a 25 x 25 matrix-slice based on successive rows of that larger matrix, so the first thing to do is transpose so the row values are in columns columns:
train_x_img <- t( train_x ) # now 784 x 27455
Fold the previous row values, now in columns by re-dimensioning:
dim(train_x_img) <- c(28,28, 27455)
And now, because you want the third dimension to be recast as the first index, use base R's aperm
function:
train_x_img <- aperm(train_x_img, c(3, 1,2)
Demonstration with a somewhat smaller object:
x <- matrix(1:24, 4, 6) # 4 x 6 example
x
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 5 9 13 17 21 # desire rows to be "folded"
[2,] 2 6 10 14 18 22
[3,] 3 7 11 15 19 23
[4,] 4 8 12 16 20 24
a <- t(x) # now 6 x 4
dim(a) <- c(2,3,4) # fold the first dimension in two smaller dimensions
a2 <- aperm(a, c(3,1,2)) # reorder the indices
Examine the first entries indexed by the first index
a2[1,,]
[,1] [,2] [,3]
[1,] 1 9 17
[2,] 5 13 21 # success, that matrix is composed of the first row of x