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
| int data[10] = {3,4,6} torch::Tensor x_data = torch::from_blob(data,{3},torch::kFloat)
std::vector<float> std_vector = {3,4,6}; torch::Tensor vector_data = torch::from_brob(std_vector.data(),{3},torch::kFloat);
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();
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(); std::cout<<b.index_select(1,torch::tensor({0,2})).sizes(); std::cout<<b.index_select(2,torch::arange(0,8)).sizes();
Tensor x_data = torch::rand({3,4}); Tensor mask = torch::zeros({3,4});
mask[1][1] = 1; mask[0][0] = 1;
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)
torch::Tensor x = torch::tensor({3, 1, 2, 0, 4, 0, 5, 9, 6}); auto [values, indices] = torch::topk(x, 3);
|
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 推理