WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

PyTorch · Intermediate · question 29 of 100

What is the difference between using torch.Tensor.item() and torch.Tensor.detach() in PyTorch?

📕 Buy this interview preparation book: 100 PyTorch questions & answers — PDF + EPUB for $5

‘torch.Tensor.item()‘ and ‘torch.Tensor.detach()‘ are both PyTorch tensor methods, but they serve different purposes.

‘torch.Tensor.item()‘ method returns a single Python scalar value from a tensor containing a single value. For example, if we have a tensor ‘t‘ of shape ‘(1,)‘ (scalar tensor), ‘t.item()‘ will return the single float or integer value stored in the tensor. Here’s an example code snippet:

import torch

t = torch.tensor([3.14159])
val = t.item()    # val holds value 3.14159 as a Python scalar
print(val, type(val))    # Output: 3.14159 <class 'float'>

On the other hand, ‘torch.Tensor.detach()‘ method creates a new tensor that shares the same underlying data as the original tensor, but its computational graph is detached and it is no longer part of the computation history. The returned tensor is a new tensor with the same values but without the gradient computation history. Detaching a tensor is useful when we want to use tensor values for further processing but don’t want to compute gradients with respect to them. Here’s an example code snippet:

import torch

t = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True)
t_detached = t.detach()   # Create a new tensor without the computation graph attached
t_detached[1, 1] = 10.0   # Modify the value
print(t)    # Output: tensor([[1., 2.], [3., 4.]], requires_grad=True)

Note that if we had modified the value of ‘t_detached‘ before detaching it, the original tensor ‘t‘ would have also been modified.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic PyTorch interview — then scores it.
📞 Practice PyTorch — free 15 min
📕 Buy this interview preparation book: 100 PyTorch questions & answers — PDF + EPUB for $5

All 100 PyTorch questions · All topics