File size: 1,853 Bytes
a56af1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torch.nn as nn
import torch.optim as optim

class RealTimeModel(nn.Module):
  def __init__(self, input_size, hidden_size, output_size):
    super(RealTimeModel, self).__init__()
    self.fc1 = nn.Linear(input_size, hidden_size)
    self.relu = nn.ReLU()
    self.fc2 = nn.Linear(hidden_size, output_size)

  def forward(self, x):
    x = self.fc1(x)
    x = self.relu(x)
    x = self.fc2(x)
    return x

  model = RealTimeModel(input_size=10, hidden_size=20, output_size=1)
  criterion = nn.MSELoss()
  optimizer = optim.SGD(model.parameters(), lr=0.01)

  import numpy as np
  import time

  def get_new_data():
    return torch.tensor(np.random.rand(10), dtype=torch.float32)

  def real_time_update():
    while True:
      new_data = get_new_data().unsqueeze(0)
      target = torch.tensor([0.5], dtype=torch.float32)

      output = model(new_data)
      loss = criterion(output, target)

      optimizer.zero_grad()
      loss.backward()
      optimzier.step()

      print(f"Real-Time Update - Loss: {loss.item():.4f}")
      time.sleep(1)

import matplotlib.pyplot as plt

def visualize_loss(loss_values):
  plt.plot(loss_values)
  plt.xlabel("Time")
  plt.ylabel("Loss")
  plt.show()

import numpy as np
import matplotlib.pyplot as plt
import torch
import time

def get_new_data():
  return torch.sin(torch.linspace(0,2 * np.p, 100) + time.time()).numpy()

  plt.ion()
  fig, ax = plt.subplots()
  x_data = np.linspace(0, 2 * np.pi, 100)
  y_data = get_new_data()
  line, = ax.plot(x_data, y_data)

  def real_time_plot():
    while True:
      new_y_data = get_new_data()
      line.set_ydata(new_y_data)
      fig.canvas.draw()
      fig.canvas.flush_events()

      time.sleep(0.1)

  try:
    real_time_plot()
  except KeyboardInterrupt:
    print("Real-time plotting stopped.")
  finally:
    plt.ioff()
    plt.show()