ensemble_model_train.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. import numpy as np
  9. import pandas as pd
  10. from sklearn.metrics import accuracy_score
  11. import sys, os, getopt
  12. saved_models_folder = 'saved_models'
  13. current_dirpath = os.getcwd()
  14. output_model_folder = os.path.join(current_dirpath, saved_models_folder)
  15. def get_best_model(X_train, y_train):
  16. Cs = [0.001, 0.01, 0.1, 1, 10]
  17. gammas = [0.001, 0.01, 0.1, 1]
  18. param_grid = {'kernel':['rbf'], 'C': Cs, 'gamma' : gammas}
  19. parameters = {'kernel':['rbf'], 'C': np.arange(1, 20)}
  20. svc = svm.SVC(gamma="scale", probability=True)
  21. clf = GridSearchCV(svc, parameters, cv=5, 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 ensemble_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 ensemble_model_train.py --data xxxx --output xxxx')
  35. sys.exit(2)
  36. for o, a in opts:
  37. if o == "-h":
  38. print('python ensemble_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. # get and split data
  49. dataset = pd.read_csv(p_data_file, header=None, sep=";")
  50. # default first shuffle of data
  51. dataset = shuffle(dataset)
  52. # get dataset with equal number of classes occurences
  53. noisy_df = dataset[dataset.ix[:, 0] == 1]
  54. not_noisy_df = dataset[dataset.ix[:, 0] == 0]
  55. nb_noisy = len(noisy_df.index)
  56. final_df = pd.concat([not_noisy_df[0:nb_noisy], noisy_df])
  57. #final_df = pd.concat([not_noisy_df, noisy_df])
  58. # shuffle data another time
  59. final_df = shuffle(final_df)
  60. print(len(final_df.index))
  61. y_dataset = final_df.ix[:,0]
  62. x_dataset = final_df.ix[:,1:]
  63. # use of the whole data set for training
  64. X_train, X_test, y_train, y_test = train_test_split(x_dataset, y_dataset, test_size=0., random_state=42)
  65. svm_model = get_best_model(X_train, y_train)
  66. lr_model = LogisticRegression(solver='liblinear', multi_class='ovr', random_state=1)
  67. rf_model = RandomForestClassifier(n_estimators=100, random_state=1)
  68. ensemble_model = VotingClassifier(estimators=[
  69. ('svm', svm_model), ('lr', lr_model), ('rf', rf_model)],
  70. voting='soft', weights=[1,1,1])
  71. ensemble_model.fit(X_train, y_train)
  72. y_train_model = ensemble_model.predict(X_train)
  73. print("**Train :** " + str(accuracy_score(y_train, y_train_model)))
  74. #y_pred = ensemble_model.predict(X_test)
  75. #print("**Test :** " + str(accuracy_score(y_test, y_pred)))
  76. # create path if not exists
  77. if not os.path.exists(saved_models_folder):
  78. os.makedirs(saved_models_folder)
  79. joblib.dump(ensemble_model, output_model_folder + '/' + p_output + '.joblib')
  80. if __name__== "__main__":
  81. main()