Traceback (most recent call last):
File “cam_new_30nov.py”, line 86, in 
logit = net(img_variable)
File “/mnt/backup/medhani/pytorch/local/lib/python2.7/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/mnt/backup/medhani/pytorch/local/lib/python2.7/site-packages/torchvision/models/resnet.py”, line 139, in forward
x = self.conv1(x)
File “/mnt/backup/medhani/pytorch/local/lib/python2.7/site-packages/torch/nn/modules/module.py”, line 491, in call
result = self.forward(*input, **kwargs)
File “/mnt/backup/medhani/pytorch/local/lib/python2.7/site-packages/torch/nn/modules/conv.py”, line 301, in forward
self.padding, self.dilation, self.groups)
RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor for argument #2 ‘weight’
I got the above error for the below code. Do you have any idea about it?
hook the feature extractor
features_blobs = []
def hook_feature(module, input, output):
features_blobs.append(output.data.cpu().numpy())
net._modules.get(finalconv_name).register_forward_hook(hook_feature)
print(net)
get the softmax weight
params = list(net.parameters())
weight_softmax = np.squeeze(params[-2].data.cpu().numpy())
def returnCAM(feature_conv, weight_softmax, class_idx):
# generate the class activation maps upsample to 256x256
size_upsample = (256, 256)
bz, nc, h, w = feature_conv.shape
output_cam = []
for idx in class_idx:
cam = weight_softmax[idx].dot(feature_conv.reshape((nc, h*w)))
cam = cam.reshape(h, w)
cam = cam - np.min(cam)
cam_img = cam / np.max(cam)
print ‘A’
print(np.uint8(255 * cam_img))
cam_img = np.uint8(255 * cam_img)
output_cam.append(cv2.resize(cam_img, size_upsample))
return output_cam

normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]
)
preprocess = transforms.Compose([
transforms.Resize((224,224)),
transforms.ToTensor(),
normalize
])
#response = requests.get(IMG_URL)
img_pil = Image.open(“ADNI_002_S_0619_MR_MPR-R__GradWarp__N3__Scaled_2_Br_20081001115218896_S15145_I118678.png”)
#img_pil = Image.open(io.BytesIO(response.content))
img_pil.save(‘test.jpg’)
img_tensor = preprocess(img_pil)
img_variable = Variable(img_tensor.unsqueeze(0).cpu())
logit = net(img_variable)
download the imagenet category list
#classes = {int(key):value for (key, value)
in requests.get(LABELS_URL).json().items()}
dic = {0: ‘MCIs’, 1: ‘MCIc’ }
with open(‘label2.json’, ‘w’) as fp:
fp.write(json.dumps(dic, sort_keys=True, indent=4))
with open(‘label2.json’) as json_data:
d = json.load(json_data)
print(d)
#pdb.set_trace()
classes = {int(key):value for (key, value)
in requests.get(‘label2.json’).json().items()}
       in d.items()}

#pdb.set_trace()
h_x = F.softmax(logit, dim=1).data.squeeze()
probs, idx = h_x.sort(0, True)
probs = probs.numpy()
idx = idx.numpy()
output the prediction
#for i in range(0, 5):
print(’{:.3f} -> {}’.format(probs[i], classes[idx[i]]))
generate class activation mapping for the top1 prediction
CAMs = returnCAM(features_blobs[0], weight_softmax, [idx[0]])
print (idx[0])
render the CAM and output
Got an error
#print(‘output CAM.jpg for the top1 prediction: %s’%classes[idx[0]])
img = cv2.imread(‘test.jpg’)
height, width, _ = img.shape
heatmap = cv2.applyColorMap(cv2.resize(CAMs[0],(width, height)), cv2.COLORMAP_JET)
result = heatmap * 0.3 + img * 0.5
cv2.imwrite(‘CAM.jpg’, result)
#with open(‘label.json’) as json_data:
d = json.load(json_data)
print(d)