| 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() |