赞
踩
1.1 pytorch
① list->tensor
data = [[1,2],[3,4]]
x_data = torch.tensor(data)
② Numpy array->tensor
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
③ 根据已有张量初始化
x_ones = torch.ones_like(x_data)
x_rand = torch.rand_like(x_data,dtype = torch.float)
④ 创建指定大小的tensor(开辟新的内存)
shape = (2,3)
x_ones = torch.ones(shape)
x_zeros = torch.zeros(shape)
x_rand = torch.rand(shape)
1.2 torchlib
① 数组->Tensor
int data[10] = {3,4,6}
torch::Tensor x_data = torch::from_blob(data,{3},torch::kFloat)
② 标准库的vector->Tensor:
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();
④ 创建指定大小的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});
2.1 pytorch
① 索引+切片:(共用一块存储数据的内存)
tensor = torch.rand(4,4)
a = tensor[:,1]
② 提取指定元素组成新的张量
Tensor[Mask]#即可提取想要的元素
2.2 torchlib
① 索引
auto x = torch::rand({3,4});
y = x[1];//选择第0维的第1层
y = x[1][3]//选择第0维的第1层,第2维的第3层对应的元素
② 切片
当切取一层时:
auto x = torch::rand({3,4});
auto y = x.select(0,1)//选择第0维的第1层张量,即矩阵中的第二行
当连续切取几层时:
auto x = torch::rand({3,4});
auto y = x.narrow(0,2,2)//从第0维的第2层张量开始选两层张量
auto y = x.slice(0,1,3)//第0维中选择第1维到第3-1维的张量
注意:x,y的数值指向同一块内存空间
③ 提取指定元素形成新的张量(关键字index:就代表是提取出来相应的元素组成新的张量)
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;
Tensor x = x_data.index({ mask.to(kBool) });//index()方法输入参量为布尔值组成的数组,输出参量为对应index的值组成新的张量(新的内存空间)
3.1 pytorch
① 按元素的加减乘除正常使用±*/的运算符即可
② 矩阵乘法:例如xx^T
x = torch.rand((3,4))
y = x @ x.T
y = x.matmul(x.T)
3.2 torchlib
① 按元素的加减乘除正常使用±*/的运算符即可
② 矩阵乘法:例如xx^T
auto x = torch::rand({3,4});
x.mm(x.t());
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。