## Importing packages

# This R environment comes with all of CRAN and many other helpful packages preinstalled.
# You can see which packages are installed by checking out the kaggle/rstats docker image: 
# https://github.com/kaggle/docker-rstats

## Put your packages here
library(readr)
library(keras)
library(data.table)

## Running code

# In a notebook, you can run a single code cell by clicking in the cell and then hitting 
# the blue arrow to the left, or by clicking in the cell and pressing Shift+Enter. In a script, 
# you can run code by highlighting the code you want to run and then clicking the blue arrow
# at the bottom of this window.

## Reading in files

# You can access files from datasets you've added to this kernel in the "../input/" directory.
# You can see the files added to this kernel by running the code below. 

list.files(path = "../input")
list.files(path = "../input/Kannada-MNIST")

## Saving data

# If you save any files or images, these will be put in the "output" directory. You 
# can see the output directory by committing and running your kernel (using the 
# Commit & Run button) and then checking out the compiled version of your kernel.



## Read in data
train <- read_csv('../input/Kannada-MNIST/train.csv')
train_images <- train[,-1]
train_labels <- train[,1]
train_images <- as.matrix(train_images)
train_labels <- as.matrix(train_labels)

test <- read_csv('../input/Kannada-MNIST/test.csv')
test_images <- test[,-1]
test_images <- as.matrix(test_images)



## Put your neural network here

network <- keras_model_sequential() %>%
  layer_dense(units = 512, activation = 'relu', input_shape = c(28 * 28)) %>%
  layer_dense(units = 10, activation = 'softmax')

## Compile the model

network %>% compile(
  optimizer = 'rmsprop',
  loss = 'categorical_crossentropy',
  metrics = c('accuracy')
)

## Preprocess Data

train_images <- train_images / 255

test_images <- test_images / 255

## Prepare the labels

train_labels <- to_categorical(train_labels)

## Fit the model to the training data

history <- network %>% fit(
  train_images, train_labels, 
  epochs = 5, batch_size = 128,
  validation_split = 0.2)

plot(history)



## Make a submission

submission <- read_csv('../input/Kannada-MNIST/sample_submission.csv')

test_labels <- network %>% predict_classes(test_images)

submission$label <- test_labels

fwrite(submission, 'submission.csv')
