0

Is there a way to train a model based on time?
Say I have the following code to train a model:

import torch
import torch.nn as nn
import torch.optim as optim

class net_x(nn.Module): 
        def __init__(self):
            super(net_x, self).__init__()
            self.fc1=nn.Linear(2, 20) 
            self.fc2=nn.Linear(20, 20)
            self.out=nn.Linear(20, 4) 

        def forward(self, x):
            x=self.fc1(x)
            x=self.fc2(x)
            x=self.out(x)
            return x

nx = net_x()


r = torch.tensor([1.0,2.0])
optimizer = optim.Adam(nx.parameters(), lr = 0.1)
scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=1e-2, max_lr=0.1, step_size_up=1, mode="triangular2", cycle_momentum=False)

for epoch in range(100):
    optimizer.zero_grad()
    net_predictions = nx(r)
    loss = torch.sum(torch.randint(0,10,(4,)) - net_predictions)
    loss.backward()
    optimizer.step()
    scheduler.step()
    print('loss:' , loss)

Instead of having 100 epochs, can I somehow change it to be for 1 hour of training?

Penguin
  • 1,923
  • 3
  • 21
  • 51
  • 4
    Does this answer your question? [Break the function after certain time](https://stackoverflow.com/questions/25027122/break-the-function-after-certain-time) – Alexander L. Hayes Apr 16 '21 at 16:50
  • 1
    Yes! I think that would work. I'm working on changing the training loop to incorporate that, and will write an answer soon after I'll see that it works correctly (there were several suggestions in that link) – Penguin Apr 17 '21 at 15:04

0 Answers0