Yongqi Z
Yongqi Z

Reputation: 641

How to modify a 2d tensor to 3d in libtorch?

I have a 2d array vector<vector>, I have coverted it to tensor, but how to modify the dimension of the tensor, I want to modify the dimension from 2d to 3d?

std::vector<std::vector<float>> voice(434, std::vector<float>(80))
ifstream fp("data.txt");
if (! fp) {
    cout << "Error, file couldn't be opened" << endl; 
    return 1; 
}    
for(int i=0;i<80;i++)
{
    for(int j=0;j<434;j++)
    {
        if ( ! fp ) 
        {
            std::cout << "read error" << std::endl;
            break;
        }
        fp >> voice[i][j]
    }
}

auto options = torch::TensorOptions().dtype(at::kDouble);
auto tensor = torch::zeros({80,434}, options);
for (int i = 0; i < 80; i++)
    tensor.slice(0, i,i+1) = torch::from_blob(vect[i].data(), {434}, options);

Now the tensor is 80 * 434, how can I add one dimension in this tensor to 3d, I want 1 * 80 * 434

Upvotes: 1

Views: 695

Answers (1)

Shaida Muhammad
Shaida Muhammad

Reputation: 1650

auto tensor = torch::zeros({80,434}, options);

followed by this line

auto tensor = tensor.view({1, 80, 434});

I would recommend to create another variable instead of tensor in the second line, like:

auto transformed_tensor = tensor.view({1, 80, 434});

Upvotes: 1

Related Questions