Advertisement
AlexanderDM

za chto

Dec 4th, 2022
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. def base_execution1(model: object, X_train: t.Tensor, X_test: t.Tensor, y_train: t.Tensor, y_test: t.Tensor) -> list:
  2.    
  3.     optimizer = t.optim.Adam(model.parameters(), lr=1e-3)
  4.  
  5.     loss = nn.MSELoss(reduction='mean')
  6.  
  7.     num_epochs = 1000
  8.     b_size = 30
  9.    
  10.     train_data = DataLoader(TensorDataset(X_train, y_train), batch_size=b_size, shuffle=True)
  11.    
  12.     train_losses = []
  13.     test_losses = []
  14.    
  15.     for epoch in range(num_epochs):
  16.        
  17.         total_train_loss = 0
  18.         total_test_loss = 0
  19.    
  20.         for X_train, y_train in train_data:
  21.            
  22.             optimizer.zero_grad()
  23.        
  24.             preds = model.forward(X_train).flatten()
  25.        
  26.             loss_train = loss(preds, y_train)
  27.             total_train_loss += math.sqrt(loss_train.item())
  28.  
  29.             loss_train.backward()
  30.        
  31.             optimizer.step()
  32.        
  33.         if epoch % 5 == 0:
  34.            
  35.             model.eval()
  36.             test_preds = model.forward(X_test)
  37.             loss_test = loss(test_preds, y_test)
  38.             total_test_loss += math.sqrt(loss_test.item())
  39.            
  40.         train_losses.append(total_train_loss)
  41.         test_losses.append(total_test_loss)
  42.        
  43.     plt.plot(train_losses)
  44.     plt.show()
  45.        
  46.     return train_losses, test_losses
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement