How to convert tensor entry to a float or double?

(Muhammad Arslan Ansari) #1

Hi all,
In C++ when we print a tensor like this:

torch::Tensor tensor = torch::zeros({10,1,7}, torch::dtype(torch::kFloat32));
std::cout<<output[i]<<'\n';

we get an output like this:

-0.3716 -0.6210 -0.4650 -0.2274  0.8657 -0.6912 -0.9256
[ Variable[CPUFloatType]{1,7} ]

here I am interested in only float values not the whole output along its datatype. I tried with accessing it with via array style access like output_real[j][0][0] even then it outputs datatype like this: -0.371585 [ Variable[CPUFloatType]{} ]. I just need to access the value, is there any way for that?

cheers :slight_smile:

(Yao Zihang) #2

Like this:

torch::Tensor tensor = torch::randn({3,4});
std::cout << tensor[1][2].item<double>() << std::endl;
1 Like
(Muhammad Arslan Ansari) #3

Thank you so much, it works :blush: