antitheft159 commited on
Commit
a56af1c
·
verified ·
1 Parent(s): cbd828f

Create Real-Time Data

Browse files
Files changed (1) hide show
  1. Real-Time Data +80 -0
Real-Time Data ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+
5
+ class RealTimeModel(nn.Module):
6
+ def __init__(self, input_size, hidden_size, output_size):
7
+ super(RealTimeModel, self).__init__()
8
+ self.fc1 = nn.Linear(input_size, hidden_size)
9
+ self.relu = nn.ReLU()
10
+ self.fc2 = nn.Linear(hidden_size, output_size)
11
+
12
+ def forward(self, x):
13
+ x = self.fc1(x)
14
+ x = self.relu(x)
15
+ x = self.fc2(x)
16
+ return x
17
+
18
+ model = RealTimeModel(input_size=10, hidden_size=20, output_size=1)
19
+ criterion = nn.MSELoss()
20
+ optimizer = optim.SGD(model.parameters(), lr=0.01)
21
+
22
+ import numpy as np
23
+ import time
24
+
25
+ def get_new_data():
26
+ return torch.tensor(np.random.rand(10), dtype=torch.float32)
27
+
28
+ def real_time_update():
29
+ while True:
30
+ new_data = get_new_data().unsqueeze(0)
31
+ target = torch.tensor([0.5], dtype=torch.float32)
32
+
33
+ output = model(new_data)
34
+ loss = criterion(output, target)
35
+
36
+ optimizer.zero_grad()
37
+ loss.backward()
38
+ optimzier.step()
39
+
40
+ print(f"Real-Time Update - Loss: {loss.item():.4f}")
41
+ time.sleep(1)
42
+
43
+ import matplotlib.pyplot as plt
44
+
45
+ def visualize_loss(loss_values):
46
+ plt.plot(loss_values)
47
+ plt.xlabel("Time")
48
+ plt.ylabel("Loss")
49
+ plt.show()
50
+
51
+ import numpy as np
52
+ import matplotlib.pyplot as plt
53
+ import torch
54
+ import time
55
+
56
+ def get_new_data():
57
+ return torch.sin(torch.linspace(0,2 * np.p, 100) + time.time()).numpy()
58
+
59
+ plt.ion()
60
+ fig, ax = plt.subplots()
61
+ x_data = np.linspace(0, 2 * np.pi, 100)
62
+ y_data = get_new_data()
63
+ line, = ax.plot(x_data, y_data)
64
+
65
+ def real_time_plot():
66
+ while True:
67
+ new_y_data = get_new_data()
68
+ line.set_ydata(new_y_data)
69
+ fig.canvas.draw()
70
+ fig.canvas.flush_events()
71
+
72
+ time.sleep(0.1)
73
+
74
+ try:
75
+ real_time_plot()
76
+ except KeyboardInterrupt:
77
+ print("Real-time plotting stopped.")
78
+ finally:
79
+ plt.ioff()
80
+ plt.show()