models.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. # models imports
  2. import numpy as np
  3. from sklearn.model_selection import GridSearchCV
  4. from sklearn.linear_model import LogisticRegression
  5. from sklearn.ensemble import RandomForestClassifier, VotingClassifier
  6. from sklearn.neighbors import KNeighborsClassifier
  7. from sklearn.ensemble import GradientBoostingClassifier
  8. from sklearn.feature_selection import RFECV
  9. import sklearn.svm as svm
  10. from sklearn.metrics import accuracy_score
  11. from thundersvm import SVC
  12. from sklearn.model_selection import KFold, cross_val_score
  13. # variables and parameters
  14. n_predict = 0
  15. def my_accuracy_scorer(*args):
  16. global n_predict
  17. score = accuracy_score(*args)
  18. print('{0} - Score is {1}'.format(n_predict, score))
  19. n_predict += 1
  20. return score
  21. def _get_best_model(X_train, y_train):
  22. Cs = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
  23. gammas = [0.001, 0.01, 0.1, 5, 10, 100]
  24. param_grid = {'kernel':['rbf'], 'C': Cs, 'gamma' : gammas}
  25. svc = svm.SVC(probability=True, class_weight='balanced')
  26. clf = GridSearchCV(svc, param_grid, cv=5, verbose=1, scoring=my_accuracy_scorer, n_jobs=-1)
  27. clf.fit(X_train, y_train)
  28. model = clf.best_estimator_
  29. return model
  30. def svm_model(X_train, y_train):
  31. return _get_best_model(X_train, y_train)
  32. def _get_best_gpu_model(X_train, y_train):
  33. # Cs = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
  34. # gammas = [0.001, 0.01, 0.1, 5, 10, 100]
  35. # param_grid = {'kernel':['rbf'], 'C': Cs, 'gamma' : gammas}
  36. # svc = SVC(probability=True, class_weight='balanced')
  37. # clf = GridSearchCV(svc, param_grid, cv=5, verbose=1, scoring=my_accuracy_scorer, n_jobs=-1)
  38. # clf.fit(X_train, y_train)
  39. Cs = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
  40. gammas = [0.001, 0.01, 0.1, 5, 10, 100]
  41. bestModel = None
  42. bestScore = 0.
  43. n_eval = 1
  44. k_fold = KFold(n_splits=5)
  45. for c in Cs:
  46. for g in gammas:
  47. svc = SVC(probability=True, class_weight='balanced', kernel='rbf', gamma=g, C=c)
  48. svc.fit(X_train, y_train)
  49. score = cross_val_score(svc, X_train, y_train, cv=k_fold, n_jobs=-1)
  50. score = np.mean(score)
  51. # keep track of best model
  52. if score > bestScore:
  53. bestScore = score
  54. bestModel = svc
  55. print('Eval n° {} [C: {}, gamma: {}] => [score: {}, bestScore: {}]'.format(n_eval, c, g, score, bestScore))
  56. n_eval += 1
  57. return bestModel
  58. def svm_gpu(X_train, y_train):
  59. return _get_best_gpu_model(X_train, y_train)
  60. def ensemble_model(X_train, y_train):
  61. svm_model = _get_best_model(X_train, y_train)
  62. lr_model = LogisticRegression(solver='liblinear', multi_class='ovr', random_state=1)
  63. rf_model = RandomForestClassifier(n_estimators=100, random_state=1)
  64. ensemble_model = VotingClassifier(estimators=[
  65. ('svm', svm_model), ('lr', lr_model), ('rf', rf_model)], voting='soft', weights=[1,1,1])
  66. ensemble_model.fit(X_train, y_train)
  67. return ensemble_model
  68. def ensemble_model_v2(X_train, y_train):
  69. svm_model = _get_best_model(X_train, y_train)
  70. knc_model = KNeighborsClassifier(n_neighbors=2)
  71. gbc_model = GradientBoostingClassifier(n_estimators=100, learning_rate=1.0, max_depth=1, random_state=0)
  72. lr_model = LogisticRegression(solver='liblinear', multi_class='ovr', random_state=1)
  73. rf_model = RandomForestClassifier(n_estimators=100, random_state=1)
  74. ensemble_model = VotingClassifier(estimators=[
  75. ('lr', lr_model),
  76. ('knc', knc_model),
  77. ('gbc', gbc_model),
  78. ('svm', svm_model),
  79. ('rf', rf_model)],
  80. voting='soft', weights=[1, 1, 1, 1, 1])
  81. ensemble_model.fit(X_train, y_train)
  82. return ensemble_model
  83. def get_trained_model(choice, X_train, y_train):
  84. if choice == 'svm_model':
  85. return svm_model(X_train, y_train)
  86. if choice == 'svm_gpu':
  87. return svm_gpu(X_train, y_train)
  88. if choice == 'ensemble_model':
  89. return ensemble_model(X_train, y_train)
  90. if choice == 'ensemble_model_v2':
  91. return ensemble_model_v2(X_train, y_train)