user13770964
user13770964

Reputation:

Convert C++ vector<vector<float>> to torch::tensor

I am trying to convert my c++ vector to a torch tensor. However, my code is returning incorrect conversions.

    cout << history << endl;
    auto options1 = torch::TensorOptions().dtype(torch::kFloat32);
    input = torch::from_blob(history.data(), {size, 1, 6}, options1).to(torch::kFloat32);

    cout << input << endl;

The above code returns the following output:

-9 -3 -3 -12 -0 -0 -12 -2 -3 -12 -0 -0

(1,.,.) = 
 -9.8681e-32  4.5793e-41 -9.8682e-32  4.5793e-41 -9.8682e-32  4.5793e-41




(2,.,.) = 
 -9.8682e-32  4.5793e-41 -9.8683e-32  4.5793e-41 -9.8683e-32  4.5793e-41




[ CPUFloatType{2,1,6} ]

Upvotes: 0

Views: 2610

Answers (1)

hasan torabi
hasan torabi

Reputation: 34

You can not convert a 2D vector or more dimension to Tensor with the from_blob() method, but you can use this method to overcome the problem:

vector<float> linearize(const vector<vector<float>>& vec_vec) {
    vector<float> vec;
    for (const auto& v : vec_vec) {
        for (auto d : v) {
            vec.push_back(d);
        }
    }
    return vec;
}

And, in this way, you can convert it to Tensor (m,n width and height of vector):

vector<float> vec = linearize(your2Dvector);
torch::Tensor t = torch::from_blob(vec.data(), {n,m});

Upvotes: 2

Related Questions