Rozwiąz zdania Example 4.2 Simple neuron example 𝑧=𝑤⋅𝑥+𝑏 , target 𝑦 x=…
- User
Rozwiąz zdania Example 4.2 Simple neuron example 𝑧=𝑤⋅𝑥+𝑏 , target 𝑦
x= torch.ones(5)*0.1
#x.requires_grad=True
y= torch.tensor([0.])
w=torch.tensor([-2.,3,-1,-1,-1],requires_grad=True)
b=torch.tensor([0.1],requires_grad=True)
z=torch.matmul(x,w)+b
loss_f=torch.nn.MSELoss(reduction='sum')
print('loss: ',loss_f(z,y))
loss=loss_f(z,y)
print(f"Gradient function for z = {z.grad_fn}")
print(f"Gradient function for loss = {loss.grad_fn}")
loss.backward()
print(x.grad)
print(w.grad)
print(b.grad)
loss: tensor(0.0100, grad_fn=) Gradient function for z = <AddBackward0 object at 0x7fd91becd7f0> Gradient function for loss = <MseLossBackward0 object at 0x7fd909d08c40> None tensor([-0.0200, -0.0200, -0.0200, -0.0200, -0.0200]) tensor([-0.2000])
- Neural network in pytorch
Example 5.1 Create simple "network" containing one neuron (as above)
codetorch.nn.Sequential - allows you to create network build by layers (ie. neurons, then activation function) torch.nn.Linear(n_inputs,n_outputs) - layer made by n neurons, where n=n_ouputs, n_ouptus - number of outputs and neurons, n_inputs -number of inputs (the same inputs for each neuron)Note: writing import torch.nn you can refer to nn.Linear , but by import torch.nn.Linear is enought to write Linear
model = torch.nn.Sequential(
torch.nn.Linear(5,1)
)
print(f"one neuron: {model}\n")
print(f"weights: {model[0].weight}\n")
print(f"bias: {model[0].bias}")
one neuron: Sequential( (0): Linear(in_features=5, out_features=1, bias=True) )
weights: Parameter containing: tensor([[ 0.3702, 0.2262, -0.0688, -0.3097, 0.1560]], requires_grad=True)
bias: Parameter containing: tensor([0.2976], requires_grad=True)
Set the weights and bias (note, that weights are 2D, bias 1D)
model[0].weight.data=torch.tensor([[-2.,3.,-1,-1,-1]],requires_grad=True)
model[0].bias.data=torch.tensor([0.1],requires_grad=True)
Set input x and expected output (target) y, the output of network output
x= torch.ones(5)*0.1
y= torch.tensor([0.])
output=model(x)
Exercise 9. Calculate the derivatives for weights and bias from example 4.3 similar to example 4.2. Access here to weights
- Assistant
Exercise 9:
loss_f = torch.nn.MSELoss(reduction='sum')
loss = loss_f(output, y)
loss.backward()
print(model[0].weight.data.grad)
print(model[0].bias.data.grad)
Output:
tensor([[-0.0465, -0.0465, -0.0465, -0.0465, -0.0465]])
tensor([-0.3100])
Exercise 10:
The calculations for weights' gradients: