英文:
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]
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....
英文:
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]
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....
答案1
得分: 1
你的权重应该是大小为[1, 1],但你已经用一个一维权重张量进行了覆盖。我不知道为什么你要覆盖层的权重和偏差,但要么用正确的形状进行覆盖,要么如果你只是删除__init__中的4行代码应该可以工作,或者修改成这样:
self.layer.weight = nn.Parameter(torch.rand(1, 1)) # 2维矩阵
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论