Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

python - How to make R2 score in nn.LSTM pytorch

I tried to make loss function with R2in nn.LSTM but i couldnt find any documentation about it . I already use RMSE and MAE loss from pytorch.

My data is a time series and im doing time series forecasting

This is the code where i use the loss function of RMSE in data training

model = LSTM_model(input_size=1, output_size=1, hidden_size=512, num_layers=2, dropout=0).to(device)
criterion = nn.MSELoss(reduction="sum")
optimizer = optim.Adam(model.parameters(), lr=0.001)
callback = Callback(model, early_stop_patience=10 ,outdir="model/lstm", plot_every=20,)


from tqdm.auto import tqdm

def loop_fn(mode, dataset, dataloader, model, criterion, optimizer,device):
    if mode =="train":
        model.train()
    elif mode =="test":
        model.eval()
    cost = 0
    for feature, target in tqdm(dataloader, desc=mode.title()):
        feature, target = feature.to(device), target.to(device)
        output , hidden = model(feature,None)
        loss = torch.sqrt(criterion(output,target))
        
        if mode =="train":
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
        
        cost += loss.item() * feature.shape[0]
    cost = cost / len(dataset)
    return cost

And this is the code to start data training

while True :
    train_cost = loop_fn("train", train_set, trainloader, model, criterion, optimizer,device)
    with torch.no_grad():
        test_cost  = loop_fn("test", test_set, testloader, model, criterion, optimizer,device)
        
    callback.log(train_cost, test_cost)
    
    callback.save_checkpoint()
    
    callback.cost_runtime_plotting()
   
    
    if callback.early_stopping(model, monitor="test_cost"):
        callback.plot_cost()
        break

Can anyone help me with the R2 loss function ? Thank you in advance

question from:https://stackoverflow.com/questions/65840698/how-to-make-r2-score-in-nn-lstm-pytorch

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...