class Detector(DetectorBase): def __init__(self, key, seq_length=10): super(Detector, self).__init__(key, seq_length) self.key = str(key) self.packet_length = 1500 self.mini_batch = 30 self.epochs = 50 self.train_buffer = [] self.exec_buffer = [] self.set_buffer = [] self.max_round = inf self.train_round = 0 self.model = Autoencoder(self.packet_length, seq_length, self.epochs) self.clf = OneClassSVM(kernel='rbf', gamma=0.1, nu=0.05) self.model_path = os.path.join('model_{}'.format(seq_length), self.key) self.stats_path = os.path.join('stats_{}'.format(seq_length), self.key + '.pkl') self.eval_path = os.path.join('evaluation_{}'.format(seq_length), self.key + '.csv') self.loss_path = os.path.join('evaluation_{}'.format(seq_length), self.key + '_loss.csv') if self.model.exist(self.model_path): print('Using existing model: {}'.format(self.key)) self.model.load(self.model_path) if os.path.exists(self.stats_path): print('Using existing stats') self.clf = joblib.load(self.stats_path) def update_buffer(self, seq, mode, info=None): seq = deepcopy(seq) if mode == 'T' and self.train_round <= self.max_round: self.train_buffer.append(seq) if len(self.train_buffer) == self.mini_batch: random.shuffle(self.train_buffer) X = np.array(self.train_buffer) self.train(X) self.train_buffer = [] self.train_round += 1 elif mode == 'E': self.exec_buffer.append(seq) if len(self.exec_buffer) == 1: X = np.array(self.exec_buffer) self.execute(X, info) self.exec_buffer = [] else: X = np.array(seq) X = X.reshape((1, X.shape[0], X.shape[1])) self.eval(X) def train(self, X): if self.train_round < self.max_round: history = self.model.fit(X) with open(self.loss_path, 'a') as f_loss: writer_loss = csv.writer(f_loss) if self.train_round == 0: writer_loss.writerow([history.history['loss'][0]]) writer_loss.writerow([history.history['loss'][-1]]) print('Detector {} saved'.format(self.key)) def eval(self, X): Y = self.model.predict(X) mse = mean_squared_error(X[0], Y[0]) print('Calculating mse of {}: {}'.format(self.key, mse)) self.set_buffer.append(mse) def set_threshold(self): self.clf = OneClassSVM(kernel='rbf', gamma=0.1, nu=0.05) self.clf.fit(np.array(self.set_buffer).reshape(-1, 1)) joblib.dump(self.clf, self.stats_path) def execute(self, X, info=None): start = time.time() Y = self.model.predict(X) dur = time.time() - start with open(self.eval_path, 'a') as f: writer = csv.writer(f) for x, y in zip(X, Y): mse = mean_squared_error(x, y) print('Execute on {}: {}'.format(self.key, mse)) label = self.clf.predict(np.array(mse).reshape(-1, 1)) result = 'Normal' if label == 1 else 'Malicious' if info: writer.writerow([str(mse), result, str(info)]) else: writer.writerow([str(mse), result]) def wrap_up(self, mode): if mode == 'T': self.model.save(self.model_path) elif mode == 'S': self.set_threshold()
model = model.build() print(model.summary()) model.load_weights(args.weights) model.compile(optimizer="adam", loss="MSE", metrics=["accuracy"]) # Generate time stamp for unique id of the result time_stamp = "{date:%Y-%m-%d-%H-%M-%S}".format(date=datetime.datetime.now()) # Pass images to network for file, i in zip(files, range(len(files))): inp_img = cv2.imread(file) / 255 inp_img = np.expand_dims(inp_img, axis=0) out_img = model.predict(inp_img) inp_img = np.squeeze(inp_img, axis=0) out_img = np.squeeze(out_img, axis=0) # Find bounding box of foreign object res = find_foreign_object(inp_img, out_img) inp_img = cv2.cvtColor((inp_img * 255).astype(np.uint8), cv2.COLOR_BGR2RGB) res = cv2.cvtColor(res, cv2.COLOR_BGR2RGB) f = plt.figure() f.add_subplot(1, 2 , 1) plt.imshow(inp_img) f.add_subplot(1, 2 , 2) plt.imshow(res)