Skip to content

Instantly share code, notes, and snippets.

@bquast
Created May 13, 2023 20:58
Show Gist options
  • Select an option

  • Save bquast/5ddf3ddf515284724285d390da448b71 to your computer and use it in GitHub Desktop.

Select an option

Save bquast/5ddf3ddf515284724285d390da448b71 to your computer and use it in GitHub Desktop.
# cnn.R
# Bastiaan Quast
# bquast@gmail.com
# Convolution function
conv2d <- function(input, filter, stride = 1) {
input_height <- dim(input)[1]
input_width <- dim(input)[2]
filter_height <- dim(filter)[1]
filter_width <- dim(filter)[2]
output_height <- (input_height - filter_height) %/% stride + 1
output_width <- (input_width - filter_width) %/% stride + 1
output <- matrix(0, output_height, output_width)
for (i in 1:output_height) {
for (j in 1:output_width) {
h_start <- (i - 1) * stride + 1
h_end <- h_start + filter_height - 1
w_start <- (j - 1) * stride + 1
w_end <- w_start + filter_width - 1
output[i, j] <- sum(input[h_start:h_end, w_start:w_end] * filter)
}
}
return(output)
}
# Pooling function
max_pool2d <- function(input, pool_size, stride) {
input_height <- dim(input)[1]
input_width <- dim(input)[2]
output_height <- (input_height - pool_size) %/% stride + 1
output_width <- (input_width - pool_size) %/% stride + 1
output <- matrix(0, output_height, output_width)
for (i in 1:output_height) {
for (j in 1:output_width) {
h_start <- (i - 1) * stride + 1
h_end <- h_start + pool_size - 1
w_start <- (j - 1) * stride + 1
w_end <- w_start + pool_size - 1
output[i, j] <- max(input[h_start:h_end, w_start:w_end])
}
}
return(output)
}
# Activation function (ReLU)
relu <- function(x) {
return(max(0, x))
}
# Apply activation function to a matrix
apply_relu <- function(matrix) {
return(matrix(matrix, nrow = nrow(matrix), ncol = ncol(matrix), byrow = TRUE, FUN = relu))
}
# Define the input image
input_image <- matrix(runif(25), 5, 5)
# Define the filter/kernel
conv_filter <- matrix(c(1, 0, -1,
1, 0, -1,
1, 0, -1), 3, 3)
# Apply the convolution operation
conv_output <- conv2d(input_image, conv_filter)
# Apply the activation function
conv_output_relu <- apply_relu(conv_output)
# Perform max pooling
pool_output <- max_pool2d(conv_output_relu, pool_size = 2, stride = 2)
# Flatten the output
flattened_output <- as.vector(pool_output)
# Define the weights for the fully connected layer
fc_weights <- runif(length(flattened_output))
# Calculate the output of the fully connected layer
fc_output <- sum(flattened_output * fc_weights)
# Apply the activation function to the fully connected layer output
fc_output_relu <- relu(fc_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment