[英]How to fix "UnboundLocalError: local variable 'books' referenced before assignment"?
[英]How to fix UnboundLocalError: local variable 'o1' referenced before assignment
我正在制作一个二元分类器并遇到了这个问题。
代码:
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class BinCNN(nn.Module):
def __init__(self, n, i, j, i1, j1, d, fc1, fc2):
super().__init__()
"""
n - source frame number of channels
i - 1-st kernel_size height
j - 1-st kernel_size width
i1 - 2-nd kernel_size height
j1 - 2-nd kernel_size width
d - dropout rate
fc1 - 1-st Linear layer size
fc2 - 2-nd Linear layer size
"""
self.conv1 = nn.Conv2d(n, o1, kernel_size=[i, j])
self.conv2 = nn.Conv2d(o1, o2, kernel_size=[i1, j1])
o1 = self._get_conv1_out(n)
o2 = self._get_conv2_out(o1)
self.drop = nn.Dropout(d)
self.fcl1 = nn.Linear(fc1, fc2)
self.fcl2 = nn.Linear(fc2, 2)
def _get_conv1_out(self, shape):
o = self.conv1(torch.zeros(1, *shape))
return int(np.prod(o.size()))
def _get_conv2_out(self, shape):
o = self.conv2(torch.zeros(1, *shape))
return int(np.prod(o.size()))
当我写
sd = BinCNN(3, 2, 2, 1, 1, 0.3, 300, 150)
print(sd)
这给了我给定的错误:
Traceback (most recent call last):
File "/home/name/Документы/work/science/train/train.py", line 46, in <module>
sd = BinCNN(3, 2, 2, 1, 1, 0.3, 300, 150)
File "/home/name/Документы/work/science/train/train.py", line 21, in __init__
self.conv1 = nn.Conv2d(n, o1, kernel_size=[i, j])
UnboundLocalError: local variable 'o1' referenced before assignment
我试图通过在self.conv1
之前添加model
来修复它,但它没有帮助
我用谷歌搜索了这个但一无所获。 请帮帮我
(我删除def forward (self, x)
因为 stackoverflow 发誓“有很多代码”)
在分别定义conv1
和_get_conv2_out
之前,您正在调用_get_conv1_out
和conv2
。 它们还没有被定义:
o1 = self._get_conv1_out(n)
o2 = self._get_conv2_out(o1)
self.conv1 = nn.Conv2d(n, o1, kernel_size=[i, j])
self.conv2 = nn.Conv2d(o1, o2, kernel_size=[i1, j1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.