LibPyTorch Doc

Tensor初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//1 数组 -> Tensor
int data[10] = {3,4,6}
torch::Tensor x_data = torch::from_blob(data,{3},torch::kFloat)

//2 vector -> Tensor
std::vector<float> std_vector = {346};
torch::Tensor vector_data = torch::from_brob(std_vector.data(),{3},torch::kFloat);

//3 Tensor like
torch::Tensor x = torch::zeros({3,4});
torch::Tensor x_zeros = torch::zeros_like(x);
torch::Tensor x_ones = torch::ones_like(x);
torch::Tensor x_rand = torch::rand_like(x);
//浅拷贝
torch::Tensor y = x
//深拷贝
torch::Tensor z = x.clone();


//4 new shape Tensor
torch::Tensor x_ones = torch::ones({3,4});
torch::Tensor x_zeros = torch::zeros({3,4});
torch::Tensor x_eye = torch::eye(4);
torch::Tensor x_full = torch::full({3,4},10);
torch::Tensor x_rand = torch::rand({3,4});
torch::Tensor x_randn = torch::randn({3,4});
torch::Tensor x_randint = torch::randint(0,4,{3,3});

Tensor 操作

index_select

提取指定元素形成新的张量(关键字index:就代表是提取出来相应的元素组成新的张量)

1
2
3
4
5
6
7
8
9
10
11
12
std::cout<<b.index_select(0,torch::tensor({0, 3, 3})).sizes();//选择第0维的0,3,3组成新张量[3,3,28,28]
std::cout<<b.index_select(1,torch::tensor({0,2})).sizes(); //选择第1维的第0和第2的组成新张量[10, 2, 28, 28]
std::cout<<b.index_select(2,torch::arange(0,8)).sizes(); //选择十张图片每个通道的前8列的所有像素[10, 3, 8, 28]

Tensor x_data = torch::rand({3,4});
Tensor mask = torch::zeros({3,4});

mask[1][1] = 1;
mask[0][0] = 1;

//index()方法输入参量为布尔值组成的数组,输出参量为对应index的值组成新的张量(新的内存空间)
Tensor x = x_data.index({ mask.to(kBool) });

torch::topk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
torch::Tensor torch::topk(const torch::Tensor& input, int k, int dim=-1, bool largest=true, bool sorted=false)

// input:输入张量。
// k:最大的 k 个值的数量。
// dim:要获取最大值的位置的维度,默认为 -1(最后一位)。
// largest:如果为 true,则返回最大的 k 个值;如果为 false,则返回最小的 k 个值。默认为 true。
// sorted:如果为 true,则返回的值是排序的;如果为 false,则不保证排序。默认为 false。

/// return
// 一个张量,包含最大的 k 个值(如果 largest=true)或最小的 k 个值(如果 largest=false)。
// 一个张量,包含这些值的索引。

torch::Tensor x = torch::tensor({3, 1, 2, 0, 4, 0, 5, 9, 6});
auto [values, indices] = torch::topk(x, 3);

// values: tensor([9, 7, 6])
// indices: tensor([8, 5, 4])

E2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
torch::Tensor scores = torch::rand({10});
std::tuple<torch::Tensor,torch::Tensor> sort_ret = torch::sort(scores.unsqueeze(1), 0, 1);
torch::Tensor v = std::get<0>(sort_ret).squeeze(1).to(scores.device());
torch::Tensor idx = std::get<1>(sort_ret).squeeze(1).to(scores.device());
std::cout<<scores<<std::endl;
std::cout<<v<<std::endl;
std::cout<<idx<<std::endl;

for(int i=0;i<10;i++)
{
int idx_1 = idx[i].item<int>();
float s = v[i].item<float>();

std::cout<<idx_1<<" "<<s<<std::endl;
}

Reference

libtorch 常用api函数示例(史上最全、最详细)_无左无右的博客-CSDN博客

Libtorch教程(二):基于Libtorch分类模型推理_脆皮茄条的博客-CSDN博客_libtorch 推理