sroyyors
(Sushmita Roy)
March 19, 2024, 2:06pm
1
Hi,
I wanted to directly access the data matrix of the Tensor to store in a primary type, e.g.a double array. I was doing this to write the Tensor to a binary file. Following this post Convert tensor into an array I tried
torch::Tensor preds = torch::zeros({ 4,8 });
preds.index_put_({0,1},2);
preds.index_put_({0,3},4);
preds.index_put_({1,7},5);
preds.index_put_({2,5},-5);
preds.index_put_({3,6},-3.96);
preds.index_put_({2,6},-1e-3);
double* mydata=preds.data_ptr<double>();
But I get sigabort every time I do this. Any ideas how to address this?
thanks!
You could try to initialize or transform the tensor to double as the default dtype would be float (i.e. float32).
sroyyors
(Sushmita Roy)
March 19, 2024, 7:12pm
3
Thank you that worked! I did it like
torch::Tensor preds = torch::zeros({ 4,8 }).to(torch::kDouble);
However, I noted that although this is a 2d tensor, the data_ptr will only return a double* pointer. So I always have to do this:
double* mydata1d=preds.data_ptr<double>();
which I would read as a 1D array. I wonder if it is possible to read it in as a 2D array.
That said, I realized I can also just write the Tensor directly to a binary file like
mytensorfile.write(reinterpret_cast<char*>(&preds),4*8*sizeof(torch::kDouble));