Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RuntimeError: torch.cat(): expected a non-empty list of Tensors when put input as tensors #240

Open
Tiabet opened this issue Nov 26, 2024 · 0 comments

Comments

@Tiabet
Copy link

Tiabet commented Nov 26, 2024

from torchvision.transforms import ToTensor
aligned = []
names = []

for x, y in loader:

x_tensor = torch.tensor(np.array(x), dtype=torch.float32).permute(2, 0, 1).unsqueeze(0).to(device)

# Enable gradient computation
x_tensor.requires_grad = True

x_aligned, prob = mtcnn(x_tensor, return_prob=True)

if x_aligned is not None:
    print('Face detected with probability: {:8f}'.format(prob))
    
    # Convert prob to a tensor (if not already) and retain it in the computation graph
    prob_tensor = torch.tensor(prob, device=device, requires_grad=True)
    
    # Define the loss as the negative probability
    loss = -prob_tensor

    # Backpropagate to compute gradients
    loss.backward()
    
    # FGSM attack: Add perturbation to the input image
    epsilon = 0.01  # Small perturbation value
    perturbed_image = x + epsilon * x_tensor.grad.sign()

    # Ensure the perturbed image stays in valid range
    perturbed_image = torch.clamp(perturbed_image, 0, 1)
    
    aligned.append(x_aligned)
    names.append(dataset.idx_to_class[y])

I am testing this code and work with adversarial attack and getting RuntimeError, there is no boxes if I put tensor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant