0
0
PytorchHow-ToBeginner · 3 min read

How to Change Tensor dtype in PyTorch Easily

In PyTorch, you can change a tensor's data type using the .to() method or specific methods like .float(), .long(), etc. For example, tensor.to(torch.float32) converts the tensor to 32-bit float type.
📐

Syntax

You can change a tensor's data type in PyTorch using these common methods:

  • tensor.to(dtype): Converts tensor to the specified dtype.
  • tensor.float(): Converts tensor to 32-bit float.
  • tensor.long(): Converts tensor to 64-bit integer.
  • tensor.int(): Converts tensor to 32-bit integer.

Here, dtype is a PyTorch data type like torch.float32, torch.int64, etc.

python
tensor.to(dtype)
tensor.float()
tensor.long()
tensor.int()
💻

Example

This example shows how to create a tensor and change its dtype from integer to float and then to long integer.

python
import torch

# Create an integer tensor
tensor = torch.tensor([1, 2, 3, 4])
print('Original tensor:', tensor)
print('Original dtype:', tensor.dtype)

# Convert to float32 dtype
float_tensor = tensor.to(torch.float32)
print('Float tensor:', float_tensor)
print('Float dtype:', float_tensor.dtype)

# Convert to long (int64) dtype
long_tensor = tensor.long()
print('Long tensor:', long_tensor)
print('Long dtype:', long_tensor.dtype)
Output
Original tensor: tensor([1, 2, 3, 4]) Original dtype: torch.int64 Float tensor: tensor([1., 2., 3., 4.]) Float dtype: torch.float32 Long tensor: tensor([1, 2, 3, 4]) Long dtype: torch.int64
⚠️

Common Pitfalls

Common mistakes when changing tensor dtype include:

  • Using tensor.type() instead of tensor.to() which returns a new tensor but does not change the original in-place.
  • Forgetting that tensor.to() returns a new tensor and does not modify the original tensor unless reassigned.
  • Trying to convert tensors with incompatible data (like strings) to numeric dtypes.

Always assign the result back if you want to keep the changed dtype.

python
import torch

# Wrong: does not change original tensor dtype
x = torch.tensor([1, 2, 3])
x.type(torch.float32)  # returns new tensor but ignored
print(x.dtype)  # still int64

# Right: assign the converted tensor
x = x.to(torch.float32)
print(x.dtype)  # now float32
Output
torch.int64 torch.float32
📊

Quick Reference

MethodDescriptionExample
tensor.to(dtype)Convert tensor to specified dtypetensor.to(torch.float32)
tensor.float()Convert tensor to float32tensor.float()
tensor.long()Convert tensor to int64 (long)tensor.long()
tensor.int()Convert tensor to int32tensor.int()

Key Takeaways

Use tensor.to(dtype) or tensor.float()/long()/int() to change tensor dtype in PyTorch.
tensor.to() returns a new tensor; assign it to keep the change.
Common dtypes include torch.float32 for floats and torch.int64 for long integers.
Avoid using tensor.type() without assignment as it does not modify the original tensor.
Ensure tensor data is compatible with the target dtype before conversion.