L
i
b
T
o
r
c
h
中
T
e
n
s
o
r
O
p
t
i
o
n
s
的使用
LibTorch中TensorOptions的使用
LibTorch中TensorOptions的使用
TensorOptions是用来配置Tensor属性用的
auto options = torch::TensorOptions()
.dtype(torch::kFloat32)
.layout(torch::kStrided)
.device(torch::kCUDA, 1)
.requires_grad(true);
torch::Tensor tensor = torch::full({3, 4}, 123, options);
assert(tensor.dtype() == torch::kFloat32);
assert(tensor.layout() == torch::kStrided);
assert(tensor.device().type() == torch::kCUDA);
assert(tensor.device().index() == 1);
assert(tensor.requires_grad());
示例:
#include <torch/torch.h>
using namespace std;
int main()
{
auto options = torch::TensorOptions()
.dtype(torch::kFloat32)
.requires_grad(true);
torch::Tensor w = torch::randn({ 1 }, options);
assert(w.dtype() == torch::kFloat32);
assert(w.requires_grad());
cout << (w.dtype() == torch::kFloat32) << " " << w.requires_grad() << endl;
system("pause");
return 0;
}
参考官方链接
https://pytorch.org/cppdocs/notes/tensor_creation.html