Python Forum
Please help with AttributeError: 'Netz' object has no attribute 'conv'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Please help with AttributeError: 'Netz' object has no attribute 'conv'
#1
Can you please hepl me with this code:
import torch
import torch.nn as nn
import torch.nn.functional as f
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable

kwargs = {}
train_data = torch.utils.data.DataLoader(datasets.MNIST('data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])), batch_size=64, shuffle=True, **kwargs)
test_data = torch.utils.data.DataLoader(datasets.MNIST('data', train=False, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])), batch_size=64, shuffle=True, **kwargs)

class Netz(nn.Module):
    def __init__(self):
        super(Netz, self).__init__()
        self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conf_dropout = nn.Dropout2d()
        self.fc1 = nn.Linear(320, 60)
        self.fc2 = nn.Linear(60, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = f.max_pool2d(x, 2)
        x = f.relu(x)
        x = self.conv2(x)
        x = self.conv.dropout(x)
        x = f.max_pool2d(x, 2)
        x = f.relu(x)
        print(x.size())
        exit()

model = Netz()

optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.8)
def train(epoch):
    model.train()
    for batch_id, (data, target) in enumerate(train_data):
        data = Variable(data)
        target = Variable(target)
        optimizer.zero_grad()
        out = model(data)
        criterion = F.nll_loss
        loss = criterion(out, target)
        loss.backward()
        optimizer.step()
        print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch, batch_id * len(data), len(train_data.dataset),
                                                                       100. * batch_id / len(train_data), loss.data[0]))


for epoch in range(1, 30):
    train(epoch)
I'm getting these Errors:
Error:
Traceback (most recent call last): File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1741, in <module> main() File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1735, in main globals = debugger.run(setup['file'], None, None, is_module) File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1135, in run pydev_imports.execfile(file, globals, locals) # execute the script File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "/Users/***/PycharmProjects/Pytorch/venv/mnist.py", line 51, in <module> train(epoch) File "/Users/***/PycharmProjects/Pytorch/venv/mnist.py", line 41, in train out = model(data) File "/Users/***/PycharmProjects/Pytorch/venv/lib/python3.7/site-packages/torch/nn/modules/module.py", line 489, in __call__ result = self.forward(*input, **kwargs) File "/Users/***/PycharmProjects/Pytorch/venv/mnist.py", line 26, in forward x = self.conv.dropout(x) File "/Users/***/PycharmProjects/Pytorch/venv/lib/python3.7/site-packages/torch/nn/modules/module.py", line 535, in __getattr__ type(self).__name__, name)) AttributeError: 'Netz' object has no attribute 'conv'
Reply
#2
in the Netz.__init___() you define conv1 and conv2, not conv. and also conf_dropout

so I guess line 26 should be
x = self.conf_dropout(x)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thanks for your immediate help, buran

Now it works :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  error "list object has no attribute transpose()" usercat123 4 4,260 Jan-28-2022, 12:01 PM
Last Post: usercat123
  AttributeError: (“module 'pandas' has no attribute 'rolling_std'” Mariana136 4 7,604 Sep-23-2019, 12:56 PM
Last Post: Mariana136
  AttributeError: module 'numpy' has no attribute 'array aapurdel 7 45,555 May-29-2019, 02:48 AM
Last Post: heiner55
  Pandas to_csv in for loop AttributeError: 'tuple' object has no attribute 'to_csv' NSearch 9 16,877 Apr-22-2019, 05:05 PM
Last Post: Yoriz
  AttributeError: 'NoneType' object has no attribute 'all' synthex 2 5,280 Mar-07-2019, 11:11 AM
Last Post: synthex
  'list' object has no attribute 'reshape' SamSoftwareLtd 1 15,579 Nov-04-2018, 10:38 PM
Last Post: stullis
  AttributeError: Can't get attribute 'Individual' on <module 'deap.creator' DomClout 4 8,790 Jul-27-2018, 09:05 PM
Last Post: Vysero
  AttributeError: module 'mnist' has no attribute 'train_images' pythonbeginner 1 8,198 Jun-14-2018, 09:29 PM
Last Post: snippsat
  AttributeError: 'set' object has no attribute 'items hey_arnold 3 26,651 Apr-29-2018, 04:33 PM
Last Post: hey_arnold
  AttributeError: module 'plotly' has no attribute 'offline' charlesczc 8 17,108 Jan-21-2018, 08:34 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020