The grad of vgg is used as the activation value to display image objects.

Source: Internet
Author: User
Import torchimport numpyimport torch. nn as nnimport torch. nn. functional as ffrom Pil import imagefrom torchvision import transformsimport torchvision. models as modelsnormalize = transforms. normalize (mean = [0.485, 0.456, 0.406], # This is imagenet STD = [0.229, 0.224, 0.225]) TRAN = transforms. compose ([transforms. resize (224,224), transforms. totensor (), transforms. normalize (mean = [0.485, 0.456, 0.406], STD = [0.22 9, 0.224, 0.225]) Im = '. /1.jpeg '# im = '. /2.jpg 'im = image. open (IM) Im = Tran (IM) im. unsqueeze _ (DIM = 0) Im = torch. autograd. variable (IM, requires_grad = true) vgg = models. vgg16 () Pre = torch. load ('/home/qk /. torch/models/vgg16-397923af.pth ') vgg. load_state_dict (pre) out = vgg (IM) outnp = out. data [0] ind = int (numpy. argmax (outnp) out [0] [ind]. backward () grad = IM. gradgrad. squeeze _ (0) grad = grad * gradgrad = grad. sum (keepdim = false, dim = 0) Grad = torch. SQRT (GRAD) Rg = torch. max (GRAD) grad = grad/rg * 255. # It's amazing. Why can we activate the image with uint8 !!!!! If I don't search for it, how can I debug it? # Im = image. fromarray (grad. numpy (), 'L ')#. eval () tensor-> numpy arrayim = image. fromarray (numpy. uint8 (grad. numpy (), 'L ')#. eval () tensor-> numpy arrayim.save('grey.png ') # input () from CLS import dprint (d [ind])

 

The grad of vgg is used as the activation value to display image objects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.