This repository was archived by the owner on Feb 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_regression.py
More file actions
49 lines (40 loc) · 1.45 KB
/
basic_regression.py
File metadata and controls
49 lines (40 loc) · 1.45 KB
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
import matplotlib.pyplot as plt
from layers import *
from models import *
from optimizers import *
if __name__ == '__main__':
random_seed = 10
np.random.seed(random_seed)
# Define the network
input_size, hidden_size, output_size = 1, 100, 1
model = Model(loss='mse')
layer1 = Dense(input_size, hidden_size, activation='relu', initializer='xavier', regularization=1e-3)
model.add_layer(layer1)
layer2 = Dense(hidden_size, output_size, activation='linear', initializer='xavier', regularization=1e-3)
model.add_layer(layer2)
optim = SGD(lr=0.01)
model.add_optim(optim)
# Training
for i in range(100000):
# Generate training data
x_pts = np.random.rand(1000, 1) * 10
y_pts = np.sin(x_pts)
# Training the network and observing the loss
loss, _ = model.train(x_pts, y_pts)
if i % 10000 == 0:
print(f"Iteration {i}: loss {loss}")
model.set_eval()
# Generate test data
x_pts = np.linspace(0, 10, 1000)[:, np.newaxis]
y_pts = np.sin(x_pts)
# Calculate predictions
prediction = model(x_pts)
# Plotting true values and prediction
x_pts, y_pts, prediction = np.squeeze(x_pts), np.squeeze(y_pts), np.squeeze(prediction)
fig, ax = plt.subplots()
ax.plot(x_pts, y_pts)
ax.plot(x_pts, prediction)
ax.set(xlabel='x', ylabel='true_val', title='sin(x)')
ax.grid()
plt.show()
#fig.savefig('results/basic_regression_result.png')