# -*- coding: utf-8 -*-
"""ml.ipynb

Automatically generated by Colaboratory.

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

def ML(X, Y, size=0.25, *args):

  """
  This function is used to train different machine learning algorithm such as LogisticRegesstion, DecisionTree, Random Forest, svm etc..
  and prints its metrics.

  Parameters:
  X - input data
  Y - output vector
  size - validation or testing data percentage
  args - ml algorithms

  Returns:
  returns trained ml algorithms
  """


  from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
  from sklearn.model_selection import train_test_split
  import pandas as pd
  import numpy
##creating a function to handle classification algorithms
  print('____________________________________________________')
  print(".....................Py-AutoML......................") 
  #print(args)  
  if  not args:
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.neighbors import KNeighborsClassifier
    from sklearn.linear_model import LogisticRegression
    from sklearn.svm import SVC

    args = (SVC(), RandomForestClassifier(), DecisionTreeClassifier(), KNeighborsClassifier(), LogisticRegression(max_iter = 7000))






  # dropping rows containing missing values
  X = pd.DataFrame(X)
  X.dropna(inplace= True, axis = 0)

  Y = pd.DataFrame(Y)
  Y.dropna(inplace= True, axis = 0)

  ##splitting the data into training and testing data and setting the test_size
  X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=size, random_state = 0)   

  ##training the model with train data
  acc_score = []
  for alg in args:
      alg.fit(X_train, y_train.values.ravel())
      prediction = alg.predict(X_test)

      ##outputing statistics on the performance of the individual models
      ##statistics printed out are the accuracy score, confusion matrix and clasification report
      
      print('____________________________________________________')
      print(alg.__class__.__name__,"______________________________","\n")
      print("Accuracy Score for "+ alg.__class__.__name__+" is \n"+ str(accuracy_score(y_test, prediction)))
      print('\n')

      print("Confusion Matrix for "+ alg.__class__.__name__+" is \n"+ str(confusion_matrix(y_test, prediction)))
      print('\n')

      print("Classification Report for "+ alg.__class__.__name__+" is \n"+ str(classification_report(y_test, prediction)))
      print('\n')


      ##saving the accuracy scores of the individual models as variables
      accuracy = str(accuracy_score(y_test, prediction))

      ##making a list of individual models and their accuracy scores
      acc_score.append([alg.__class__.__name__, accuracy])

  ##creating a dataframe of every individual model and accuracy score 
  df = pd.DataFrame(acc_score, columns=['Model', 'Accuracy'])
  ##outputing the created dataframe 
  print(df)

  #return args

        ##creating another function for handling the categorial encoding of data 


def EncodeCategorical(Y): ##defining the argument the function takes
    from sklearn.preprocessing import LabelEncoder ##importing the needed library to handle data encoding
    le = LabelEncoder() ## assigning the encoder function to a variable
    return le.fit_transform(Y) ##returning the transformed encoded data 


def ml(X, Y, size=0.25, *args):
  return ML(X, Y, size=0.25, *args)