Convert tensor into an array

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 =< 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 =<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;

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 ? ->

	auto temp_tensor = torch::randn({ 3, 4 }).to(torch::kInt32);
	int* temp_arr =<int>();
catch (std::runtime_error& e)
  std::cout << e.what() << std::endl;
catch (const c10::Error& e)
   std::cout << e.msg() << std::endl;

1 Like

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

terminate called after throwing an instance of ‘c10::Error’
what(): expected scalar type Int but found Long
Exception raised from data_ptr at aten/src/ATen/core/TensorMethods.cpp:20 (most recent call first):
frame #0: c10::Error::Error(c10::SourceLocation, std::string) + 0x3e (0x7f66dab3aa1e in /home/nathan/app/libtorch/lib/
frame #1: c10::detail::torchCheckFail(char const*, char const*, unsigned int, std::string const&) + 0x5c (0x7f66dab13ce4 in /home/nathan/app/libtorch/lib/
frame #2: int* at::TensorBase::data_ptr() const + 0x112 (0x7f66c3b5b2b2 in /home/nathan/app/libtorch/lib/
frame #3: ./bins/run_test() [0x41e94a]
frame #4: ./bins/run_test() [0x41cf21]
frame #5: ./bins/run_test() [0x41d3d2]
frame #6: ./bins/run_test() [0x41337b]
frame #7: ./bins/run_test() [0x4133d3]
frame #8: __libc_start_main + 0xf0 (0x7f66c01f7840 in /lib/x86_64-linux-gnu/
frame #9: ./bins/run_test() [0x4130a9]