読者です 読者をやめる 読者になる 読者になる

RでDeep Learning(10)

Affineレイヤの書き換え

Affine <- R6Class("Affine",

	public = list(
		W = NULL,
		b = NULL,
		x = NULL,
		x_shape = NULL,
		dW = NULL,
		db = NULL,
		
		initialize = function(W,b){
			self$W <- W
			self$b <- b
		},

		forward = function(x){

			dummy_shape <- dim(x)
			dummy_shape[1] <- dim(x)[2]
			dummy_shape[2] <- dim(x)[1]
			self$x_shape <- dummy_shape
			batch <- dim(x)[4]
			seld$x <-  x %>% aperm(.,c(2,1,3,4)) %>% as.vector %>% matrix(.,nrow=batch,byrow=T)
			out <- (self$x %*% self$W)+matrix(rep(self$b,batch),nrow=batch,byrow=T)
			return(out) 
		},
		
		backward = function(dout){
			dx <- dout %*% (self$W %>% t())
			self$dW <- (self$x %>% t()) %*% dout
			self$db <- apply(dout,2,sum)
			dx <- array(t(dx),self$x_shape) %>% aperm(.,c(2,1,3,4))
			return(dx)
		}
	)
)