【问题标题】:Multi Layer Perceptron Deep Learning in Python using Pytorch使用 Pytorch 在 Python 中进行多层感知器深度学习
【发布时间】:2021-04-09 21:57:19
【问题描述】:

我在 MLP 中执行我的代码的 train 函数时出错。

这是错误:

mat1 和 mat2 形状不能相乘(128x10 和 48x10)

我的 train 函数代码是这样的:

class net(nn.Module):
def __init__(self, input_dim2, hidden_dim2, output_dim2):
    super(net, self).__init__()
    self.input_dim2 = input_dim2
    self.fc1 = nn.Linear(input_dim2, hidden_dim2)
    self.relu = nn.ReLU()
    self.fc2 = nn.Linear(hidden_dim2, hidden_dim2)
    self.fc3 = nn.Linear(hidden_dim2, output_dim2) 
def forward(self, x):
  x = self.fc1(x)
  x = self.relu(x)
  x = self.fc2(x)
  x = self.relu(x)
  x = self.fc3(x) 
  x = F.softmax(self.fc3(x)) 
  
  return x



model = net(input_dim2, hidden_dim2, output_dim2) #create the network
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.RMSprop(model.parameters(), lr = learning_rate2)


def train(num_epochs2):
for i in range(num_epochs2):
  tmp_loss = []
  for (x,y) in train_loader:
    print(y.shape)
    print(x.shape)
    outputs = model(x) #forward pass
    print(outputs.shape)
    loss = criterion(outputs, y) #loss computation
    tmp_loss.append(loss.item()) #recording the loss
    optimizer.zero_grad() #all the accumulated gradient
    loss.backward()  #auto-differentiaton - accumulation of gradient
    optimizer.step() # a gradient step

  print("Loss at {}th epoch: {}".format(i, np.mean(tmp_loss)))  

我不知道我错在哪里。我的代码似乎可以正常工作。

【问题讨论】:

  • 请添加整个错误信息

标签: python pytorch perceptron mlp


【解决方案1】:

从有限的消息来看,我猜你错的地方是以下sn-ps:

x = self.fc3(x) 
x = F.softmax(self.fc3(x))

尝试替换为:

x = self.fc3(x) 
x = F.softmax(x)

一个好的问题应该包括:错误回溯信息和可能重复错误的完整玩具示例!

【讨论】:

  • 嗨!这确实有效!谢谢!很抱歉这个问题。我会改进我提出问题的方式。谢谢!
【解决方案2】:

这里的“init”函数中似乎缺少relu 激活。或者在 forward 函数中有一个额外的relu 激活。查看下面的代码并尝试找出多余或缺少的内容。

def __init__(self, input_dim2, hidden_dim2, output_dim2):
    super(net, self).__init__()
    self.input_dim2 = input_dim2
    self.fc1 = nn.Linear(input_dim2, hidden_dim2)
    self.relu = nn.ReLU()
    self.fc2 = nn.Linear(hidden_dim2, hidden_dim2)
    self.fc3 = nn.Linear(hidden_dim2, output_dim2) 
def forward(self, x):
    x = self.fc1(x)
    x = self.relu(x)
    x = self.fc2(x)
    x = self.relu(x)
    x = self.fc3(x) 
    x = F.softmax(self.fc3(x)) 

return x

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2017-11-08
    • 2017-03-18
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2013-03-04
    相关资源
    最近更新 更多