簡體   English   中英

如何修復 UnboundLocalError:賦值前引用的局部變量“o1”

[英]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_outconv2 它們還沒有被定義:

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM