多个tensor组成的list转换为tensor
时间: 2023-08-12 21:06:56 浏览: 134
可以使用 PyTorch 中的 torch.stack() 函数将多个 Tensor 组成的 List 转化为一个 Tensor。该函数的参数为一个 Tensor 列表和一个维度参数 dim,表示在哪个维度上进行堆叠。例如,以下代码将三个形状为 (2, 3) 的 Tensor 堆叠在一起,形成一个形状为 (3, 2, 3) 的 Tensor:
```
import torch
a = torch.Tensor([[1,2,3],[4,5,6]])
b = torch.Tensor([[7,8,9],[10,11,12]])
c = torch.Tensor([[13,14,15],[16,17,18]])
tensor_list = [a, b, c]
stacked_tensor = torch.stack(tensor_list, dim=0)
print(stacked_tensor.shape) # 输出 torch.Size([3, 2, 3])
```
相关问题
list 转tensor
可以使用PyTorch中的torch.stack方法将包含tensor的多维list转换成tensor。例如,对于一个包含多个2x3的tensor的list,可以使用torch.stack(a_list)将其转换成一个6x3的tensor。但是,对于包含了tensor的list,使用torch.Tensor就会报错。因此,如果要将普通list转换成tensor,可以直接使用torch.Tensor方法。
list转torch.tensor
可以使用 `torch.tensor()` 将 Python 中的 list 转换为 PyTorch 中的 tensor。例如:
```python
import torch
my_list = [1, 2, 3, 4, 5]
my_tensor = torch.tensor(my_list)
print(my_tensor)
```
输出:
```
tensor([1, 2, 3, 4, 5])
```
如果 list 中包含多个子列表,则可以使用二维列表的形式将其转换为 tensor。例如:
```python
import torch
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
my_tensor = torch.tensor(my_list)
print(my_tensor)
```
输出:
```
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
```
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)