---
title: "Quasi-Randomized -- Neural -- Networks"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Quasi-Randomized -- Neural -- Networks}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r}
library(learningmachine)
library(caret)
library(mlbench)
library(palmerpenguins)
```

```{r}
X <- as.matrix(mtcars[,-1])
y <- mtcars$mpg
```

```{r}
set.seed(123)
(index_train <- base::sample.int(n = nrow(X),
                                 size = floor(0.8*nrow(X)),
                                 replace = FALSE))
X_train <- X[index_train, ]
y_train <- y[index_train]
X_test <- X[-index_train, ]
y_test <- y[-index_train]
dim(X_train)
dim(X_test)
```

# 1 `ranger` regression

```{r}
obj <- learningmachine::Regressor$new(method = "ranger", nb_hidden=5L,  
        pi_method = "splitconformal")
obj$get_type()
obj$get_name()
```

```{r}
t0 <- proc.time()[3]
obj$fit(X_train, y_train)
cat("Elapsed: ", proc.time()[3] - t0, "s \n")
```

```{r}
print(sqrt(mean((obj$predict(X_test)$preds - y_test)^2)))
```

```{r fig.width=7.2}
t0 <- proc.time()[3]
obj$fit(X_train, y_train)
cat("Elapsed: ", proc.time()[3] - t0, "s \n")

obj$set_level(95)

res <- obj$predict(X = X_test)

plot(c(y_train, res$preds), type='l',
     main="",
     ylab="",
     ylim = c(min(c(res$upper, res$lower, y)),
              max(c(res$upper, res$lower, y))))
lines(c(y_train, res$upper), col="gray60")
lines(c(y_train, res$lower), col="gray60")
lines(c(y_train, res$preds), col = "red")
lines(c(y_train, y_test), col = "blue")

mean((y_test >= as.numeric(res$lower)) * (y_test <= as.numeric(res$upper)))
```

# 2 - Using `Classifier` object

```{r}
set.seed(43)
X <- as.matrix(iris[, 1:4])
# y <- factor(as.numeric(iris$Species))
y <- iris$Species

index_train <- base::sample.int(n = nrow(X),
                                 size = floor(0.8*nrow(X)),
                                 replace = FALSE)
X_train <- X[index_train, ]
y_train <- y[index_train]
X_test <- X[-index_train, ]
y_test <- y[-index_train]
dim(X_train)
dim(X_test)

obj <- learningmachine::Classifier$new(method = "ranger", nb_hidden=5L, pi_method="kdesplitconformal", type_prediction_set="score")
obj$get_type()
obj$get_name()
obj$set_B(10)
obj$set_level(95)

t0 <- proc.time()[3]
obj$fit(X_train, y_train)
cat("Elapsed: ", proc.time()[3] - t0, "s \n")

probs <- obj$predict_proba(X_test)
```

```{r fig.width=8, fig.height=4, eval=TRUE}
df <- reshape2::melt(probs$sims$setosa[1:3, ])
df$Var2 <- NULL 
colnames(df) <- c("individual", "prob_setosa")
df$individual <- as.factor(df$individual)
ggplot2::ggplot(df, aes(x=individual, y=prob_setosa)) + geom_boxplot() + coord_flip()
```

```{r fig.width=8, fig.height=4, eval=TRUE}
ggplot2::ggplot(df, aes(x=prob_setosa, fill=individual)) + geom_density(alpha=.3)
```

```{r}
obj$summary(X_test, y=y_test, 
            class_name = "setosa",
            show_progress=FALSE)
```
