---
title: "R, fast.ai and CycleGAN"
author: "Turgut"
date: "11/27/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = TRUE)
```


## R interface to fastai

The fastai package provides R wrappers to
[fastai](https://github.com/fastai/fastai).

The fastai library simplifies training fast and accurate neural nets using
modern best practices. See the
[fastai website](https://henry090.github.io/fastai/) to get started. The library
is based on research into deep learning best practices undertaken at `fast.ai`,
and includes "out of the box" support for `vision`, `text`, `tabular`,
[audio](https://github.com/fastaudio/fastaudio),
[time-series](https://github.com/tcapelle/timeseries_fastai) and `collab`
(collaborative filtering) models.


```{r eval=T,echo=F}
devtools::install_github('rstudio/reticulate',dependencies=FALSE)
devtools::install_github("henry090/fastai",dependencies=FALSE)
library(fastai)
install_fastai(gpu = TRUE)
detach("package:fastai", unload = TRUE)
```


CycleGAN by [Tanishq Abraham](https://github.com/tmabraham/UPIT) makes
building and training a CycleGAN model very easily.

## Dataset

Read data:

```{r}
library(fastai)
library(magrittr)
art = '../input/gan-getting-started'


trainA_path = file.path(art,'photo_jpg')
trainB_path = file.path(art,'monet_jpg')
```

## Dataloader

Create a dataloader:

```{r}
dls = get_dls(trainA_path, trainB_path, num_A = 30, load_size = 512, crop_size = 256, bs = 4)
```

See batch:
    
```{r}
dls %>% one_batch()
```

## Cycle GAN

Create model:

```{r}
cycle_gan = CycleGAN(3,3,64)
learn = cycle_learner(dls, cycle_gan,opt_func=partial(Adam(),mom=0.5,sqr_mom=0.999))
```

Architecture:

```{r}
learn
```

## Trainig

And fit the model:

```{r}
result = learn %>% fit_flat_lin(20, 30, 2e-5)
```

See results:
    
```{r}
tail(result,5)
```

## Result

See results:

```{r}
learn %>% show_results()
```

```{r echo=F}
learn %>% show_results()
```

```{r echo=F}
learn %>% show_results()
```

## Conclusion

Get predictions:

```{r}
learn %>% get_preds_cyclegan(trainA_path, 'images', suffix = 'jpg')

setwd('images')

zip(zipfile = 'images.zip', files = '.')

unlink("./*.jpg")

file.copy(from='images.zip', to="/kaggle/working/", 
          overwrite = TRUE, recursive = FALSE, 
          copy.mode = TRUE)
```