Dan_Sagher
(Dan Sagher)
#1
Hi,
I’m new in Pytorch and I would like to know how to convert an existing tensor into an int array.
I tried to do:
temp_arr = temp_tensor.data< int>();
when “temp_arr” is an (int *), and “temp_tensor” type is int, but i keep getting run time error.
Thank you very much!
I think data is templated member so I would suggest using .data<int>()
auto temp_tensor = torch::randn({ 3, 4 }).to(torch::kInt32);
int* temp_arr = temp_tensor.data<int>();
// alternative
//int* temp_arr = (int*)temp_tensor.data_ptr();
for (int y = 0; y < temp_tensor.sizes()[0]; ++y)
{
for (int x = 0; x < temp_tensor.sizes()[1]; ++x)
{
std::cout << (*temp_arr++) << " ";
}
std::cout << std::endl;
}
std::cout << temp_tensor << std::endl;
Dan_Sagher
(Dan Sagher)
#3
Thank you for your comment!
That’s true, when I put <> in my post it deleted it so now i added space (< int>).
Anyway, I keep getting an error.
What does the error say ? There’s usually pretty good explaining message. Do you catch those errors ? ->
try
{
auto temp_tensor = torch::randn({ 3, 4 }).to(torch::kInt32);
int* temp_arr = temp_tensor.data<int>();
}
catch (std::runtime_error& e)
{
std::cout << e.what() << std::endl;
}
catch (const c10::Error& e)
{
std::cout << e.msg() << std::endl;
}
system("PAUSE");
1 Like
Dan_Sagher
(Dan Sagher)
#5
The problem was that after some functions the tensor type was converted to long so i got the massage:
expected scalar type Int but found Long
Thanks again!
1 Like