Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simple Neural Network Using Pytorch

I want to build Simple Neural Network with pytorch.
And I want to teach this network.

the network has
y = w(weight) * x + b(bias)
with w = 3 and b = 0

so I have the data
x = [1,2,3,4,5,6]
y = [3,6,9,12,15,18]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I have some problem while building this Simple Neural Network

import torch
import torch.nn as nn

class MyNeuralNetwork(nn.Module):
    def __init__(self):
        super(MyNeuralNetwork, self).__init__()
        self.layer=nn.Linear(in_features=1, out_features=1, bias=True)
        
        weight = torch.rand(1)
        bias = torch.rand(1)
        self.layer.weight = nn.Parameter(weight)
        self.layer.bias = nn.Parameter(bias)
    
    def forward(self, input):
        output = self.layer(input)
        return output
    
model = MyNeuralNetwork().to("cpu")
print(model)

print(f"weight : {model.layer.weight}")
print(f"bias : {model.layer.bias}")

input = torch.tensor([1.]).view(-1,1)
model(input)
# out = model(input)
# print(out)
# y = torch.tensor([3.,6.,9.,12.,15.,18.])

I have an error which says that
"RuntimeError: mat2 must be a matrix, got 1-D tensor"

What should I do to fix this problem?
Thanks OTL….

>Solution :

your weight should be of size [1, 1] which you have overrided with a 1d weight tensor. I do not know why you have overwrite the weight and bias of the layer, but either override with correct shape or if you just remove the 4 lines inside the init should work.or change but this:

self.layer.weight  = nn.Parameter(torch.rand(1, 1)) # 2d Matrix
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading