Creating NN with pytorch and assign weights and biases manually

parisa71: <p>Hi,<br>
I want to create a simple neural network using pytorch with one input neuron and two neurons in the hidden layer and one neuron in the output layer which activation function for the hidden layer and the output layer is f(x)=x^2 (we have 1 hidden layer). Take the number 5 as an input and the weights of the first layer are W1=0.06 and W2=2.03 and its bias is b1=1.87. The weights of the second layer are W3=0.06 and W4=2.03 and its bias is b2=3.29. The output should be 12.1002. I don’t want to train this NN. Can anyone guide me on this please?<br>
Thank you very much.</p>

ptrblck: <p>You can create the modules and assign the custom weight and bias values in a <code>with torch.no_grad()</code> context.</p>

parisa71: <p>Thank you for your reply.<br>
I read your post about setting the weights and biases manually but i can’t apply this in my network. Could you please write the code?</p>

ptrblck: <p>Could you post your model definition and the approach you’ve used so far so I could add the missing parts?</p>

parisa71: <h2><a name="i-had-generated-the-neural-network-with-custom-weights-biases-and-activation-function-in-python-before-and-i-wanted-to-calculate-the-value-of-the-nns-output-when-input-equals-5-now-i-want-to-do-same-procedure-in-pytorch-but-i-cant-write-the-code-this-is-my-python-code-which-i-generated-before-import-numpy-as-np-def-activation_funct-return-t2-num_hidden2-t-nparray-0-1-15-5-07-02-u-nparray0-13-155-105-115-9t-defining-weights-and-biases-b1-2-b2-3-hidden_weights-nparray02-03-output_weights-nparray15-25-hidden_layer-npdott-hidden_weights-hidden_layer_outputs-activation_funchidden_layer-b1-output_layer-npdothidden_layer_outputs-output_weights-u_hat-activation_funcoutput_layer-b2-printu_hat-1" class="anchor" href="#i-had-generated-the-neural-network-with-custom-weights-biases-and-activation-function-in-python-before-and-i-wanted-to-calculate-the-value-of-the-nns-output-when-input-equals-5-now-i-want-to-do-same-procedure-in-pytorch-but-i-cant-write-the-code-this-is-my-python-code-which-i-generated-before-import-numpy-as-np-def-activation_funct-return-t2-num_hidden2-t-nparray-0-1-15-5-07-02-u-nparray0-13-155-105-115-9t-defining-weights-and-biases-b1-2-b2-3-hidden_weights-nparray02-03-output_weights-nparray15-25-hidden_layer-npdott-hidden_weights-hidden_layer_outputs-activation_funchidden_layer-b1-output_layer-npdothidden_layer_outputs-output_weights-u_hat-activation_funcoutput_layer-b2-printu_hat-1"></a>I had generated the neural network with custom weights, biases and activation function in python before, and I wanted to calculate the value of the NN’s output when input equals 5.<br>
Now I want to do same procedure in pytorch but I can’t write the code.<br>
This is my python code which I generated before:<br>
import numpy as np<br>
def activation_func(t):<br>
return t**2<br>
num_hidden=2<br>
t = np.array([<br>
[0],<br>
[1],<br>
[1.5],<br>
[5],<br>
[0.7],<br>
[0.2],<br>
])<br>
u = np.array([[0, 13, 15.5, 10.5, 11.5, 9]]).T<br>
<span class="hashtag-raw">#defining</span> weights and biases<br>
b1 = 2<br>
b2 = 3<br>
hidden_weights = np.array([[0.2, 0.3]])<br>
output_weights = np.array([[1.5], [2.5]])<br>
hidden_layer = np.dot(t, hidden_weights)<br>
hidden_layer_outputs = activation_func(hidden_layer + b1)<br>
output_layer = np.dot(hidden_layer_outputs, output_weights)<br>
u_hat = activation_func(output_layer + b2)<br>
print(u_hat)</h2>
<p>and this is the pytorch code I tried to write it with your guidance in previous posts but I can’t change the activation functions and I don’t know how can I apply the hidden_weights and output_weights and biases to the network.<br>
import numpy as np<br>
import torch<br>
import torch.nn as nn<br>
X = np.array([<br>
[0],<br>
[1],<br>
[1.5],<br>
[5],<br>
[0.7],<br>
[0.2],<br>
])<br>
y = np.array([[0, 13, 15.5, 10.5, 11.5, 9]]).T</p>
<p>X = torch.tensor(X, dtype=torch.float32)<br>
y = torch.tensor(y, dtype=torch.float32)</p>
<p>class PimaClassifier(nn.Module):<br>
def <strong>init</strong>(self):<br>
super().<strong>init</strong>()<br>
self.hidden1 = nn.Linear(1, 2)<br>
self.act1 = nn.ReLU()<br>
self.output = nn.Linear(2, 1)<br>
self.act_output = nn.Sigmoid()</p>
<pre><code>def forward(self, x):
    x = self.act1(self.hidden1(x))
    x = self.act_output(self.output(x))
    return x
</code></pre>
<p>model = PimaClassifier()<br>
hidden_weights = np.array([[0.2, 0.3]])<br>
output_weights = np.array([[1.5], [2.5]])<br>
bias = np.array([2., 3.])<br>
with torch.no_grad():<br>
model.weight = nn.Parameter(torch.from_numpy(hidden_weights).float())<br>
model.weight = nn.Parameter(torch.from_numpy(output_weights).float())</p>
<p>print(model(X)[3])</p>

parisa71: <p>Hi. I want to create a neural network with 1 neuron in input layer, 2 neurons in hidden layer<br>
and 1 neuron in output layer, the activation function for both hidden and output layer is<br>
f(x)=x**2. the weights and bias of hidden layer are [0.2, 0.3] and 2 respectively.<br>
the weights and bias of output layer are [1.5, 2.5] and 3 respectively. I want to calculate<br>
the output of the neural network with input value of 5. it should be obtain 2220.765625.<br>
I wrote this code but I can’t obtain true answer.<br>
could you please correct this code? I don’t want to train the network.</p>
<p>import torch<br>
import torch.nn as nn</p>
<p>input_size = 1</p>
<p>class NeuralNet(nn.Module):<br>
def <strong>init</strong>(self):<br>
super(NeuralNet, self).<strong>init</strong>()</p>
<pre><code>    self.fc1 = nn.Linear(in_features=input_size, out_features=2)
    self.output = nn.Linear(in_features=2, out_features=1)

    self.weights_initialization()

def forward(self, x):        
    out = self.fc1(x)       
    out = out ** 2          
    output = self.output(out)            
    return output**2  

def weights_initialization(self):
    with torch.no_grad():
        self.fc1.weight.copy_(torch.tensor([[0.2, 0.3]], requires_grad=False))
        self.fc1.bias.copy_(torch.tensor([2], requires_grad=False))  
        self.output.weight.copy_(torch.tensor([[1.5, 2.5]], requires_grad=False))
        self.output.bias.copy_(torch.tensor([3], requires_grad=False))  
</code></pre>
<p>net = NeuralNet()<br>
input_data = torch.rand(5, input_size)<br>
output = net(input_data)<br>
print(output)</p>

ptrblck: <aside class="quote no-group" data-username="parisa71" data-post="6" data-topic="194362">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/parisa71/48/77195_2.png" class="avatar"> parisa71:</div>
<blockquote>
<p>I want to calculate<br>
the output of the neural network with input value of 5. it should be obtain 2220.765625.</p>
</blockquote>
</aside>
<p>You are creating 5 random values in your current code as the input to your model while it seems you want to pass 5 as the actual value to it.</p>

parisa71: <p>You are right but I don’t know how to implement 5 as input in neural network.</p>

ptrblck: <p><code>x = torch.tensor([[5.]])</code> should work.</p>

parisa71: <p>thank you for your answer. i tried it but code doesn’t work. i received this error.<br>
could you please check my code?<br>
in weights_initialization<br>
self.fc1.weight.copy_(torch.tensor([[0.2, 0.3]], requires_grad=False))<br>
RuntimeError: output with shape [2, 1] doesn’t match the broadcast shape [2, 2]</p>

J_Johnson: <aside class="quote no-group" data-username="parisa71" data-post="10" data-topic="194362">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/parisa71/48/77195_2.png" class="avatar"> parisa71:</div>
<blockquote>
<p>self.fc1.weight.copy_(torch.tensor([[0.2, 0.3]], requires_grad=False))</p>
</blockquote>
</aside>
<p>Change to:</p>
<pre><code class="lang-auto">self.fc1.weight.copy_(torch.tensor([[0.2], [0.3]], requires_grad=False))
</code></pre>

parisa71: <p>Thank you for your help, but it doesn’t work. The problem is due to output shape.<br>
The output shape should be 1<em>1 but I don’t know why its shape becomes 1</em>2.<br>
This is the error:<br>
RuntimeError: output with shape [1, 2] doesn’t match the broadcast shape [2, 2]</p>

J_Johnson: <aside class="quote no-group" data-username="parisa71" data-post="6" data-topic="194362">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/parisa71/48/77195_2.png" class="avatar"> parisa71:</div>
<blockquote>
<p><code>self.fc1.bias.copy_(torch.tensor([2], requires_grad=False))</code></p>
</blockquote>
</aside>
<p>Might be your fc1.bias only has 1 value and should have 2.</p>
<p>Anyways, it has something to do with how you’re setting the parameters. Before setting them, make sure you have the right shapes by printing their sizes out and again after you set them.</p>
<pre><code class="lang-auto">for param in model.parameters():
    print(param.size())
</code></pre>

parisa71: <p>Thank you very much. I will try it.</p>