# Install and load the required package
# install.packages("keras")
library(keras)
# Function to get data
get_data <- function() {
mnist <- dataset_mnist()
x_test <- mnist$test$x
y_test <- mnist$test$y
# Reshape and normalize
x_test <- array_reshape(x_test, c(nrow(x_test), 28 * 28)) / 255
return(list(x_test = x_test, y_test = y_test))
}
# Sigmoid activation function
sigmoid <- function(x) {
return(1 / (1 + exp(-x)))
}
# Softmax activation function
softmax <- function(x) {
exp_x <- exp(x - max(x)) # Prevent overflow
return(exp_x / rowSums(exp_x))
}
# Predict function
predict <- function(network, x) {
W1 <- network$W1
W2 <- network$W2
W3 <- network$W3
b1 <- network$b1
b2 <- network$b2
b3 <- network$b3
a1 <- x %*% W1 + b1
z1 <- sigmoid(a1)
a2 <- z1 %*% W2 + b2
z2 <- sigmoid(a2)
a3 <- z2 %*% W3 + b3
y <- softmax(a3)
return(y)
}
# Initialize network
initialize_network <- function(input_size, hidden_size1, hidden_size2, output_size) {
network <- list()
network$W1 <- matrix(rnorm(input_size * hidden_size1), nrow = input_size) * 0.01
network$b1 <- matrix(0, nrow = 1, ncol = hidden_size1)
network$W2 <- matrix(rnorm(hidden_size1 * hidden_size2), nrow = hidden_size1) * 0.01
network$b2 <- matrix(0, nrow = 1, ncol = hidden_size2)
network$W3 <- matrix(rnorm(hidden_size2 * output_size), nrow = hidden_size2) * 0.01
network$b3 <- matrix(0, nrow = 1, ncol = output_size)
return(network)
}
# Main program
data <- get_data() # Get test data and labels
x <- data$x_test
y_true <- data$y_test
network <- initialize_network(28 * 28, 128, 64, 10) # Initialize network
accuracy_cnt <- 0
for (i in 1:nrow(x)) {
y <- predict(network, x[i, , drop = FALSE]) # Keep input shape
p <- which.max(y) - 1 # R indices start at 1
if (p == y_true[i]) {
accuracy_cnt <- accuracy_cnt + 1
}
}
accuracy <- accuracy_cnt / nrow(x)
cat(sprintf("Accuracy: %.2f%%\n", accuracy * 100))
展开/折叠结果
Accuracy: 10.10%
发表回复