Lesson 7 - CAM AttributeError: 'Sequential' object has no attribute 'layer1'

I’m getting this error running the lesson 7 code:

----> 1 sfs = [SaveFeatures(o) for o in [m.layer1, m.layer2, m.layer3, m.layer4]]

AttributeError: 'Sequential' object has no attribute 'layer1'

I can see that the model object is returning numbered attributes that look like they should be the layers, but I can’t work out how they should be passed into the SaveFeatures function.

Any suggestions?

1 Like

I got same issue and somehow children() seems not preserve module name (unlike when the lecture was done?)
I don’t know whether there is cleaner way, but I got it working like this:

m = nn.Sequential(OrderedDict([
*(list(m.named_children())[:-2]),
(‘conv_out’, nn.Conv2d(512, 2, 3, padding=1)),
(‘pool_out’, nn.AdaptiveAvgPool2d(1)),
(‘flat_out’, Flatten()),
(‘sm_out’, nn.LogSoftmax())
]))

This same question was addressed by @sam2 under the “Part 1 (2017)” category of the forum. See this link and Jeremy has updated the code in GitHub as suggested by Sam.

In short Sam suggested that the code be changed from:

sfs = [SaveFeatures(o) for o in [m.layer1, m.layer2, m.layer3, m.layer4]]

to

sfs = [SaveFeatures(o) for o in [m[-7], m[-6], m[-5], m[-4]]]

Sam also suggested a change in cell 16:

feat = np.maximum(0, sf.features[0])

to

feat = np.maximum(0, to_np(sf.features[0]))

The first change resolved problem 1, but I am now getting a problem with the “feat = …” statement, with or without Sam’s suggested change.

feat = np.maximum(0, to_np(sf.features[0]))
–> NameError: name ‘sf’ is not defined

Applying the change suggested by @sjcho did overcome the layers issue highlighted by @pete.condon, but I still had the above error with the “feat = …” statement. Any help would be appreciated.

sf is one of sfs (-s means plural)
Pick whatever you want from sfs

1 Like

@bevanc,

try:
feat = np.maximum(0,to_np(sfs[3].features[0])

sf does not exist because there are multiple of “sf”, which are stored in “sfs” list (-s: plural). Index 3 inside sfs[3] because you want to extract features from layer m[-4].

Hope that help,

1 Like

Thanks for the feedback @sjcho and @HungDO . Problem resolved :grinning:

@bevanc,
To be honest, I think my hack just got me past the point where I was getting the error.
I did get some errors beyond that point…but I moved on because I had learnt what was the essence of the lecture. Sorry :tired_face:
It is by no means iron-clad…so play with it and fix the error.
I’d also like to know what the fix was.

Thanks, that worked for me. I’ve suggested the change on GitHub.

2 Likes