# -*- coding: utf-8 -*-
"""Deep Recommender in Keras.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1__80a8fgl-59VcUzlAToo4LDiQ8AeyVn
"""

import keras
import pandas as pd
import numpy as np

import keras.backend as K

def masked_mean_squared_loss(y_true, y_pred):
  mask = K.tf.cast(y_true >= 1.0e-09, dtype = K.tf.float32)
  num_ratings = K.sum(mask)
  return K.mean(K.tf.scalar_mul(1/num_ratings, K.tf.multiply(mask, K.tf.square(K.tf.subtract(y_true, y_pred)))))

from keras.layers import Input, Dense, Dropout

from keras.models import Model

input_layer = Input(shape=(1024,))

encoder_1 = Dense(512, activation = 'selu')(input_layer)

encoder_2 = Dense(256, activation = 'selu')(encoder_1)

dropout = Dropout(0.5)(encoder_2)

decoder_1 = Dense(512, activation = 'selu')(dropout)

decoder_2 = Dense(1024, activation = 'selu')(decoder_1)

autoencoder = Model(input_layer, decoder_2)

opt = keras.optimizers.SGD(lr = 0.1, decay = 1.0e-6, momentum = 0.9, nesterov = True)

autoencoder.compile(loss = masked_mean_squared_loss, optimizer = opt)

def fetch_data(mode = "train"):
  
  data = pd.read_csv("/path/to/file")
  
  if(mode == "train"):
    
    return np.array(data[:][0:480000].values)
    
  else:
    
    return np.array(data[:][480001:480189].values)

for i in range(5): # Epochs
  
  x_train = fetch_data()
  
  x_test = fetch_data(mode = 'test')
  
  for i in range(10): # Iterations
    
    autoencoder.fit(x_train, x_train,  epochs = 1, batch_size = 128, shuffle = True, validation_data = (x_test, x_test))
    
    x_train = autoencoder.predict(x_train)

from google.colab import files

model_json = autoencoder.to_json()
with open("autoencoder.json","w") as json_file:
     json_file.write(model_json)

files.download("autoencoder.json")

autoencoder.save('autoencoder.h5')
files.download('autoencoder.h5')

