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

neural_networks.py 6.1 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
  1. import torch
  2. from torch import nn, optim
  3. from torch.nn import functional as F
  4. import numpy as np
  5. from tqdm import tqdm
  6. import torch.utils.data as data_utils
  7. from features import downsample
  8. import pickle as pkl
  9. import models
  10. class neural_net_sklearn():
  11. """
  12. sklearn wrapper for training a neural net
  13. """
  14. def __init__(self, D_in=40, H=40, p=17, epochs=1000, batch_size=100,
  15. lr=0.001,
  16. track_name='X_same_length_normalized', arch='fcnn', torch_seed=2):
  17. """
  18. Parameters:
  19. ==========================================================
  20. D_in, H, p: int
  21. same as input to FCNN
  22. epochs: int
  23. number of epochs
  24. batch_size: int
  25. batch size
  26. track_name: str
  27. column name of track (the tracks should be of the same length)
  28. """
  29. torch.manual_seed(torch_seed)
  30. self.D_in = D_in
  31. self.H = H
  32. self.p = p
  33. self.epochs = epochs
  34. self.batch_size = batch_size
  35. self.track_name = track_name
  36. self.torch_seed = torch_seed
  37. self.lr = lr
  38. self.arch = arch
  39. torch.manual_seed(self.torch_seed)
  40. if self.arch == 'fcnn':
  41. self.model = models.FCNN(self.D_in, self.H, self.p)
  42. elif 'lstm' in self.arch:
  43. self.model = models.LSTMNet(self.D_in, self.H, self.p)
  44. elif 'cnn' in self.arch:
  45. self.model = models.CNN(self.D_in, self.H, self.p)
  46. elif 'attention' in self.arch:
  47. self.model = models.AttentionNet(self.D_in, self.H, self.p)
  48. elif 'video' in self.arch:
  49. self.model = models.VideoNet()
  50. def fit(self, X, y, verbose=False, checkpoint_fname=None, device='cpu'):
  51. """
  52. Train model
  53. Parameters:
  54. ==========================================================
  55. X: pd.DataFrame
  56. input data, should contain tracks and additional covariates
  57. y: np.array
  58. input response
  59. """
  60. print('fit', X.shape, X.columns)
  61. torch.manual_seed(self.torch_seed)
  62. if self.arch == 'fcnn':
  63. self.model = models.FCNN(self.D_in, self.H, self.p)
  64. elif 'lstm' in self.arch:
  65. self.model = models.LSTMNet(self.D_in, self.H, self.p)
  66. elif 'cnn' in self.arch:
  67. self.model = models.CNN(self.D_in, self.H, self.p)
  68. elif 'attention' in self.arch:
  69. self.model = models.AttentionNet(self.D_in, self.H, self.p)
  70. elif 'video' in self.arch:
  71. self.model = models.VideoNet()
  72. # convert input dataframe to tensors
  73. X_track = X[self.track_name] # track
  74. X_track = torch.tensor(np.array(list(X_track.values)), dtype=torch.float)
  75. if len(X.columns) > 1: # covariates
  76. X_covariates = X[[c for c in X.columns if c != self.track_name]]
  77. X_covariates = torch.tensor(np.array(X_covariates).astype(float), dtype=torch.float)
  78. else:
  79. X_covariates = None
  80. # response
  81. y = torch.tensor(y.reshape(-1, 1), dtype=torch.float)
  82. # initialize optimizer
  83. optimizer = optim.Adam(self.model.parameters(), lr=self.lr)
  84. # initialize dataloader
  85. if X_covariates is not None:
  86. dataset = torch.utils.data.TensorDataset(X_track, X_covariates, y)
  87. else:
  88. dataset = torch.utils.data.TensorDataset(X_track, y)
  89. train_loader = torch.utils.data.DataLoader(dataset,
  90. batch_size=self.batch_size,
  91. shuffle=True)
  92. #train_loader = [(X1, X2, y)]
  93. # train fcnn
  94. print('fitting dnn...')
  95. self.model = self.model.to(device)
  96. for epoch in tqdm(range(self.epochs)):
  97. train_loss = 0
  98. for batch_idx, data in enumerate(train_loader):
  99. optimizer.zero_grad()
  100. # print('shapes input', data[0].shape, data[1].shape)
  101. if X_covariates is not None:
  102. preds = self.model(data[0].to(device), data[1].to(device))
  103. y = data[2].to(device)
  104. else:
  105. preds = self.model(data[0].to(device))
  106. y = data[1].to(device)
  107. loss_fn = torch.nn.MSELoss()
  108. loss = loss_fn(preds, y)
  109. loss.backward()
  110. train_loss += loss.item()
  111. optimizer.step()
  112. if verbose:
  113. print(f'Epoch: {epoch}, Average loss: {train_loss/len(X_track):.4e}')
  114. elif epoch % (self.epochs // 10) == 99:
  115. print(f'Epoch: {epoch}, Average loss: {train_loss/len(X_track):.4e}')
  116. if checkpoint_fname is not None:
  117. pkl.dump({'model_state_dict': self.model.state_dict()},
  118. open(checkpoint_fname, 'wb'))
  119. def predict(self, X_new):
  120. """
  121. make predictions with new data
  122. Parameters:
  123. ==========================================================
  124. X_new: pd.DataFrame
  125. input new data, should contain tracks and additional covariates
  126. """
  127. print('predict', X_new.columns, X_new.shape, self.track_name)
  128. self.model.eval()
  129. with torch.no_grad():
  130. # convert input dataframe to tensors
  131. X_new_track = X_new[self.track_name]
  132. X_new_track = torch.tensor(np.array(list(X_new_track.values)), dtype=torch.float)
  133. if len(X_new.columns) > 1:
  134. X_new_covariates = X_new[[c for c in X_new.columns if c != self.track_name]]
  135. X_new_covariates = torch.tensor(np.array(X_new_covariates).astype(float), dtype=torch.float)
  136. preds = self.model(X_new_track, X_new_covariates)
  137. else:
  138. preds = self.model(X_new_track)
  139. return preds.data.numpy().reshape(1, -1)[0]
Tip!

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

Comments

Loading...