Tensor 和 NumPy 相互转换的实现

  • Post category:Python

以下是Tensor和NumPy相互转换的实现的攻略:

Tensor 和 NumPy 相互转换的实现

在PyTorch中,可以使用Tensor和NumPy数组来表示和处理数据。以下是一些实现方法:

将NumPy数组转换为Tensor

可以使用torch.from_numpy()函数将NumPy数组转换为Tensor。以下是一个示例:

import numpy as np
import torch

a = np.array([1, 2, 3])
t = torch.from_numpy(a)
print(t)

输出:

tensor([1, 2, 3])

将Tensor转换为NumPy数组

可以使用numpy()函数将Tensor转换为NumPy数组。以下是一个示例:

import numpy as np
import torch

t = torch.tensor([1, 2, 3])
a = t.numpy()
print(a)

输出:

[1 2 3]

总结

这就是Tensor和NumPy相互转换的实现的攻略。可以使用torch.from_numpy()函数将NumPy数组转换为Tensor,也可以使用numpy()函数将Tensor转换为NumPy数组。希望这篇文章能够帮助您更好地理解Tensor和NumPy相互转换的实现方法。