torch.Tensor怎么转换成numpy.ndarray
时间: 2024-02-11 11:07:41 浏览: 19
可以使用 `numpy()` 函数将 `torch.Tensor` 转换为 `numpy.ndarray`,示例代码如下:
```python
import torch
import numpy as np
# 创建一个 tensor
tensor = torch.tensor([[1, 2], [3, 4]])
# 将 tensor 转换为 numpy 数组
array = tensor.numpy()
print(array)
```
输出结果为:
```
array([[1, 2],
[3, 4]])
```
相关问题
numpy.ndarray转torch.tensor
要将numpy.ndarray转换为torch.tensor,可以使用torch.from_numpy()函数。这个函数接受一个numpy数组作为输入,并返回一个对应的torch.tensor对象。下面是一个示例代码:
```python
import numpy as np
import torch
# 创建一个numpy数组
arr = np.array(\[\[1, 2, 3\], \[4, 5, 6\]\])
# 将numpy数组转换为torch.tensor
tensor = torch.from_numpy(arr)
print(tensor)
```
输出结果为:
```
tensor(\[\[1, 2, 3\],
\[4, 5, 6\]\])
```
在这个示例中,我们首先创建了一个numpy数组`arr`,然后使用`torch.from_numpy()`函数将其转换为torch.tensor对象`tensor`。最后,我们打印了转换后的tensor对象。
python torch.tensor转numpy.ndarray
可以使用`.numpy()`方法将PyTorch张量转换为NumPy数组,例如:
```python
import torch
import numpy as np
# 创建一个PyTorch张量
x = torch.tensor([[1, 2], [3, 4]])
# 将PyTorch张量转换为NumPy数组
y = x.numpy()
# 打印NumPy数组
print(y)
```
输出结果为:
```
array([[1, 2],
[3, 4]])
```