train_model.py 5.0 KB

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