Skip to content

Commit 9802bff

Browse files
committed
Fixed some bugs when using GPU
1 parent 631080d commit 9802bff

12 files changed

+299
-276
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@
44
.python-version
55
__pycache__
66
images
7+
vis.py

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
PyTorch implementation of [SmoothGrad: removing noise by adding noise](https://arxiv.org/abs/1706.03825).
44

5-
<img src="result/grad/vanilla_grad.jpg" width="180px"> <img src="result/grad/smooth_grad.jpg" width="180px"> <img src="result/grad/guided_grad.jpg" width="180px"> <img src="result/grad/guided_smooth_grad.jpg" width="180px">
5+
|Vanilla Gradients|SmoothGrad|Guided backpropagation|Guided SmoothGrad|
6+
|:-:|:-:|:-:|:-:|:-:|
7+
|<img src="result/grad/vanilla_grad.jpg" width="180px">|<img src="result/grad/smooth_grad.jpg" width="180px">|<img src="result/grad/guided_grad.jpg" width="180px">|<img src="result/grad/guided_smooth_grad.jpg" width="180px">|
68

79
And other techniques such as the following are implemented.
810

grad_cam.py

Lines changed: 74 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -17,79 +17,83 @@
1717

1818

1919
def parse_args():
20-
parser = argparse.ArgumentParser()
21-
parser.add_argument('--cuda', action='store_true', default=False,
22-
help='Use NVIDIA GPU acceleration')
23-
parser.add_argument('--img', type=str, default='',
24-
help='Input image path')
25-
parser.add_argument('--out_dir', type=str, default='./result/cam/',
26-
help='Result directory path')
27-
args = parser.parse_args()
28-
args.cuda = args.cuda and torch.cuda.is_available()
29-
if args.cuda:
30-
print("Using GPU for acceleration")
31-
else:
32-
print("Using CPU for computation")
33-
if args.img:
34-
print('Input image: {}'.format(args.img))
35-
else:
36-
print('Input image: raccoon face (scipy.misc.face())')
37-
print('Output directory: {}'.format(args.out_dir))
38-
print()
39-
return args
20+
parser = argparse.ArgumentParser()
21+
parser.add_argument('--cuda', action='store_true', default=False,
22+
help='Use NVIDIA GPU acceleration')
23+
parser.add_argument('--img', type=str, default='',
24+
help='Input image path')
25+
parser.add_argument('--out_dir', type=str, default='./result/cam/',
26+
help='Result directory path')
27+
args = parser.parse_args()
28+
args.cuda = args.cuda and torch.cuda.is_available()
29+
if args.cuda:
30+
print("Using GPU for acceleration")
31+
else:
32+
print("Using CPU for computation")
33+
if args.img:
34+
print('Input image: {}'.format(args.img))
35+
else:
36+
print('Input image: raccoon face (scipy.misc.face())')
37+
print('Output directory: {}'.format(args.out_dir))
38+
print()
39+
return args
4040

4141

4242
def main():
43-
args = parse_args()
44-
45-
if not os.path.exists(args.out_dir):
46-
os.makedirs(args.out_dir)
47-
48-
target_layer_names = ['35']
49-
target_index = None
50-
51-
# Prepare input image
52-
if args.img:
53-
img = cv2.imread(args.img, 1)
54-
else:
55-
img = misc.face()
56-
img = np.float32(cv2.resize(img, (224, 224))) / 255
57-
preprocessed_img = preprocess_image(img, args.cuda)
58-
59-
# Prediction
60-
output = vgg19(pretrained=True)(preprocessed_img)
61-
pred_index = np.argmax(output.data.cpu().numpy())
62-
print('Prediction: {}'.format(IMAGENET_LABELS[pred_index]))
63-
64-
# Prepare grad cam
65-
grad_cam = GradCam(
66-
pretrained_model=vgg19(pretrained=True),
67-
target_layer_names=target_layer_names,
68-
cuda=args.cuda)
69-
70-
# Compute grad cam
71-
mask = grad_cam(preprocessed_img, target_index)
72-
73-
save_cam_image(img, mask, os.path.join(args.out_dir, 'grad_cam.jpg'))
74-
print('Saved Grad-CAM image')
75-
76-
# Reload preprocessed image
77-
preprocessed_img = preprocess_image(img)
78-
79-
# Compute guided backpropagation
80-
guided_backprop = GuidedBackpropGrad(
81-
pretrained_model=vgg19(pretrained=True), cuda=args.cuda)
82-
guided_backprop_saliency = guided_backprop(preprocessed_img, index=target_index)
83-
84-
cam_mask = np.zeros(guided_backprop_saliency.shape)
85-
for i in range(guided_backprop_saliency.shape[0]):
86-
cam_mask[i, :, :] = mask
87-
88-
cam_guided_backprop = np.multiply(cam_mask, guided_backprop_saliency)
89-
save_as_gray_image(
90-
cam_guided_backprop,
91-
os.path.join(args.out_dir, 'guided_grad_cam.jpg'))
92-
print('Saved Guided Grad-CAM image')
43+
args = parse_args()
44+
45+
if not os.path.exists(args.out_dir):
46+
os.makedirs(args.out_dir)
47+
48+
target_layer_names = ['35']
49+
target_index = None
50+
51+
# Prepare input image
52+
if args.img:
53+
img = cv2.imread(args.img, 1)
54+
else:
55+
img = misc.face()
56+
img = np.float32(cv2.resize(img, (224, 224))) / 255
57+
preprocessed_img = preprocess_image(img, args.cuda)
58+
59+
model = vgg19(pretrained=True)
60+
if args.cuda:
61+
model.cuda()
62+
63+
# Prediction
64+
output = model(preprocessed_img)
65+
pred_index = np.argmax(output.data.cpu().numpy())
66+
print('Prediction: {}'.format(IMAGENET_LABELS[pred_index]))
67+
68+
# Prepare grad cam
69+
grad_cam = GradCam(
70+
pretrained_model=model,
71+
target_layer_names=target_layer_names,
72+
cuda=args.cuda)
73+
74+
# Compute grad cam
75+
mask = grad_cam(preprocessed_img, target_index)
76+
77+
save_cam_image(img, mask, os.path.join(args.out_dir, 'grad_cam.jpg'))
78+
print('Saved Grad-CAM image')
79+
80+
# Reload preprocessed image
81+
preprocessed_img = preprocess_image(img)
82+
83+
# Compute guided backpropagation
84+
guided_backprop = GuidedBackpropGrad(
85+
pretrained_model=model, cuda=args.cuda)
86+
guided_backprop_saliency = guided_backprop(preprocessed_img, index=target_index)
87+
88+
cam_mask = np.zeros(guided_backprop_saliency.shape)
89+
for i in range(guided_backprop_saliency.shape[0]):
90+
cam_mask[i, :, :] = mask
91+
92+
cam_guided_backprop = np.multiply(cam_mask, guided_backprop_saliency)
93+
save_as_gray_image(
94+
cam_guided_backprop,
95+
os.path.join(args.out_dir, 'guided_grad_cam.jpg'))
96+
print('Saved Guided Grad-CAM image')
9397

9498

9599
if __name__ == '__main__':

0 commit comments

Comments
 (0)