train_model.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # main imports
  2. import numpy as np
  3. import pandas as pd
  4. import sys, os, argparse
  5. # models imports
  6. from sklearn.model_selection import train_test_split
  7. from sklearn.model_selection import GridSearchCV
  8. from sklearn.linear_model import LogisticRegression
  9. from sklearn.ensemble import RandomForestClassifier, VotingClassifier
  10. import joblib
  11. import sklearn.svm as svm
  12. from sklearn.utils import shuffle
  13. from sklearn.metrics import accuracy_score, f1_score
  14. from sklearn.model_selection import cross_val_score
  15. # modules and config imports
  16. sys.path.insert(0, '') # trick to enable import of main folder module
  17. import custom_config as cfg
  18. import models as mdl
  19. # variables and parameters
  20. saved_models_folder = cfg.saved_models_folder
  21. models_list = cfg.models_names_list
  22. current_dirpath = os.getcwd()
  23. output_model_folder = os.path.join(current_dirpath, saved_models_folder)
  24. def main():
  25. parser = argparse.ArgumentParser(description="Train SKLearn model and save it into .joblib file")
  26. parser.add_argument('--data', type=str, help='dataset filename prefix (without .train and .test)')
  27. parser.add_argument('--output', type=str, help='output file name desired for model (without .joblib extension)')
  28. parser.add_argument('--choice', type=str, help='model choice from list of choices', choices=models_list)
  29. args = parser.parse_args()
  30. p_data_file = args.data
  31. p_output = args.output
  32. p_choice = args.choice
  33. if not os.path.exists(output_model_folder):
  34. os.makedirs(output_model_folder)
  35. ########################
  36. # 1. Get and prepare data
  37. ########################
  38. dataset_train = pd.read_csv(p_data_file + '.train', header=None, sep=";")
  39. dataset_test = pd.read_csv(p_data_file + '.test', header=None, sep=";")
  40. # default first shuffle of data
  41. dataset_train = shuffle(dataset_train)
  42. dataset_test = shuffle(dataset_test)
  43. # get dataset with equal number of classes occurences
  44. noisy_df_train = dataset_train[dataset_train.iloc[:, 0] == 1]
  45. not_noisy_df_train = dataset_train[dataset_train.iloc[:, 0] == 0]
  46. nb_noisy_train = len(noisy_df_train.index)
  47. noisy_df_test = dataset_test[dataset_test.iloc[:, 0] == 1]
  48. not_noisy_df_test = dataset_test[dataset_test.iloc[:, 0] == 0]
  49. nb_noisy_test = len(noisy_df_test.index)
  50. final_df_train = pd.concat([not_noisy_df_train[0:nb_noisy_train], noisy_df_train])
  51. final_df_test = pd.concat([not_noisy_df_test[0:nb_noisy_test], noisy_df_test])
  52. # shuffle data another time
  53. final_df_train = shuffle(final_df_train)
  54. final_df_test = shuffle(final_df_test)
  55. final_df_train_size = len(final_df_train.index)
  56. final_df_test_size = len(final_df_test.index)
  57. # use of the whole data set for training
  58. x_dataset_train = final_df_train.iloc[:,1:]
  59. x_dataset_test = final_df_test.iloc[:,1:]
  60. y_dataset_train = final_df_train.iloc[:,0]
  61. y_dataset_test = final_df_test.iloc[:,0]
  62. #######################
  63. # 2. Construction of the model : Ensemble model structure
  64. #######################
  65. print("-------------------------------------------")
  66. print("Train dataset size: ", final_df_train_size)
  67. model = mdl.get_trained_model(p_choice, x_dataset_train, y_dataset_train)
  68. #######################
  69. # 3. Fit model : use of cross validation to fit model
  70. #######################
  71. val_scores = cross_val_score(model, x_dataset_train, y_dataset_train, cv=5)
  72. print("Accuracy: %0.2f (+/- %0.2f)" % (val_scores.mean(), val_scores.std() * 2))
  73. ######################
  74. # 4. Test : Validation and test dataset from .test dataset
  75. ######################
  76. # we need to specify validation size to 20% of whole dataset
  77. val_set_size = int(final_df_train_size/3)
  78. test_set_size = val_set_size
  79. total_validation_size = val_set_size + test_set_size
  80. if final_df_test_size > total_validation_size:
  81. x_dataset_test = x_dataset_test[0:total_validation_size]
  82. y_dataset_test = y_dataset_test[0:total_validation_size]
  83. X_test, X_val, y_test, y_val = train_test_split(x_dataset_test, y_dataset_test, test_size=0.5, random_state=1)
  84. y_test_model = model.predict(X_test)
  85. y_val_model = model.predict(X_val)
  86. val_accuracy = accuracy_score(y_val, y_val_model)
  87. test_accuracy = accuracy_score(y_test, y_test_model)
  88. val_f1 = f1_score(y_val, y_val_model)
  89. test_f1 = f1_score(y_test, y_test_model)
  90. ###################
  91. # 5. Output : Print and write all information in csv
  92. ###################
  93. print("Validation dataset size ", val_set_size)
  94. print("Validation: ", val_accuracy)
  95. print("Validation F1: ", val_f1)
  96. print("Test dataset size ", test_set_size)
  97. print("Test: ", val_accuracy)
  98. print("Test F1: ", test_f1)
  99. ##################
  100. # 6. Save model : create path if not exists
  101. ##################
  102. if not os.path.exists(saved_models_folder):
  103. os.makedirs(saved_models_folder)
  104. joblib.dump(model, output_model_folder + '/' + p_output + '.joblib')
  105. if __name__== "__main__":
  106. main()