From eae5a4f37ec1f7bc7972ac9334ea3879526360c9 Mon Sep 17 00:00:00 2001 From: mehce338 <mehce338@student.liu.se> Date: Tue, 10 Dec 2024 16:54:33 +0100 Subject: [PATCH] assignment 3 started --- lab3/assignment4.R | 83 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 lab3/assignment4.R diff --git a/lab3/assignment4.R b/lab3/assignment4.R new file mode 100644 index 0000000..6a5e365 --- /dev/null +++ b/lab3/assignment4.R @@ -0,0 +1,83 @@ +library(neuralnet) +set.seed(1234567890) + + +Var <- runif(500, 0, 10) + + +mydata <- data.frame(Var, Sin=sin(Var)) + + +tr <- mydata[1:25,] # Training +te <- mydata[26:500,] # Test + + +# Random initialization of the weights in the interval [-1, 1] +winit <- runif(10,-1,1) +formula <- Sin ~ Var + nn <- neuralnet( formula , data = tr, hidden = c(10), startweights = winit ) + # Plot of the training data (black), test data (blue), and predictions (red) + plot(tr, cex=2) + points(te, col = "blue", cex=1) + points(te[,1],predict(nn,te), col="red", cex=1) + +### PART 2 ### + + +h1 <- function(x) { + x +} + + +h2 <- function(x) { + ifelse(x>0,x,0) +} + +h3 <- function(x) { + log(1 + exp(x)) +} + + + +nn_h1 <- neuralnet( formula , data = tr, hidden = c(10), startweights = t(winit), act.fct = h1 ) +# Plot of the training data (black), test data (blue), and predictions (red) +plot(tr, cex=2, main = "h1") +points(te, col = "blue", cex=1) +points(te[,1],predict(nn_h1,te), col="red", cex=1) + + + +nn_h2 <- neuralnet( formula , data = tr, hidden = c(10), startweights = t(winit), act.fct = h2 ) +# Plot of the training data (black), test data (blue), and predictions (red) +plot(tr, cex=2, main="h2") +points(te, col = "blue", cex=1) +points(te[,1],predict(nn_h2,te), col="red", cex=1) + + + + +nn_h3 <- neuralnet( formula , data = tr, hidden = c(10), startweights = t(winit), act.fct = h3 ) +# Plot of the training data (black), test data (blue), and predictions (red) +plot(tr, cex=2, main = "h3") +points(te, col = "blue", cex=1) +points(te[,1],predict(nn_h3,te), col="red", cex=1) + + +# part 3 + + +Var1 <- runif(500, 0, 50) + + +mydata1 <- data.frame(Var = Var1, Sin=sin(Var1)) + +plot(mydata1, cex=2, main = "500 random points",ylim = c(-10,10)) +points(mydata1, col = "blue", cex=1) +pred <- predict(nn,te) +prediciton <- predict(nn,mydata1) +points(mydata1[,1],prediciton, col="red", cex = 1) + + +# Part 4 + + -- GitLab