gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
How to convert a pytorch tensor in a numpy array?
- User
How to convert a pytorch tensor in a numpy array?
- Assistant
To convert a PyTorch tensor to a numpy array, you can use the
.numpy()method. Here's an example:import torch import numpy as np # create a PyTorch tensor x = torch.tensor([[1, 2], [3, 4]]) # convert the tensor to a numpy array x_np = x.numpy() print(x_np)Output:
array([[1, 2], [3, 4]])Note that if the PyTorch tensor is on a CUDA device, you will need to move it to the CPU first using
.cpu()before converting it to numpy. For example:# create a PyTorch tensor on the GPU x_gpu = torch.tensor([[1, 2], [3, 4]], device='cuda') # move the tensor to the CPU and convert to numpy x_np = x_gpu.cpu().numpy() print(x_np)