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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import optuna from torch import optim, nn
''' # 这个定义的model只是个示例,实际并没什么用 class model(nn.Module):
def __init__(self, input_size, output_size, hidden_size=200, dropout=p): super(model, self).__init__() self.embedding = nn.Embedding(num_embeddings=input_size, embedding_dim=hidden_size) self.linear = nn.Linear(in_features=hidden_size, out_features=output_size) self.dropout = nn.Dropout(dropout) def forward(self, x): x = self.dropout(self.embedding(x)) outputs = self.linear(x) return outputs '''
def define_model(trial): hidden_size = trial.suggest_int('hidden_size', 100, 200) p = trial.suggest_uniform('dropout', 0.2, 0.5) m = model(input_size=vocab_size, output_size=output_size, hidden_size=hiddensize, dropout=p) return m
def objective(trial): optimizer_name = trial.suggest_categorical('optimizer', ['Adam', 'RMSprop', 'SGD']) lr = trial.suggest_uniform('lr', 1e-5, 1e-1) m = define_model(trial) optimizer = getattr(optim, optimizer_name)(m.parameters(), lr=lr) acc = run(m, optimizer=optimizer) return acc
if __name__ == '__main__': study = optuna.create_study(direction='maximize') study.optimize(objective, n_trials=100, n_jobs=-1) print('Number of finished trials: ', len(study.trials)) print('Best trial:') trial = study.best_trial print(' Value: ', trial.value) print(' Params: ') for key, value in trial.params.items(): print(' {}: {}'.format(key, value))
|