RuntimeError: cannot register a hook on a tensor that doesn't require gradient #132
-
my model is resnet18,and i change its fc,1000 to 2, from torchcam.methods import SmoothGradCAMpp, GradCAMpp
cam_extractor = GradCAMpp(model)` how ever:
|
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 8 replies
-
Hi @kevinxu-cn97 👋 That looks more like a bug report than a "Question & Answers" 😅 |
Beta Was this translation helpful? Give feedback.
-
@kevinxu-cn97 |
Beta Was this translation helpful? Give feedback.
-
Hi all @kevinxu-cn97 @JACKCHAN000 @RuixiangZhao 👋 As discussed in #146, here are a few updates:
One last thing to illustrate my struggle here:
from torch import nn
from torchvision.models import resnet18
from torchcam.methods import GradCAMpp
# Create the model
model = resnet18(pretrained=False)
model.fc = nn.Linear(512, 2)
# Hook it
cam_extractor = GradCAMpp(model) which runs perfectly on my end. According to your error, perhaps you've frozen layers of the model (and thus the snippet is incomplete), but I cannot infer much more 🤷♂️
import torch
from torchvision import transforms
from torchvision.models import resnet50
from torchcam.methods import SmoothGradCAMpp
from PIL import Image
my_model = resnet50().eval()
cam_extractor = SmoothGradCAMpp(my_model)
img = Image.fromarray((255 * torch.rand((224, 224, 3))).round().to(dtype=torch.uint8).numpy())
test_transforms = transforms.Compose(
[transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
input_tensor = test_transforms(img)
out = my_model(input_tensor.unsqueeze(0)) which also runs perfectly on my end 🤷♂️ Let's get to the bottom of this together 🙌 |
Beta Was this translation helpful? Give feedback.
-
@frgfm It finally works now. |
Beta Was this translation helpful? Give feedback.
-
Could you help me out with my implementation? I'm no expert at PyTorch but I believe I have frozen the required layers and kept the target layer unfrozen but I am still getting the same error as @kevinxu-cn97 . I have attached all relevant code snippets below. This is the part where I import the model and freeze the layers, then change the model. fc after I have frozen the layers.
let me show you the implementation of
This is where I got my error
|
Beta Was this translation helpful? Give feedback.
Hi all @kevinxu-cn97 @JACKCHAN000 @RuixiangZhao 👋
As discussed in #146, here are a few updates:
One last thing to illustrate my struggle here: