Skip to content

Commit

Permalink
Ann labs structured
Browse files Browse the repository at this point in the history
  • Loading branch information
alexsanchezpla committed May 8, 2024
1 parent bedc4db commit c61ef60
Show file tree
Hide file tree
Showing 18 changed files with 3,928 additions and 51 deletions.
51 changes: 0 additions & 51 deletions labs/ANNs/Diabetes1.ipynb

This file was deleted.

File renamed without changes.
File renamed without changes.
611 changes: 611 additions & 0 deletions labs/ANNs/Dividend_prediction-R/Prediction_with_ANN.html

Large diffs are not rendered by default.

93 changes: 93 additions & 0 deletions labs/ANNs/Dividend_prediction-R/Prediction_with_ANN.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
---
title: "Prediction with (shallow) Neural Networks"
format: html
editor: visual
---

# An example using R

## A predictive ANN

We use the `neuralnet` package to build a simple neural network to predict if a type of stock pays dividends or not.

```{r echo=TRUE}
if (!require(neuralnet))
install.packages("neuralnet", dep=TRUE)
```

## Data for the example

And use the `dividendinfo.csv` dataset from <https://github.com/MGCodesandStats/datasets>

```{r echo=TRUE}
mydata <- read.csv("https://raw.githubusercontent.com/MGCodesandStats/datasets/master/dividendinfo.csv")
str(mydata)
```

## Data pre-processing

```{r echo=TRUE}
normalize <- function(x) {
return ((x - min(x)) / (max(x) - min(x)))
}
normData <- as.data.frame(lapply(mydata, normalize))
```

## Test and training sets

Finally we break our data in a test and a training set:

```{r echo=TRUE}
perc2Train <- 2/3
ssize <- nrow(normData)
set.seed(12345)
data_rows <- floor(perc2Train *ssize)
train_indices <- sample(c(1:ssize), data_rows)
trainset <- normData[train_indices,]
testset <- normData[-train_indices,]
```

## Training a neural network

We train a simple NN with two hidden layers, with 4 and 2 neurons respectively.

```{r echo=TRUE}
#Neural Network
library(neuralnet)
nn <- neuralnet(dividend ~ fcfps + earnings_growth + de + mcap + current_ratio,
data=trainset,
hidden=c(2,1),
linear.output=FALSE,
threshold=0.01)
```

## Network plot

The output of the procedure is a neural network with estimated weights

```{r echo=TRUE}
plot(nn, rep = "best")
```

## Predictions

```{r echo=TRUE}
temp_test <- subset(testset, select =
c("fcfps","earnings_growth",
"de", "mcap", "current_ratio"))
nn.results <- compute(nn, temp_test)
results <- data.frame(actual =
testset$dividend,
prediction = nn.results$net.result)
head(results)
```

## Model evaluation

```{r echo=TRUE}
roundedresults<-sapply(results,round,digits=0)
roundedresultsdf=data.frame(roundedresults)
attach(roundedresultsdf)
table(actual,prediction)
```

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit c61ef60

Please sign in to comment.