WHy does the following code not work as a square approximator? I am getting weird dimensions. When I tried plotting loss, the graph somehow does not show anything. I am a beginner with pytorch, so I would be grateful for any help.
JavaScript
x
46
46
1
import torch
2
from torch import nn
3
import matplotlib.pyplot as plt
4
import numpy as np
5
6
data = [[i] for i in range(-10000, 10000)]
7
y = [[i[0] * i[0]] for i in data]
8
data=torch.FloatTensor(data)
9
y=torch.FloatTensor(y)
10
11
12
class MyModel(nn.Module):
13
def __init__(self, numfeatures, outfeatures):
14
super().__init__()
15
self.modele = nn.Sequential(
16
nn.Linear( numfeatures, 2*numfeatures),
17
nn.ReLU(),
18
nn.Linear(2 * numfeatures, 4 * numfeatures),
19
nn.ReLU(),
20
nn.Linear(4* numfeatures, 2 * numfeatures),
21
nn.ReLU(),
22
nn.Linear(2*numfeatures, numfeatures),
23
)
24
def forward(self, x):
25
return self.modele(x)
26
27
28
model = MyModel(1, 1)
29
criterion = nn.MSELoss()
30
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
31
32
n_epochs = 10000
33
epoch_loss= []
34
35
for i in range(n_epochs):
36
y_pred = model(data)
37
loss = criterion(y_pred, y)
38
optimizer.zero_grad()
39
loss.backward()
40
optimizer.step()
41
epoch_loss.append(loss.item())
42
43
44
45
plt.plot(epoch_loss)
46
Advertisement
Answer
Your data is ranging from -10000
to 10000
! You need to standardize your data, otherwise you won’t be able to make your model learn:
JavaScript
1
3
1
data = (data - data.min()) / (data.max() - data.min())
2
y = (y - y.min()) / (y.max() - y.min())
3
Additionally, you could normalize your input with:
JavaScript
1
3
1
mean, std = data.mean(), data.std()
2
data = (data - mean) / std
3
After 100 epochs: