如何在libtorch中将2d张量修改为3d?

发布于 2025-01-09 08:41:54 字数 834 浏览 5 评论 0原文

我有一个2d数组向量,我已经将它转换为张量,但是如何修改张量的维度,我想将维度从2d修改为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);

现在张量是80 * 434,我怎样才能将这个张量中的一维添加到3d,我想要1 * 80 * 434

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绳情 2025-01-16 08:41:54
auto tensor = torch::zeros({80,434}, options);

在这一行之后,

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

我建议在第二行中创建另一个变量而不是张量,例如:

auto transformed_tensor = tensor.view({1, 80, 434});
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});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文