pytorch创建一个1维tensor
时间: 2023-03-27 16:05:08 浏览: 66
可以使用以下代码创建一个1维tensor:
```python
import torch
tensor = torch.tensor([1, 2, 3])
```
这将创建一个包含1、2、3的1维tensor。
相关问题
pytorch获取tensor某一维
可以使用 PyTorch 中的索引方式来获取 tensor 的某一维。具体操作为:
```python
import torch
# 创建一个 3x4 的 tensor
tensor = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# 获取第2列
col_2 = tensor[:, 1]
print(col_2)
```
输出结果为:
```
tensor([ 2, 6, 10])
```
在上面的例子中,`[:, 1]` 表示获取 tensor 的所有行,第 1 列的元素。如果要获取其他维度的元素,只需要在索引中指定相应的维度即可。例如:
```python
# 获取第2行
row_2 = tensor[1, :]
print(row_2)
```
输出结果为:
```
tensor([5, 6, 7, 8])
```
pytorch返回1维tensor中不为0元素的索引
可以使用`nonzero()`函数来获取一个1维tensor中所有非零元素的索引。例如,假设有一个1维tensor `x`,我们可以使用以下代码来获取所有非零元素的索引:
```python
import torch
x = torch.tensor([0, 1, 0, 2, 3, 0])
indices = torch.nonzero(x)
print(indices)
```
这将输出:
```
tensor([[1],
[3],
[4]])
```
其中,索引值1、3、4分别对应着tensor中非零元素1、2、3的位置。如果要将这些索引转换成Python列表,可以使用`.tolist()`函数,例如:
```python
indices_list = indices.squeeze().tolist()
print(indices_list)
```
这将输出`[1, 3, 4]`,即所有非零元素的位置。