File size: 3,042 Bytes
25e7dcb |
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
from typing import Type
import numpy as np
import optuna
import torch
from torch import nn
from utils import tts_last_n
from .early_stopping import EarlyStopping
from .loaders import get_dataloader
from .train_eval import train_model, validate_model, predict
from sklearn.metrics import roc_auc_score
import math
def objective_tune_reg_a(trial: optuna.Trial,
model_class: Type[nn.Module],
inputs: np.ndarray,
targets: np.ndarray
) -> float:
criterion = nn.MSELoss()
hidden_size = trial.suggest_categorical('hidden_size', [4, 8, 16, 32, 64, 128])
num_layers = trial.suggest_int('num_layers', 1, 4)
dropout = trial.suggest_float('dropout', 0.05, 0.5, log=True)
learning_rate = trial.suggest_float('learning_rate', 1e-4, 1e-1, log=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model_class(
input_size=inputs.shape[2],
hidden_size=hidden_size,
num_layers=num_layers,
dropout=dropout,
output_size=1
)
train_seq, test_seq, train_tar, test_tar = tts_last_n(inputs, targets, 252)
tloader = get_dataloader(train_seq, train_tar, device)
vloader = get_dataloader(test_seq, test_tar, device)
train_model(
model=model,
criterion=criterion,
train_loader=tloader,
val_loader=vloader,
early_stopping=EarlyStopping(5, 1e-6),
epochs=100,
lr=learning_rate,
verbose=0
)
return math.sqrt(validate_model(model, vloader, criterion, device))
def objective_tune_clas_a(trial: optuna.Trial,
model_class: Type[nn.Module],
inputs: np.ndarray,
targets: np.ndarray
) -> float:
criterion = nn.BCELoss()
hidden_size = trial.suggest_categorical('hidden_size', [4, 8, 16, 32, 64, 128])
num_layers = trial.suggest_int('num_layers', 1, 4)
dropout = trial.suggest_float('dropout', 0.05, 0.5, log=True)
learning_rate = trial.suggest_float('learning_rate', 1e-4, 1e-1, log=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model_class(
input_size=inputs.shape[2],
hidden_size=hidden_size,
num_layers=num_layers,
dropout=dropout,
output_size=1
)
train_seq, test_seq, train_tar, test_tar = tts_last_n(inputs, targets, 252)
tloader = get_dataloader(train_seq, train_tar, device)
vloader = get_dataloader(test_seq, test_tar, device)
train_model(
model=model,
criterion=criterion,
train_loader=tloader,
val_loader=vloader,
early_stopping=EarlyStopping(5, 1e-6),
epochs=100,
lr=learning_rate,
verbose=0
)
labels, preds = predict(model, vloader, device)
return roc_auc_score(labels, preds) |