AttributeError Occurs After Creating a Simple Autoencoder in Python 3

Asked 2 years ago, Updated 2 years ago, 92 views

When I created AutoEncoder in the Chainer and made them learn,
The following error occurred:

Traceback (most recent call last):
  File "MNIST_autoenc.py", line 30, in <module>
    y=model(xs[batch:batch+128])
  File"/usr/local/lib/python 3.7/site-packages/chainer/link.py", line 293, in__call__
    forward=self.forward# type —ignore
AttributeError: 'AutoEncoder' object has no attribute' forward'

The code is as follows.
Please let me know if there are any corrections.

import chainer
import chain.links as L
import chain.functions as F
import numpy as np

class AutoEncoder (chain.Chain):
    def__init__(self):
        super(AutoEncoder,self).__init__(
            l0 = L. Linear (784,256),
            l1 = L. Linear (256,784) 
        )

        def__call__(self, x):
            h0 = F.relu(self.l0(x))
            h1 = F.sigmoid(self.l1(h0))
            return 5

train, test=chainer.datasets.get_mnist(ndim=1)
xs,ts=train._datasets
txs, tts = test._datasets

model = AutoEncoder()
model.to_cpu()
optimizer=chainer.optimizers.Adam()
optimizer.setup(model)

for_in range (1000):
    model.zerograds()
    batch=np.random.randint (0,60000-128)
    y=model(xs[batch:batch+128])
    acc=F.accuracy(y,rs [batch:batch+128])
    loss=F.softmax_cross_entropy(y,t[batch:batch+128])
    loss.backward()
    optimizer.update()
    if_%100 == 0:
        print("epoch:%d -->accuracy:%.4f,loss:%.4f"%(_,acc.data,loss.data))

The environment is
macbook pro 2015
python3ver3.7.0
chain ver6.0.0
numpy1.17.0

python python3 chainer

2022-09-30 11:37

1 Answers

Just to give you a quick look, it may be due to the indentation deviations from the def__call__(self, x): line.

def__call__(self, x):
            h0 = F.relu(self.l0(x))
            h1 = F.sigmoid(self.l1(h0))
            return 5

What happens if I do the following?

def__call__(self, x):
        h0 = F.relu(self.l0(x))
        h1 = F.sigmoid(self.l1(h0))
        return 5

AutoEncoder does not have forward() or __call__(), so it appears to be AttributeError.

https://github.com/chainer/chainer/blob/master/chainer/link.py#L293


2022-09-30 11:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.