Pytorch C++ libtorch的使用方法

Pytorch C++ libtorch

pytorch C++ libtorch的,版本方面可以自己进行源码编译(有很多依赖),也可以从github上下载已经编译好的版本,官方使用教程给的libtorch编译时g++版本较低,不支持CXX11所以,可以下载支持CXX11版本的libtorch

具体使用

对于pytorch的模型使用官方已有很明确的教程,可以放心使用,其中从pth->pt时,可能会遇到关于hooks的问题,我找到的方法首先

# pth->pt pt用来给C++使用
import torch
from torch import nn
from collections import OrderedDict
from collections import namedtuple
def remove_hooks(model):
    model._backward_hooks = OrderedDict()
    model._forward_hooks = OrderedDict()
    model._forward_pre_hooks = OrderedDict()
    for child in model.children():
        remove_hooks(child)
device = torch.device('cpu')
model=torch.
以下是使用C++libtorch实现类似于pytorch的ImageFolder方法的示例代码: ``` #include <torch/torch.h> #include <opencv2/opencv.hpp> class ImageFolderDataset : public torch::data::datasets::Dataset<ImageFolderDataset> { public: ImageFolderDataset(const std::string& root_dir, const std::string& extensions = ".jpg") : root_dir_(root_dir), extensions_(extensions) { // find all image files in the root directory for (auto& dir_entry : std::filesystem::directory_iterator(root_dir)) { auto path = dir_entry.path(); if (std::filesystem::is_regular_file(path) && is_image_file(path)) { image_paths_.push_back(path); } } } // get the i-th example in the dataset torch::data::Example<> get(size_t index) override { // load the image and convert to tensor auto image = cv::imread(image_paths_[index].string()); cv::cvtColor(image, image, cv::COLOR_BGR2RGB); // convert from BGR to RGB torch::Tensor tensor_image = torch::from_blob(image.data, { image.rows, image.cols, 3 }, torch::kByte).permute({ 2, 0, 1 }).toType(torch::kFloat) / 255.0; // get the label from the directory name auto label_path = image_paths_[index].parent_path(); int label = std::distance(std::filesystem::directory_iterator(root_dir_), std::find_if(std::filesystem::directory_iterator(root_dir_), std::filesystem::directory_iterator(), [&label_path](const auto& dir_entry) { return dir_entry.path() == label_path; })); return { tensor_image.clone(), torch::tensor(label) }; } // return the number of examples in the dataset torch::optional<size_t> size() const override { return image_paths_.size(); } private: std::vector<std::filesystem::path> image_paths_; std::string root_dir_; std::string extensions_; bool is_image_file(const std::filesystem::path& path) const { auto extension = path.extension().string(); return extensions_.empty() || std::find(extensions_.begin(), extensions_.end(), extension) != extensions_.end(); } }; int main() { // create the dataset and dataloader std::string root_dir = "/path/to/dataset"; ImageFolderDataset dataset(root_dir); auto data_loader = torch::data::make_data_loader<torch::data::samplers::SequentialSampler>(dataset, torch::data::DataLoaderOptions().batch_size(32)); // train the model using the dataset // ... } ``` 在上面的代码中,`ImageFolderDataset`类继承了`torch::data::datasets::Dataset`,并实现了`get()`和`size()`方法,以便能够使用`torch::data::make_data_loader()`函数创建一个数据加载器。在`get()`方法中,我们加载了图像并将其转换为张量,并从目录名称中获取标签。在`size()`方法中,我们返回数据集中的示例数。 注意,这里我们使用了OpenCV库来加载和处理图像。如果您想使用其他库,可以相应地修改代码。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值