Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train_model.py 2.5 KB

You have to be logged in to leave a comment. Sign In
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
  1. """
  2. Train classification model for MNIST
  3. """
  4. import json
  5. import pickle
  6. import numpy as np
  7. import time
  8. # New imports
  9. import torch
  10. import torch.utils.data
  11. import torch.nn.functional as F
  12. import torch.optim as optim
  13. from my_torch_model import Net
  14. # New function
  15. def train(model, device, train_loader, optimizer, epoch):
  16. log_interval = 100
  17. model.train()
  18. for batch_idx, (data, target) in enumerate(train_loader):
  19. data, target = data.to(device), target.to(device)
  20. optimizer.zero_grad()
  21. output = model(data)
  22. loss = F.nll_loss(output, target)
  23. loss.backward()
  24. optimizer.step()
  25. if batch_idx % log_interval == 0:
  26. print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
  27. epoch, batch_idx * len(data), len(train_loader.dataset),
  28. 100. * batch_idx / len(train_loader), loss.item()))
  29. def train_model():
  30. # Measure training time
  31. start_time = time.time()
  32. # Setting up network
  33. print("Setting up Params...")
  34. device = torch.device("cpu")
  35. batch_size = 64
  36. epochs = 3
  37. learning_rate = 0.01
  38. momentum = 0.5
  39. print("done.")
  40. # Load training data
  41. print("Load training data...")
  42. train_data = np.load('./data/processed_train_data.npy')
  43. # Divide loaded data-set into data and labels
  44. labels = torch.Tensor(train_data[:, 0]).long()
  45. data = torch.Tensor(train_data[:, 1:].reshape([train_data.shape[0], 1, 28, 28]))
  46. torch_train_data = torch.utils.data.TensorDataset(data, labels)
  47. train_loader = torch.utils.data.DataLoader(torch_train_data,
  48. batch_size=batch_size,
  49. shuffle=True)
  50. print("done.")
  51. # Define SVM classifier and train model
  52. print("Training model...")
  53. model = Net().to(device)
  54. optimizer = optim.SGD(model.parameters(),
  55. lr=learning_rate,
  56. momentum=momentum)
  57. for epoch in range(1, epochs + 1):
  58. train(model, device, train_loader, optimizer, epoch)
  59. print("done.")
  60. # Save model as pkl
  61. print("Save model and training time metric...")
  62. with open("./data/model.pkl", 'wb') as f:
  63. pickle.dump(model, f)
  64. # End training time measurement
  65. end_time = time.time()
  66. # Create metric for model training time
  67. with open('./metrics/train_metric.json', 'w') as f:
  68. json.dump({'training_time': end_time - start_time}, f)
  69. print("done.")
  70. if __name__ == '__main__':
  71. train_model()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...