import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split

# Reading the Dataset

def read_dataset():
	df = pd.read_csv("bankNotes.csv")

	X = df[df.columns[0:4]].values
	y = df[df.columns[4]]

	# Encode the dependent variables
	encoder = LabelEncoder()
	encoder.fit(y)
	y = encoder.transform(y)
	Y = one_hot_encode(y)
	print(X.shape)
	return (X, Y)


# Define the one hot encoder function
def one_hot_encode(labels):
	n_labels = len(labels)
	n_unique_labels = len(np.unique(labels))
	one_hot_encode = np.zeros((n_labels, n_unique_labels))
	one_hot_encode[np.arange(n_labels), labels] = 1
	return one_hot_encode


# Read the data 
X, Y = read_dataset()

# Shuffle the dataset
X, Y = shuffle(X, Y, random_state = 12)

# Split the dataset into train and test
train_x, test_x, train_y, test_y = train_test_split(X, Y, test_size = 0.20, random_state = 99)

# Define all important parameters
learning_rate = 0.3	
epochs = 200 			# Number of Iterations
cost_history = np.empty(shape = [1], dtype = float)
n_dim = X.shape[1] 		#  Number of Columns in X.. the dataset.. or also be said as numbr of features
print("n_dim", n_dim)
n_class = 2				# Number of classes to be defined upon -> Real Note, Fake Note

# Define the path to where the model will be saved
model_path = "/Users/arjun/Documents/Machine Learning Works/5) Bank Note Authentication/BankNoteModel"

# Define the number of hidden layers and number of neurons in each layer
n_hidden_1 = 10



x = tf.placeholder(tf.float32, [None, n_dim])
W = tf.Variable(tf.zeros([n_dim, n_class]))
b = tf.Variable(tf.zeros([n_class]))
y_ = tf.placeholder(tf.float32, [None, n_class])


# Define the model
def multilayer_perceptron(x, weights, biases):

	# Hidden layer 1 with Sigmoid Activation Function
	layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
	layer_1 = tf.nn.sigmoid(layer_1)

	

	# Output layer with linear activation function
	out_layer = tf.matmul(layer_4, weights['out']) + biases['out']
	return out_layer


# Define weights and biases

weights = {
	'h1' : tf.Variable(tf.truncated_normal([n_dim, n_hidden_1])),
	
	'out' : tf.Variable(tf.truncated_normal([n_hidden_4, n_class]))
}

biases = {
	'b1' : tf.Variable(tf.truncated_normal([n_hidden_1])),
	
	'out' : tf.Variable(tf.truncated_normal([n_class]))
}


# Initialize all variables
init = tf.global_variables_initializer()

saver = tf.train.Saver()

# Call the model
y = multilayer_perceptron(x, weights, biases)

# Define the cost function and optimizer
cost_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = y, labels = y_)) # y_ is the actual output and y is the output generated by the model (Model Output)
training = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function)

sess = tf.Session()
sess.run(init)


# Calculate the cost and accuracy for each epoch

mse_history = []
accuracy_history = []

for i in range(epochs):
	sess.run(training, feed_dict = {x: train_x, y_: train_y})
	cost = sess.run(cost_function, feed_dict = {x: train_x, y_: train_y})
	cost_history = np.append(cost_history, cost)
	
	correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))

	accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

	pred_y = sess.run(y, feed_dict = {x: test_x})
	mse = tf.reduce_mean(tf.square(pred_y - test_y))
	mse_ = sess.run(mse)
	mse_history.append(mse_)

	accuracy = (sess.run(accuracy, feed_dict = {x: train_x, y_: train_y}))
	accuracy_history.append(accuracy)

	print("Epoch: ", i, " - ", " Cost: ", cost, " - MSE: ", mse_, " - Training Accuracy : ", accuracy)


save_path = saver.save(sess, model_path)
print("Model is saved in file : ", save_path)

# Plotting the accuracy graph
plt.plot(accuracy_history)
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.show()

# Print Final Accuracy
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Test Accuracy : ", sess.run(accuracy, feed_dict = {x: test_x, y_: test_y}))

# Print Mean Square Error
pred_y = sess.run(y, feed_dict = {x: test_x})
mse = tf.reduce_mean(tf.square(pred_y - test_y))
print("MSE : %.4f" % sess.run(mse))
