selin
selin

Reputation: 21

Conversion of 2d vector to torch::tensor doesn't have the right data in C++

I'm trying to convert a 2d vectors to torch tensor in c++ but the output doesn't have the right data:

std::vector<std::vector <int>> indx1 = {{126, 22}, {166, 102}, {46, 46}, {166, 54} };
auto indx_options = torch::TensorOptions().dtype(torch::kInt32);
auto indx = torch::from_blob(indx1.data(), {indx1.size(),2}, indx_options);

output:

 1.1586e+09  2.2036e+04
 1.1586e+09  2.2036e+04
 1.1586e+09  2.2036e+04
 1.1586e+09  2.2036e+04
[ CPUIntType{4,2} ]

I appreciate any feedback.

Upvotes: 0

Views: 76

Answers (2)

Jalin Lee
Jalin Lee

Reputation: 1

Yes, That's all because the type vector<vector>. A memory of a one-dim vector is contiguous, but that's not for other that 2. Your provided memory layout may be like this: [126, 22, xxx, xxx, xxx] // with a size reserved for a vector [166, 102, xxx,xxx,xxx] .......

Upvotes: 0

selin
selin

Reputation: 21

Update: I could resolve this by using arrays instead of vectors.

int indx1[4][2] = {126, 22}, {166, 102}, {46, 46}, {166, 54}};
auto indx_options = torch::TensorOptions().dtype(torch::kInt32);
auto indx = torch::from_blob(indx1, {4,2}, indx_options);

output:

 126  22
 166  102
 46   46
 166  54
[ CPUIntType{4,2} ]

Upvotes: 0

Related Questions