深度阅读

How to convert a PyTorch tensor to a NumPy array?

作者
作者
2023年08月22日
更新时间
8.94 分钟
阅读时间
0
阅读量

To convert a PyTorch tensor to a NumPy array, you can use the .numpy() method. Here is 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
y = x.numpy()

# Print the NumPy array
print(y)

In this code, we create a PyTorch tensor x and then use the .numpy() method to convert it to a NumPy array y. Note that if the PyTorch tensor is on the GPU, you will need to move it to the CPU before calling .numpy(), like this:

# Move the PyTorch tensor to the GPU
x = x.to('cuda')

# Convert the tensor to a NumPy array (on CPU)
y = x.to('cpu').numpy()

In this code, we use the .to() method to move the tensor to the GPU, and then move it back to the CPU using the .to() method again before calling .numpy(). This is necessary because NumPy does not support GPU tensors.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。