[libtorch]common api

目录

tensor::Tensor

init tensor

tensor attribute

数据类型转换

基本操作​​​​​​​

tensor::Tensor

init tensor

torch::Tensor b = torch::zeros({2,3});  // 2x3的全0张量
torch::Tensor b = torch::ones({2,3});   // 2x3的全1张量
torch::Tensor b = torch::eye(5);        // 5x5的张量,对角线为1,其余为0
torch::Tensor b = torch::full({2,3},-1);    // 2x3的全-1张量
torch::Tensor a = torch::full_like(b,2.5);  // b_shape的全2.5张量,数据类型同b
torch::Tensor a = torch::full_like(b.toType(kFloat),2.5); // b_shape的全2.5张量,dtype改变
torch::Tensor b = torch::tensor({1,2,3,4,5,6});   // 1-D constant张量
torch::Tensor b = torch::rand({2,3});   // 2x3的张量,数据符合均匀分布的随机数[0,1)之间
torch::Tensor b = torch::randn({2,3});  // 2x3的张量,数据符合标准正态分布,均值为0,方差为1
torch::Tensor b = torch::randint(0, 10, {2,3});  // 2x3的tensor,数据范围[0,10)之间的整数

//用数组初始化
int array[4] = {1,2,3,4,5,6};
auto b = torch::from_blob(array, {2,3}, torch::kInt);

//用vector迭代器初始化
std::vector<float> array = {1,2,3,4,5,6};
auto b = torch::from_blob(array.data(), {2,6}, torch::kFloat);

//用opencv::Mat初始化
cv2::Mat a = Mat::zeros(5,5,CV_32FC1);  // 5x5 全0
auto b = torch::from_blob(a.data, {1,1,5,5}, torch::kFloat);

//PS:torch::from_blob是浅拷贝,输出的tensor与传入的指针共享内存;
// 如果需要开辟新内存,调用clone函数来实现深拷贝
int array[4] = {1,2,3,4,5,6};
auto b = torch::from_blob(array, {2,3}, torch::kInt).clone();


tensor attribute

torch::Tensor b = torch::rand({2,3});

cout << b.sizes() << endl;   //Tensor维度:[2,3]
cout << b.print() << endl;   //Tensor维度+数据类型: [CPUFLoatType [2,3]]
cout << b << endl;           //tensor内容
cout << b.is_cuda() << endl; //CPU or GPU:0
cout << a.dtype() << endl;   //数据类型:CPUFLoatType 
cout << a.ndimension() << endl;  //维度:2
cout << a.nbytes() << endl;    // 数据字节数:4*6=24
cout << a.sizes()[0] << endl;  // axis=0形状:2
cout << a.sizes()[1] << endl;  // axis=1形状:3

数据类型转换

// tensor convert to scaler
torch::Tensor a = torch::tensor({1,2,3,4});
int b = a[0].item<int>();

基本操作

// concat:张量拼接
torch::Tensor a1 = torch::rand({2,3});
torch::Tensor a2 = torch::rand({2,4});
torch::Tensor b = torch::cat({a1,a2}, 1);  //在axis=1拼接,outshape=2x7



// index:索引操作

//linespace(start,end,length):取值范围在[start,end]之间取length个数
torch::Tensor b = torch::linspace(1,75,75).reshape({3,5,5});
auto out = b.index({2, "..."});     // b[2][:][:]->shape=(5,5)
auto out = b.index({2, 3, "..."});  // b[2][3][:]->shape=(5,)
auto out = b.index({"...", 2, 3});  // b[:][2][3]->shape=(3,)
auto out = b.index({"...", 3});     // b[:][:][3]->shape=(3,5)
auto out = b.index({0, 0, 0});      // b[0][0][0]->scaler

//通过索引赋值
b.index_put_({0,0,0}, -1);
b.index_put_({"...", 1}, -2);


// at::slice(input,dim,start,end,step):张量切片,在axis轴上执行
torch::Tensor a = torch::linspace(1,75,75).reshape({3,5,5});
auto b = aten::slice(a, 2, 1, -1, 2);    //在axis=2轴[1,5)slice,outshape=(3,5,2)

//at::equal(tensor1,tensor2)
bool judge = at::equal(a, b);

猜你喜欢

转载自blog.csdn.net/zmj1582188592/article/details/123633820
API