-
Notifications
You must be signed in to change notification settings - Fork 0
/
lin_reg.py
63 lines (41 loc) · 1.47 KB
/
lin_reg.py
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
import torch
import torch.nn as nn
from torch.autograd import Variable
from utils.funcs import *
from utils.dicts import *
class LinReg(nn.Module):
"""
Linear Regression Class
"""
def __init__(self, input_dim,
criterion=LossDict.mse, optimizer=OptimizerDict.sgd,
learning_rate=0.01):
# calling the super class
super(LinReg, self).__init__()
# initializing the linear layer
self.linear_layer = nn.Linear(input_dim, 1)
# creating optimizer and criterion
self.optimizer, self.criterion = self.__compile(criterion, optimizer, learning_rate)
def __compile(self, criterion, optimizer, learning_rate):
optimizer = get_pytorch_optimizer(optimizer, self.parameters(), learning_rate)
criterion = get_pytorch_criterion(criterion)
return optimizer, criterion
def forward(self, X):
y = self.linear_layer(X)
return y
def fit(self, X, y):
# resetting gradients w.r.t. weights
self.optimizer.zero_grad()
# passing input forward to get outputs
y_ = self.forward(X)
# calculating loss + getting gradients
loss = self.criterion(y_, y)
loss.backward()
# updating weights
self.optimizer.step()
# calculating training accuracy
return loss.item()
def predict(self, X):
# passing input forward to get outputs
y_ = self.forward(X)
return y_