Commit 9be20683c02b6d3a9b7b68d7bc32bdcdb22c5226

Authored by Brice COLOMBIER
1 parent 99f992dab3
Exists in master

Add PCA

Showing 1 changed file with 39 additions and 0 deletions

  1 +import numpy as np
  2 +from sklearn.decomposition import PCA
  3 +from sklearn.externals import joblib
  4 +
  5 +import argparse
  6 +import os
  7 +
  8 +def pca(traces_name, nb_components, save_model = False, load_model = False, model = "./model.pkl"):
  9 + print "Loading data"
  10 + traces = np.load(traces_name)
  11 +
  12 + dirname, filename = os.path.split(traces_name)
  13 + filename, extension = os.path.splitext(filename)
  14 +
  15 + if load_model:
  16 + print "Loading model"
  17 + model = joblib.load(model)
  18 + else:
  19 + print "Building PCA object"
  20 + pca = PCA(n_components=nb_components)
  21 + print "Fitting"
  22 + model = pca.fit(traces)
  23 + pca_traces = model.transform(traces)
  24 + np.save(os.path.join(dirname, "pca_"+str(nb_components)+"_"+filename)+'.npy', pca_traces)
  25 + if save_model:
  26 + joblib.dump(model, os.path.join(dirname, "model_"+str(nb_components)+"_"+filename)+'.pkl')
  27 +
  28 +if __name__ == "__main__":
  29 +
  30 + # Parsing arguments
  31 + parser = argparse.ArgumentParser(description='Preprocess traces')
  32 + parser.add_argument("traces_name", type=str)
  33 + parser.add_argument("-n", "--nb_components", type=int)
  34 + parser.add_argument("-s", "--save_model", action='store_true', default=False)
  35 + parser.add_argument("-l", "--load_model", action='store_true', default=False)
  36 + parser.add_argument("-m", "--model", type=str, default="./model.pkl")
  37 + args = parser.parse_args()
  38 +
  39 + pca(args.traces_name, args.nb_components, args.save_model, args.load_model, args.model)