import torch
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output
1234)
torch.manual_seed(
# DANE
= torch.linspace(0,10,500).view(-1,1)
x = torch.sin(x)
y = y + 0.1*(torch.rand(500).view(-1,1)-0.5)
y
=(8,4))
plt.figure(figsize-1,1), color="tab:grey", alpha=0.6, label="sin(x)")
plt.plot(x, torch.sin(x).view(="dane treningowe")
plt.scatter(x,y, label'x')
plt.xlabel('y')
plt.ylabel(
plt.legend() plt.show()
Trenowanie sieci neuronowej PyTorch
klasyczna sieć neuronowa
class SinusEstimator(torch.nn.Module):
def __init__(self, N_INPUT: int, N_OUTPUT: int):
super(SinusEstimator,self).__init__()
self.layers = torch.nn.Sequential(
64),
torch.nn.Linear(N_INPUT,
torch.nn.ReLU(),64,32),
torch.nn.Linear(
torch.nn.ReLU(),32,16),
torch.nn.Linear(
torch.nn.Tanh(),16,N_OUTPUT)
torch.nn.Linear(
)
def forward(self, x):
= self.layers(x)
x return x
= SinusEstimator(1,1)
model
=0.001
learning_rate= torch.optim.Adam(model.parameters(), lr=learning_rate)
optimiser = torch.nn.MSELoss()
criterion
= []
losses
def callback(model, loss):
losses.append(loss.item())
=True)
clear_output(wait= model(x).detach()
prediction =(6,2.5))
plt.figure(figsize0].detach(), torch.sin(x)[:,0].detach(), label="Exact solution", color="tab:grey", alpha=0.6)
plt.plot(x[:,0].detach(), prediction[:,0], label="Classical solution", color="tab:green")
plt.plot(x[:,f"Training step {len(losses)}")
plt.title(
plt.legend()
plt.show()
=(6,2.5))
plt.figure(figsize'Lossfn Visualised')
plt.title(
plt.plot(losses)
plt.show()
def train(X,Y, model, optimiser, epochs, lossfn, callback = None):
for epoch in range(epochs):
model.train()= model(X)
prediction = lossfn(prediction, Y)
loss
optimiser.zero_grad()
loss.backward()
optimiser.step()eval()
model.if callback != None:
callback(model, loss)
= x.requires_grad_(True)
x_train
300, criterion, callback) train(x_train, y, model, optimiser,
Sprawdź czy modyfikacja funkcji straty pomoze polepszyć wynik
def mse(y, y_pred) -> torch.Tensor:
return torch.mean((y-y_pred)**2)
def special_loss_fn(y, y_pred) -> torch.Tensor:
return mse(y, y_pred) + torch.mean((y_pred - torch.sin(x))**2)
= SinusEstimator(1,1)
model2
=0.001
learning_rate= torch.optim.Adam(model2.parameters(), lr=learning_rate)
optimiser = torch.nn.MSELoss()
criterion = []
losses
200, special_loss_fn, callback) train(x_train, y, model2, optimiser,