自定义侧信道攻击中的网格搜索超参数方法
在侧信道攻击中使用的超参搜索方法均为for循环,最近在训练AE时发现sklearn有现成的greph方法来完成网格调参,但是自带的方法自由度较低,且在判定超参好坏时并没有考虑到侧信道攻击并不主要以acc来判定模型的攻击效率,这里引入sklearn中的ParameterGrid
方法来完成自定义构造。
Python: 3.8.16 Sklearn==1.0.2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| def monkey_search(data, params, model, callbacks, key, shuffle=True, pred_size=5000, verbose=1): assert type(callbacks) == list train_data, test_data = data['train_data'], data['test_data'] idx = None for i, callback in enumerate(callbacks): if callback.__class__.__name__ == 'OneCycleLR': idx = i
candidatas = ParameterGrid(param_grid=params) for index, candidata in enumerate(candidatas): x_train, x_val, y_train, y_val = train_test_split(train_data[0], train_data[1], test_size=0.2, shuffle=True) if(shuffle == True) else train_test_split(train_data[0], train_data[1], test_size=0.2) optimizer = candidata['optimizer'] learning_rate = candidata['learning_rate'] epoch = candidata['epoch'] batch_size = candidata['batch_size'] loss = candidata['loss'] if idx != None: callbacks[idx].num_samples = x_train.shape[0] callbacks[idx].batch_size = batch_size callbacks[idx].max_lr = learning_rate model.compile(optimizer=optimizer, loss=loss, metrics=['acc']) model.optimizer.learning_rate.assign(learning_rate) model.fit(x_train, y_train, validation_data=(x_val, y_val), callbacks=callbacks, epochs=epoch, batch_size=batch_size)
ranks = np.zeros((10, pred_size)) for i in range(ranks.shape[0]): ranks[i] = mean_rank_score(model, test_data, pred_size=pred_size, key=key) if verbose == 1: show_result(ranks, optimizer, learning_rate, epoch, batch_size, loss)
|
该方法接收参数格式如下:
data:{"train_data": [x_train, y_train], "test_data": [x_test, y_test]}
params:{"optmizer": [string], "learning_rate:"[int],"epoch":[int],"batch_size":[int], "loss":[string] }
callbacks:{callback_function}
key: test_key int
model: model object
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| def mean_rank_score(model, test_data, pred_size, key): attack_traces, targets = test_data[0], test_data[1] predictions = model.predict(attack_traces, verbose=0) predictions = np.log(predictions + 1e-40) rank_times = np.zeros(pred_size) pred = np.zeros(256) idx = np.random.randint(predictions.shape[0], size=pred_size) for i, p in enumerate(idx): for k in range(pred.shape[0]): pred[k] += predictions[p, targets[p, k]] ranked = np.argsort(pred)[::-1] rank_times[i] = list(ranked).index(key) return rank_times
|
1 2 3 4 5 6 7
| def show_result(rank_times, optmizier, learning_rate, epoch, batch_size, loss): fig, ax = plt.subplots(figsize=(15, 7)) plt.title("optmizer:" + str(optmizier) + '_' + str(learning_rate) + '_epoch:' + str(epoch) + '_batch' + str(batch_size) + '_loss: '+ str(loss)) x = [x for x in range(0, 5000)] ax.plot(x, np.mean(rank_times, axis=0), 'b') ax.set(xlabel="number of traces", ylabel="mean rank") plt.show()
|
完整代码在:https://github.com/i4mhmh/A-custom-gridSearch-method-in-SCA