如何在libtorch中重复张量

发布于 2025-01-11 05:11:22 字数 1198 浏览 3 评论 0原文

我正在使用libtorch进行推理,我已将数据从txt文件读取到向量并转换为张量,我想重复张量 三次,然后将其更改为 3D, 我试过了,

std::vector<std::vector<float>> feature_data(255, std::vector<float>(221));
ifstream f_data("../data.txt"); // 
if (! f_data) {
    cout << "Error, file couldn't be opened" << endl; 
    return 1; 
}    
for(int i=0;i<255;i++)
{
    for(int j=0;j<221;j++)
    {
        if ( !f_data ) 
        {
            std::cout << "read error" << std::endl;
            break;
        }
        f_data >> feature_data[i][j];
    }
}
auto data_options = torch::TensorOptions().dtype(at::kFloat);
auto feature_tensor = torch::zeros({255,221}, data_options);
for (int i = 0; i < 255; i++)
    feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221}, 
    data_options);

// begin to repeat three times
auto tensor_clone = feature_tensor.clone();
auto one_time_clone = torch::cat({feature_tensor, tensor_clone}, 0);
auto two_times_clone = torch::cat({one_time_clone, tensor_clone}, 0);
auto transformed_asr = two_times_clone.view({3, 255, 221});

看起来很麻烦,不知道是否正确,有没有简单的方法?

I am using libtorch to inference, I have read data from txt file to vector and convert to tensor, I want to repeat a tensor three times then change it to 3D,
I tried this

std::vector<std::vector<float>> feature_data(255, std::vector<float>(221));
ifstream f_data("../data.txt"); // 
if (! f_data) {
    cout << "Error, file couldn't be opened" << endl; 
    return 1; 
}    
for(int i=0;i<255;i++)
{
    for(int j=0;j<221;j++)
    {
        if ( !f_data ) 
        {
            std::cout << "read error" << std::endl;
            break;
        }
        f_data >> feature_data[i][j];
    }
}
auto data_options = torch::TensorOptions().dtype(at::kFloat);
auto feature_tensor = torch::zeros({255,221}, data_options);
for (int i = 0; i < 255; i++)
    feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221}, 
    data_options);

// begin to repeat three times
auto tensor_clone = feature_tensor.clone();
auto one_time_clone = torch::cat({feature_tensor, tensor_clone}, 0);
auto two_times_clone = torch::cat({one_time_clone, tensor_clone}, 0);
auto transformed_asr = two_times_clone.view({3, 255, 221});

it looks troublesome and I am not sure if it is right, is there an easy way?

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

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

发布评论

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

评论(1

拥抱没勇气 2025-01-18 05:11:22
...
for (int i = 0; i < 255; i++)
    feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221}, 
data_options);
auto tensor_clone = feature_tensor.repeat({3, 1});
...
...
for (int i = 0; i < 255; i++)
    feature_tensor.slice(0, i,i+1) = torch::from_blob(feature_data[i].data(), {221}, 
data_options);
auto tensor_clone = feature_tensor.repeat({3, 1});
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文