svm_model_train.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. from sklearn.model_selection import train_test_split
  2. from sklearn.model_selection import GridSearchCV
  3. from sklearn.linear_model import LogisticRegression
  4. from sklearn.ensemble import RandomForestClassifier, VotingClassifier
  5. import sklearn.svm as svm
  6. from sklearn.utils import shuffle
  7. from sklearn.externals import joblib
  8. from sklearn.metrics import accuracy_score, f1_score
  9. from sklearn.model_selection import cross_val_score
  10. import numpy as np
  11. import pandas as pd
  12. import sys, os, getopt
  13. saved_models_folder = 'saved_models'
  14. current_dirpath = os.getcwd()
  15. output_model_folder = os.path.join(current_dirpath, saved_models_folder)
  16. def get_best_model(X_train, y_train):
  17. Cs = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
  18. gammas = [0.001, 0.01, 0.1, 1, 5, 10, 100]
  19. param_grid = {'kernel':['rbf'], 'C': Cs, 'gamma' : gammas}
  20. svc = svm.SVC(probability=True)
  21. clf = GridSearchCV(svc, param_grid, cv=10, scoring='accuracy', verbose=10)
  22. clf.fit(X_train, y_train)
  23. model = clf.best_estimator_
  24. return model
  25. def main():
  26. if len(sys.argv) <= 1:
  27. print('Run with default parameters...')
  28. print('python svm_model_train.py --data xxxx --output xxxx')
  29. sys.exit(2)
  30. try:
  31. opts, args = getopt.getopt(sys.argv[1:], "hd:o", ["help=", "data=", "output="])
  32. except getopt.GetoptError:
  33. # print help information and exit:
  34. print('python svm_model_train.py --data xxxx --output xxxx')
  35. sys.exit(2)
  36. for o, a in opts:
  37. if o == "-h":
  38. print('python svm_model_train.py --data xxxx --output xxxx')
  39. sys.exit()
  40. elif o in ("-d", "--data"):
  41. p_data_file = a
  42. elif o in ("-o", "--output"):
  43. p_output = a
  44. else:
  45. assert False, "unhandled option"
  46. if not os.path.exists(output_model_folder):
  47. os.makedirs(output_model_folder)
  48. ########################
  49. # 1. Get and prepare data
  50. ########################
  51. dataset_train = pd.read_csv(p_data_file + '.train', header=None, sep=";")
  52. dataset_test = pd.read_csv(p_data_file + '.test', header=None, sep=";")
  53. # default first shuffle of data
  54. dataset_train = shuffle(dataset_train)
  55. dataset_test = shuffle(dataset_test)
  56. # get dataset with equal number of classes occurences
  57. noisy_df_train = dataset_train[dataset_train.ix[:, 0] == 1]
  58. not_noisy_df_train = dataset_train[dataset_train.ix[:, 0] == 0]
  59. nb_noisy_train = len(noisy_df_train.index)
  60. noisy_df_test = dataset_test[dataset_test.ix[:, 0] == 1]
  61. not_noisy_df_test = dataset_test[dataset_test.ix[:, 0] == 0]
  62. nb_noisy_test = len(noisy_df_test.index)
  63. final_df_train = pd.concat([not_noisy_df_train[0:nb_noisy_train], noisy_df_train])
  64. final_df_test = pd.concat([not_noisy_df_test[0:nb_noisy_test], noisy_df_test])
  65. # shuffle data another time
  66. final_df_train = shuffle(final_df_train)
  67. final_df_test = shuffle(final_df_test)
  68. final_df_train_size = len(final_df_train.index)
  69. final_df_test_size = len(final_df_test.index)
  70. # use of the whole data set for training
  71. x_dataset_train = final_df_train.ix[:,1:]
  72. x_dataset_test = final_df_test.ix[:,1:]
  73. y_dataset_train = final_df_train.ix[:,0]
  74. y_dataset_test = final_df_test.ix[:,0]
  75. #######################
  76. # 2. Construction of the model : Ensemble model structure
  77. #######################
  78. svm_model = get_best_model(x_dataset_train, y_dataset_train)
  79. #######################
  80. # 3. Fit model : use of cross validation to fit model
  81. #######################
  82. print("-------------------------------------------")
  83. print("Train dataset size: ", final_df_train_size)
  84. svm_model.fit(x_dataset_train, y_dataset_train)
  85. val_scores = cross_val_score(svm_model, x_dataset_train, y_dataset_train, cv=5)
  86. print("Accuracy: %0.2f (+/- %0.2f)" % (val_scores.mean(), val_scores.std() * 2))
  87. ######################
  88. # 4. Test : Validation and test dataset from .test dataset
  89. ######################
  90. # we need to specify validation size to 20% of whole dataset
  91. val_set_size = int(final_df_train_size/3)
  92. test_set_size = val_set_size
  93. total_validation_size = val_set_size + test_set_size
  94. if final_df_test_size > total_validation_size:
  95. x_dataset_test = x_dataset_test[0:total_validation_size]
  96. y_dataset_test = y_dataset_test[0:total_validation_size]
  97. X_test, X_val, y_test, y_val = train_test_split(x_dataset_test, y_dataset_test, test_size=0.5, random_state=1)
  98. y_test_model = svm_model.predict(X_test)
  99. y_val_model = svm_model.predict(X_val)
  100. val_accuracy = accuracy_score(y_val, y_val_model)
  101. test_accuracy = accuracy_score(y_test, y_test_model)
  102. val_f1 = f1_score(y_val, y_val_model)
  103. test_f1 = f1_score(y_test, y_test_model)
  104. ###################
  105. # 5. Output : Print and write all information in csv
  106. ###################
  107. print("Validation dataset size ", val_set_size)
  108. print("Validation: ", val_accuracy)
  109. print("Validation F1: ", val_f1)
  110. print("Test dataset size ", test_set_size)
  111. print("Test: ", val_accuracy)
  112. print("Test F1: ", test_f1)
  113. ##################
  114. # 6. Save model : create path if not exists
  115. ##################
  116. # create path if not exists
  117. if not os.path.exists(saved_models_folder):
  118. os.makedirs(saved_models_folder)
  119. joblib.dump(svm_model, output_model_folder + '/' + p_output + '.joblib')
  120. if __name__== "__main__":
  121. main()