prediction_scene.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. from sklearn.externals import joblib
  2. import numpy as np
  3. import pandas as pd
  4. from sklearn.metrics import accuracy_score
  5. from keras.models import Sequential
  6. from keras.layers import Conv1D, MaxPooling1D
  7. from keras.layers import Activation, Dropout, Flatten, Dense, BatchNormalization
  8. from keras import backend as K
  9. from keras.models import model_from_json
  10. from keras.wrappers.scikit_learn import KerasClassifier
  11. import sys, os, getopt
  12. import json
  13. from modules.utils import config as cfg
  14. output_model_folder = cfg.saved_models_folder
  15. def main():
  16. # TODO : use of argparse
  17. if len(sys.argv) <= 1:
  18. print('Run with default parameters...')
  19. print('python prediction_scene.py --data xxxx.csv --model xxxx.joblib --output xxxx --scene xxxx')
  20. sys.exit(2)
  21. try:
  22. opts, args = getopt.getopt(sys.argv[1:], "hd:o:s", ["help=", "data=", "model=", "output=", "scene="])
  23. except getopt.GetoptError:
  24. # print help information and exit:
  25. print('python prediction_scene.py --data xxxx.csv --model xxxx.joblib --output xxxx --scene xxxx')
  26. sys.exit(2)
  27. for o, a in opts:
  28. if o == "-h":
  29. print('python prediction_scene.py --data xxxx.csv --model xxxx.joblib --output xxxx --scene xxxx')
  30. sys.exit()
  31. elif o in ("-d", "--data"):
  32. p_data_file = a
  33. elif o in ("-m", "--model"):
  34. p_model_file = a
  35. elif o in ("-o", "--output"):
  36. p_output = a
  37. elif o in ("-s", "--scene"):
  38. p_scene = a
  39. else:
  40. assert False, "unhandled option"
  41. if '.joblib' in p_model_file:
  42. kind_model = 'sklearn'
  43. model_ext = '.joblib'
  44. if '.json' in p_model_file:
  45. kind_model = 'keras'
  46. model_ext = '.json'
  47. if not os.path.exists(output_model_folder):
  48. os.makedirs(output_model_folder)
  49. dataset = pd.read_csv(p_data_file, header=None, sep=";")
  50. y_dataset = dataset.ix[:,0]
  51. x_dataset = dataset.ix[:,1:]
  52. noisy_dataset = dataset[dataset.ix[:, 0] == 1]
  53. not_noisy_dataset = dataset[dataset.ix[:, 0] == 0]
  54. y_noisy_dataset = noisy_dataset.ix[:, 0]
  55. x_noisy_dataset = noisy_dataset.ix[:, 1:]
  56. y_not_noisy_dataset = not_noisy_dataset.ix[:, 0]
  57. x_not_noisy_dataset = not_noisy_dataset.ix[:, 1:]
  58. if kind_model == 'keras':
  59. with open(p_model_file, 'r') as f:
  60. json_model = json.load(f)
  61. model = model_from_json(json_model)
  62. model.load_weights(p_model_file.replace('.json', '.h5'))
  63. model.compile(loss='binary_crossentropy',
  64. optimizer='adam',
  65. metrics=['accuracy'])
  66. _, vector_size = np.array(x_dataset).shape
  67. # reshape all data
  68. x_dataset = np.array(x_dataset).reshape(len(x_dataset), vector_size, 1)
  69. x_noisy_dataset = np.array(x_noisy_dataset).reshape(len(x_noisy_dataset), vector_size, 1)
  70. x_not_noisy_dataset = np.array(x_not_noisy_dataset).reshape(len(x_not_noisy_dataset), vector_size, 1)
  71. if kind_model == 'sklearn':
  72. model = joblib.load(p_model_file)
  73. if kind_model == 'keras':
  74. y_pred = model.predict_classes(x_dataset)
  75. y_noisy_pred = model.predict_classes(x_noisy_dataset)
  76. y_not_noisy_pred = model.predict_classes(x_not_noisy_dataset)
  77. if kind_model == 'sklearn':
  78. y_pred = model.predict(x_dataset)
  79. y_noisy_pred = model.predict(x_noisy_dataset)
  80. y_not_noisy_pred = model.predict(x_not_noisy_dataset)
  81. accuracy_global = accuracy_score(y_dataset, y_pred)
  82. accuracy_noisy = accuracy_score(y_noisy_dataset, y_noisy_pred)
  83. accuracy_not_noisy = accuracy_score(y_not_noisy_dataset, y_not_noisy_pred)
  84. if(p_scene):
  85. print(p_scene + " | " + str(accuracy_global) + " | " + str(accuracy_noisy) + " | " + str(accuracy_not_noisy))
  86. else:
  87. print(str(accuracy_global) + " \t | " + str(accuracy_noisy) + " \t | " + str(accuracy_not_noisy))
  88. with open(p_output, 'w') as f:
  89. f.write("Global accuracy found %s " % str(accuracy_global))
  90. f.write("Noisy accuracy found %s " % str(accuracy_noisy))
  91. f.write("Not noisy accuracy found %s " % str(accuracy_not_noisy))
  92. for prediction in y_pred:
  93. f.write(str(prediction) + '\n')
  94. if __name__== "__main__":
  95. main()