python - Pythorch 错误 - UnboundLocalError:分配前引用了局部变量“out”
问题描述
我正在尝试使用 Pytorch 编写人工神经网络。我正在使用 MNIST 数据集。我是 Pytorch 的新手。我无法解决错误。我猜错在这里“ outfc1lrelu = self.lrelu(out) ”
代码:
import torch
import torch.nn as nn
from sklearn.datasets import load_breast_cancer
device = torch.device("cpu")
#Hyper Parameter
input_size = 30
hidden_size = 500
num_classes = 2
num_epoch = 100
learning_rate = 1e-8
girdi, cikti = load_breast_cancer(return_X_y=True)
train_input = torch.from_numpy(girdi).float()
train_output = torch.from_numpy(cikti)
class NeuralNet(nn.Module): #sinir agı torch u ımport etmıs oldu
def __init__(self,input_size,hidden_size,num_classes):
super(NeuralNet,self).__init__()
self.fc1 = nn.Linear(input_size,hidden_size)
self.lrelu = nn.LeakyReLU(negative_slope=0.02)
self.fc2 = nn.Linear(hidden_size,num_classes)
def forward(self,input):
outfc1 = self.fc1(input)
outfc1lrelu = self.lrelu(out)
out = self.fc2(outfc1lrelu)
return out
model = NeuralNet(input_size,hidden_size,num_classes)
lossf = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
for epoch in range(num_epoch):
outputs=model(train_input)
loss=lossf(outputs,train_output)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch + 1,num_epoch,loss.item()))
错误部分:
UnboundLocalError Traceback (most recent call last)
<ipython-input-105-70765d74f98b> in <module>
1 for epoch in range(num_epoch): #100 tekrar yapcaz
----> 2 outputs = model(train_input) #çıktı olarak il cıktıyı versın
3 loss = lossf(outputs,train_output) #kaybı hesapladıkçoutputsu ardından traın outputsu alsın
4
5 optimizer.zero_grad() #0 a esıtledık
~\anaconda3\envs\pytorchTutorial\lib\site-packages\torch\nn\modules\module.py in _call_impl(self, *input, **kwargs)
870 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
871 or _global_forward_hooks or _global_forward_pre_hooks):
--> 872 return forward_call(*input, **kwargs)
873 # Do not call functions when jit is used
874 full_backward_hooks, non_full_backward_hooks = [], []
<ipython-input-101-58455cd48d9f> in forward(self, input)
8 def forward(self,input):
9 outfc1 = self.fc1(input) #girdi degerımızı alıcaz
---> 10 outfc1lrelu = self.lrelu(out) #ilk katman fc1 girdi ardından lrelu gırdı cıktı olarak(out) belli bir deger geldı
11 out = self.fc2(outfc1lrelu) #1 mı sıfır mı tahmın etsın
12 return out
UnboundLocalError: local variable 'out' referenced before assignment
为什么我会犯这个错误?哪里出错了?如果您能提供帮助,我会很高兴。
解决方案
推荐阅读
- javascript - 在我的 nodejs 应用程序中有两个单独的模式
- c# - 将日期时间转换为日期时间?(零合并?)
- r - 有什么方法可以替换 r 中的 for 循环
- python - 如何修改我当前的二叉搜索树以创建一棵空树?
- python - Pandas 以奇怪的格式返回数据(Int64、Float64)
- ruby-on-rails - 如何在使用 jQuery Datepicker 在 Ruby on Rails 应用程序中发送到服务器之前将时间转换为 UTC
- angular - 在角度材料中选择所有子复选框时,不选中标题复选框
- css - 图像的 Ionic/Angular CSS 问题
- sql-server - 基于日期创建表 SQL
- c# - 如何在 Xamarin Forms 的 Flex Button 控件模板中处理“单击”事件?