Ubuntu18.04安装gpu版本libtorch1.3.1

ubuntu系统安装cuda、cudnn、pytorch、libtorch、TensorRT ubuntu系统安装pytorch和libtorch 阅读详情

安装libtorch

X86平台直接下载官方编译的版本,解压后可直接用, arm平台需要下载源码编译
libtorch库的安装参考:https://pytorch.org/cppdocs/installing.html。
下载:libtorch c++

GPU版本
Libtorch1.3.1 cuda10.0
https://download.pytorch.org/libtorch/cu100/libtorch-shared-with-deps-1.3.1%2Bcu100.zip
https://download.pytorch.org/libtorch/cu100/libtorch-cxx11-abi-shared-with-deps-1.3.1%2Bcu100.zip  (使用这个链接)

unzip libtorch-cxx11-abi-shared-with-deps-1.3.1%2Bcu100.zip
解压后就可以使用

一个简单的 example-app

example-app/
  CMakeLists.txt
  example-app.cpp

example-app.cpp

#include <torch/torch.h>
#include <iostream>

int main() {
  torch::Tensor tensor = torch::rand({2, 3});
  std::cout << tensor << std::endl;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example-app)

find_package(Torch REQUIRED)

add_executable(example-app example-app.cpp)
target_link_libraries(example-app "${TORCH_LIBRARIES}")
set_property(TARGET example-app PROPERTY CXX_STANDARD 11)

编译example-app

mkdir build
cd build
cmake -DCMAKE_PREFIX_PATH=/absolute/path/to/libtorch .. //(=后面不能有空格)
cmake --build . --config Release 或者 make

libTorch调用预训练好的模型

转换一个简单的分类模型resnet18
python代码 , 将.pth模型转为.pt模型, 环境配置 torch1.3.1 libtorch1.3.1
opencv4+

demo.py

#!/usr/bin/env python
#coding:utf-8
import torch
import torchvision
from torchvision import transforms
from PIL import Image
from time import time
import numpy as np

# An instance of your model.
model = torchvision.models.resnet18(pretrained=False)
#将模型提前下载下来, 直接加载
state_dict = torch.load('./resnet18-5c106cde.pth') 
model.load_state_dict(state_dict)
model.eval()

# An example input you would normally provide to your model's forward() method.
example = torch.rand(1, 3, 224, 224)

# Use torch.jit.trace to generate a torch.jit.ScriptModule via tracing.
traced_script_module = torch.jit.trace(model, example)
traced_script_module.save("model.pt")

# evalute time
batch = torch.rand(64, 3, 224, 224)
start = time()
output = traced_script_module(batch)
stop = time()
print(str(stop-start) + "s")

# read image
image = Image.open('cat.jpg').convert('RGB')
default_transform = transforms.Compose([
        transforms.Resize([224, 224]),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                             std=[0.229, 0.224, 0.225])
      ])
image = default_transform(image)

# forward
output = traced_script_module(image.unsqueeze(0))
print(output[0, :10])

# print top-5 predicted labels
labels = np.loadtxt('synset_words.txt', dtype=str, delimiter='\n')

data_out = output[0].data.numpy()
sorted_idxs = np.argsort(-data_out)

for i,idx in enumerate(sorted_idxs[:5]):
  print('top-%d label: %s, score: %f' % (i, labels[idx], data_out[idx]))

将.pt模型用c++调用

example-app.cpp

#include "torch/script.h"
#include "torch/torch.h" 
//#include "torch/Tensor.h" 
#include "opencv2/opencv.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/types_c.h"

#include <iostream>
#include <memory>
#include <string>
#include <vector>

/* main */
int main(int argc, const char* argv[]) {
  if (argc < 4) {
    std::cerr << "usage: example-app <path-to-exported-script-module> "
      << "<path-to-image>  <path-to-category-text>\n";
    return -1;
  }

  // Deserialize the ScriptModule from a file using torch::jit::load().
  //std::shared_ptr<torch::jit::script::Module> module = torch::jit::load(argv[1]);
  torch::jit::script::Module module = torch::jit::load(argv[1]);

  //assert(module != nullptr);
  std::cout << "load model ok\n";

  // Create a vector of inputs.
  std::vector<torch::jit::IValue> inputs;
  inputs.push_back(torch::rand({64, 3, 224, 224}));

  // evalute time
  double t = (double)cv::getTickCount();
  module.forward(inputs).toTensor();
  t = (double)cv::getTickCount() - t;
  printf("execution time = %gs\n", t / cv::getTickFrequency());
  inputs.pop_back();

  // load image with opencv and transform
  cv::Mat image;
  image = cv::imread(argv[2], 1);
  cv::cvtColor(image, image, CV_BGR2RGB);
  cv::Mat img_float;
  image.convertTo(img_float, CV_32F, 1.0/255);
  cv::resize(img_float, img_float, cv::Size(224, 224));
  //std::cout << img_float.at<cv::Vec3f>(56,34)[1] << std::endl;
  //auto img_tensor = torch::CPU(torch::kFloat32).tensorFromBlob(img_float.data, {1, 224, 224, 3});

  auto img_tensor = torch::from_blob(img_float.data, {1, 224, 224, 3}); //.permute({0, 3, 1, 2}).to(torch::kCUDA);
 
  img_tensor = img_tensor.permute({0,3,1,2}); //.to(torch::kCUDA);

  img_tensor[0][0] = img_tensor[0][0].sub_(0.485).div_(0.229);
 
  img_tensor[0][1] = img_tensor[0][1].sub_(0.456).div_(0.224);
  img_tensor[0][2] = img_tensor[0][2].sub_(0.406).div_(0.225);

  //auto img_var = torch::autograd::make_variable(img_tensor, false);
  //torch::Tensor img_var = torch::autograd::make_variable(img_tensor, false);
 
  inputs.push_back(img_tensor);
  
  // Execute the model and turn its output into a tensor.
  torch::Tensor out_tensor = module.forward(inputs).toTensor();
 
  std::cout << out_tensor.slice(/*dim=*/1, /*start=*/0, /*end=*/10) << '\n';


  // Load labels
  std::string label_file = argv[3];
  std::ifstream rf(label_file.c_str());
  CHECK(rf) << "Unable to open labels file " << label_file;
  std::string line;
  std::vector<std::string> labels;
  while (std::getline(rf, line))
    labels.push_back(line);

  // print predicted top-5 labels
  std::tuple<torch::Tensor,torch::Tensor> result = out_tensor.sort(-1, true);
  torch::Tensor top_scores = std::get<0>(result)[0];
  torch::Tensor top_idxs = std::get<1>(result)[0].toType(torch::kInt32);
  
  auto top_scores_a = top_scores.accessor<float,1>();
  auto top_idxs_a = top_idxs.accessor<int,1>();

  for (int i = 0; i < 5; ++i) {
    int idx = top_idxs_a[i];
    std::cout << "top-" << i+1 << " label: ";
    std::cout << labels[idx] << ", score: " << top_scores_a[i] << std::endl;
  }

  return 0;
}


CMakeLists.txt

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(custom_ops)

find_package(Torch REQUIRED)

find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )

add_executable(example-app example-app.cpp)
target_link_libraries(example-app ${TORCH_LIBRARIES} ${OpenCV_LIBS})
set_property(TARGET example-app PROPERTY CXX_STANDARD 11)

编译 与运行

mkdir build
cd build 
cmake -DCMAKE_PREFIX_PATH=/home/jonado/soft/libtorch/libtorch ..     
make
//运行
./example-app ../model.pt ../dog.png ../synset_words.txt 

…/model.pt 为运行demo.py程序生成的
…/dog.png 任意一张图片
…/synset_words.txt 是googlenet的synset_words.txt为分类标签, 可以在github搜索下载, 里面放的是1000个类的名称

以下为遇到的相关错误及处理:

fatal error: torch/Tensor.h: 没有那个文件或目录
屏蔽该行
//#include <torch/Tensor.h>

std::shared_ptr<torch::jit::script::Module> module = torch::jit::load("../xxx.pt");
	修改为:
torch::jit::script::Module module = torch::jit::load("../xxx.pt");

现在的Module已经不是指针,这个断言没有存在的必要了,删掉就行
	assert(module != nullptr);
torch::Tensor output = module->forward(std::move(inputs)).toTensor();
	修改为
torch::Tensor output = module.forward(std::move(inputs)).toTensor();
	
error: ‘class at::DeprecatedTypeProperties’ has no member named ‘tensorFromBlob’
   auto img_tensor = torch::CPU(torch::kFloat32).tensorFromBlob(img_float.data, {1, 224, 224, 3});

错误代码:
	auto img_tensor = torch::CPU(torch::kFloat32).tensorFromBlob(img_float.data, { 1, input_image_size, input_image_size, 3 });
原因:libtorch 1.1的接口改了,
正确代码:
	auto img_tensor = torch::from_blob(image.data, {1, inp_dim[0], inp_dim[1], 3}).permute({0, 3, 1, 2}).to(torch::kCUDA);
	
terminate called after throwing an instance of 'c10::Error' 
  what():  Must not create a new variable from a variable, use its .tensor_data() (make_variable at /home/jonado/soft/libtorch/libtorch/include/torch/csrc/autograd/variable.h:545)
frame #0: c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) + 0x6a (0x7fecf0a1dc4a in /home/jonado/soft/libtorch/libtorch/lib/libc10.so)
frame #1: torch::autograd::make_variable(at::Tensor, bool, bool) + 0x10c (0x5575108ced11 in ./example-app)
frame #2: main + 0xa76 (0x5575108c64aa in ./example-app)
frame #3: __libc_start_main + 0xe7 (0x7fecee847b97 in /lib/x86_64-linux-gnu/libc.so.6)
frame #4: _start + 0x2a (0x5575108c43aa in ./example-app)

定位错误代码行: auto img_var = torch::autograd::make_variable(img_tensor, false);
img_tensor已经是tensor类型数据了, 删掉这一行, 直接把img_tensor放入到inputs容器 inputs.push_back(img_tensor);

Ubuntu 20.04 c++ libtorch gpu Ubuntu 20.04 c++ libtorch gpu1. Install nvidia-driver, cuda, cudnn according to your system2. Download libtorch (gpu)2.1 chose suitable package based on your system2.2 extract package3. Execute c++ code3.1 Obtain "model.pt" form pytorch3.2 load "model.pt" 阅读详情

相关推荐

从零到一:Ubuntu20.04下C++与LibTorch的深度学习部署实战

本文详细介绍了在Ubuntu20.04系统下使用C++与LibTorch进行深度学习模型部署的完整流程。从环境配置、LibTorch安装验证到OpenCV集成、模型转换与部署实战,提供了全面的步骤指导和性能优化技巧,帮助开发者高效实现从Python训练到C++推理的完整链路。

weixin_29001419的博客 981

arm64平台编译libtorch

到项目编译的时候发现报错,显示应该基于lapack库编译,回看了libtorch的编译日志发现系统之前装的blas库有问题导致lapack找不到底层实现,所以编译libtorch的时候依赖lapack的部分都跳过了,重装了blas之后发现没解决问题,还是找不到blas,就换了openblas库,编译成功。编译完成后build/lib文件夹下就是编译好的库了,一起复制到项目里;复制pytorch/torch/share/cmake文件夹到libtorch/share,这是cmake的文件。

chen499093551的博客 4600

从零到一:Ubuntu20.04下LibTorch与高斯溅射的深度集成实践

本文详细介绍了在Ubuntu20.04系统下如何深度集成LibTorch与高斯溅射技术,从环境准备、CUDA配置到实战项目部署,提供了一套完整的3D场景重建解决方案。通过优化参数和性能监控,开发者可以高效实现高质量的计算机视觉应用。

ik678901234的博客 648

ARM64平台编译libtorch

Traceback (most recent call last): File "../tools/build_libtorch.py", line 14, in from tools.build_pytorch_libs import build_caffe2 File "/home/wheeltec/Documents/YOLO_ORB_SLAM3-master/Thirdparty/pytorch/tools/build_pytorch_libs.py", line

m0_66486211的博客 1534

Ubuntu 18.04下部署NVIDIA Isaac SDK 2020.2全指南

机器人AI开发离不开仿真-训练-部署闭环,而Isaac SDK正是NVIDIA面向真实机器人提供的核心工具链。其本质是深度集成CUDA加速、ROS通信与高保真物理仿真的C++系统级框架,依赖严格的Linux环境兼容性——尤其对GCC ABI、CUDA Toolkit版本、动态链接库路径等底层机制高度敏感。理解这些原理,才能规避‘CUDA version mismatch’‘libnvcuvid.so not found’等典型故障,支撑从Gazebo仿真到Jetson边缘部署的完整流程。本文聚焦Ubuntu

weixin_30872337的博客 354

第10节 libtorch与torchvision交叉编译(ARM与安卓 ios)

libtorch 编译 交叉编译 arm

全网120W+关注AI拉呱,专注人工智能以及科技前沿! 1911

ubuntu安装libtorch

nouveau是由第三方为NVIDIA显卡开发的一个开源3D驱动,ubuntu默认集成了nouveau驱动,安装NVIDIA驱动前必须禁用系统自带的显卡驱动nouveau,否则安装NVIDIA驱动时会报错。,一定要确定好安装的CUDA版本是否支持显卡的算力,否则安装成功也无法使用GPU加速。如果cmake版本低于3.18,会出现下面的报错,这是由于低于3.18的cmake不支持CUDA17的编译,需要更新cmake版本。因为安装的CUDA版本为12.1,这里选择最新版的CUDNN 9.4.0进行安装。

meng_152634的博客 2969

极智开发 | ubuntu 安装 libtorch

大家好,我是极智视界,本文介绍一下 ubuntu 安装 libtorch。

极智视界 1458

ubuntu vscode_如何在Ubuntu-18.04下用VSCode编译LibTorch

谨以此纪录环境搭建过程,以供后续参考操作系统: Ubuntu 18.04GPU: GeForce RTX 2080 CUDA 10.2:CUDA Toolkit 10.2 Download​developer.nvidia.comDriver Version: 440.44VSCode:Download Visual Studio Code - Mac, Linux, Windows​code.v...

weixin_39935777的博客 433

机器人C++开源库The Robotics Library (RL)使用手册(三)

进入VS工程,我们先看看这些功能函数及其依赖库的分布关系:rl命名空间下,主要有八大模块。搞定VS后将逐个拆解。

qq_34839823的博客 1736

高性能网站设计之缓存更新的套路

看到好些人在写更新缓存数据代码时,先删除缓存,然后再更新数据库,而后续的操作会把数据再装载的缓存中。然而,这个是逻辑是错误的。试想,两个并发操作,一个是更新操作,另一个是查询操作,更新操作删除缓存后,查询操作没有命中缓存,先把老数据读出来后放到缓存中,然后更新操作更新了数据库。于是,在缓存中的数据还是老的数据,导致缓存中的数据是脏的,而且还一直这样脏下去了。 我不知道为什么这么多人用的都是这

代码技巧 1万+

ubuntu18.04 + QT+ libtorch + GPU安装 + C++

本章内容: 1.资源下载 1.资源下载 torch官网:  https://pytorch.org/ 一键下载: wget https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-1.5.1%2Bcpu.zip 2. 解压资源 博主手动解压 3. libtorch内容 CPU版本与GPU版本所包含的文件目录一致,其中include,lib文件夹为qt所需要引用内容..

人工智能笔记 2162

推荐系统召回总结(持续更新)

推荐系统架构 候选池:可供推荐的物料候选池,对于图文、短视频、新闻等来说通常是最近N天的新物料组成的集合,定期进行物料更新。 召回:从候选池中选出和用户相关的物料,交给后面的排序模块进行打分。召回面对的候选集通常是数十万或者百万甚至千万的量级,检索过程必须轻量快速。通常由多路召回组成,保证不遗漏且相关性、多样性尽量好,可以分为非个性化召回和个性化召回。 粗排:对召回选择的几千或者几百候选物料进行排序,快速打分选出topN,减少精排的压力,兼顾精准与效率。 精排:对粗排的结果进行精准排序,这个环节需要特征尽可

whgyxy的博客 2515

vscode 跳转cuda头文件_如何在Ubuntu-18.04下用VSCode编译LibTorch

谨以此纪录环境搭建过程,以供后续参考操作系统: Ubuntu 18.04GPU: GeForce RTX 2080 CUDA 10.2:CUDA Toolkit 10.2 Download​developer.nvidia.comDriver Version: 440.44VSCode:Download Visual Studio Code - Mac, Linux, Windows​code.v...

weixin_42384743的博客 759

NE555构成多谐振荡器及三角波、正弦波的生成(附工程文件)

NE555构成多谐振荡器及三角波、正弦波的生成 续上一篇:NE555基本原理及相关公式的推导

qq_49979053的博客 5万+

ArcGIS | 全球新冠肺炎地图数据下载和处理

ArcGIS

thinkpang的博客 2901

Ubuntu 18.04下安装Isaac SDK全链路指南

Isaac SDK是NVIDIA面向机器人AI开发的系统级中间件,深度融合GPU加速推理、物理仿真与实时控制。其核心依赖于CUDA 10.2、特定版本NVIDIA驱动(≥440.33)及严格匹配的Linux内核(Ubuntu 18.04 HWE),构成典型的‘CUDA-驱动-内核’三角兼容体系。技术价值在于提供可复现的机器人感知与控制工程底座,支撑视觉避障、机械臂位姿估计等典型场景;而Docker容器化部署成为规避宿主机环境冲突、保障PyTorch 1.4.0+cu100与TensorFlow 1.15.0

weixin_30340819的博客 332

5.7 医疗 Agent 实战:构建一个懂“望闻问切”的智能医疗咨询助手

本文介绍了如何构建一个智能医疗咨询助手项目,通过LoRA微调和vLLM部署技术,将通用大模型改造为专业"AI皮肤科医生"。项目采用精简架构:Streamlit前端直接与vLLM推理服务通信,重点展示了微调模型在专业性、安全性和同理心方面的显著提升。实施步骤包括:部署微调模型、构建交互界面,并通过对比测试验证微调效果。项目强调AI仅作为咨询助手而非医生替代品,始终以引导用户寻求专业医疗帮助为核心目标,体现了负责任AI应用的关键原则。

yonggeit的博客 2962

Ubuntu 18.04 Python 3 开发环境配置:pyenv+conda 双轨隔离实践

Python 开发环境配置是软件工程的基础能力,其核心在于运行时、包管理与虚拟环境的三重隔离。在 Ubuntu 等 Linux 发行版中,系统 Python 与用户 Python 的耦合极易引发 apt 崩溃、pip 冲突和 ABI 不兼容等深层问题。pyenv 提供源码级 Python 版本控制,保障 glibc 和 OpenSSL 兼容性;conda 则通过预编译二进制提供开箱即用的科学计算栈(如 PyTorch/TensorFlow),二者协同可实现系统安全与开发敏捷的统一。该方案广泛适用于遗留服务器

weixin_30906185的博客 384

ABAP BDC 处理踩坑笔记:把错误挡在录制之前,把稳定做进每一行 BDCDATA

本文总结了SAP BDC(批输入)开发中的常见问题和解决方案。重点包括:1)理解BDCDATA本质是模拟人工操作而非直接操作数据库;2)数据格式化技巧,如金额、日期、物料号等字段的标准化处理;3)通过CTU_PARAMS参数控制执行环境,确保屏幕尺寸和更新模式一致;4)不要依赖sy-subrc,应通过解析MESSTAB消息判断业务是否成功;5)录制阶段的常见陷阱及解决方法;6)疑难问题的系统性解决思路;7)建议建立完善的错误处理机制,包括日志记录和重跑功能。文章提供了实用的ABAP代码示例和配置建议,帮助开

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 267

流媒体之LL-HLS 低延时HLS协议

LL-HLS协议通过扩展了HLS协议,为实时直播场景提供了更丰富的功能,如延迟控制、播放列表增量更新、阻止播放列表重新加载等。同时客户端可以更灵活地控制播放列表的加载和播放,以适应各种场景和需求。LL-HLS在直播中的延时可以控制在3s内, 但是即使这样, 还是不如RTMP, RTSP等协议的实时性。

技术控的笔记 3366

关于C++ libtorch调用pytorch模型的总结

最近接到了一个需求,需要把一个用python基于pytorch实现的DQN强化学习模型移植到Arm平台。 经历了很多坑,最终都解决了,记录一下过程: 环境: 系统:Ubuntu20.04 LTS; pytorch版本:1.9.0; python版本:3.8; libtorch版本:1.9; 准备步骤: ①如何安装python和pytorch请自行百度; ②进入pytorch官网,下载合适版本的libtorch https://pytorch.org/,因为我的需求是移植到Arm平台上,没有GPU以及CUDA

qq_29414731的博客 2140

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

告别Windows依赖:在Ubuntu 22.04上从零编译你的第一个LibTorch C++程序

本文详细指导如何在Ubuntu 22.04上从零开始编译并运行你的第一个LibTorch C++程序,摆脱对Windows的依赖。涵盖环境配置、LibTorch版本选择、CMake项目设置、C++代码编写及高级部署技巧,帮助开发者快速掌握深度学习在C++中的实现。

weixin_30378623的博客 646

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

Ubuntu 18.04深度学习环境搭建:cuDNN 7与NCCL 2精准配置指南

cuDNN和NCCL是GPU加速深度学习的核心底层库——前者为卷积等算子提供微架构级优化内核,后者实现GPU间零拷贝、拓扑感知的高效通信。其正确安装并非简单复制文件,而是需严格匹配CUDA版本、glibc ABI、内核模块与硬件拓扑的系统工程。在Ubuntu 18.04这一关键LTS平台上,cuDNN 7.6.5与NCCL 2.4.8构成TensorFlow 1.x和PyTorch 1.4等经典框架的稳定基线,广泛应用于ResNet、BERT等分布式训练复现。本文聚焦版本对齐原理、动态库加载机制、LD_LI

weixin_30924087的博客 445

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

YOLOv5-LibTorch使用LibTorchCAPI进行实时对象检测:高效部署YOLOv5算法

YOLOv5-LibTorch使用LibTorchCAPI进行实时对象检测:高效部署YOLOv5算法 去发现同类优质开源项目:https://gitcode.com/ YOLOv5-LibTorch项目利用LibTorch C++ API,为开发者提供了一种高效部署YOLOv5算法进行实时对象检测的方法。以下是对该项目的详细介绍、技术分析、应用场景和特点的全面解读。 项目介绍 YOLOv5-Lib...

gitblog_06738的博客 895

Ubuntu 18.04:机器人与AI开发的工业级稳定底座

Linux发行版是现代AI、机器人及边缘计算系统的底层基石,其内核版本、服务架构与软件生态共同决定系统确定性与硬件兼容性。Ubuntu 18.04搭载4.15 LTS内核,原生强化实时调度(PREEMPT_RT)、USB 3.0电源管理与GPU直通能力,成为ROS Melodic官方唯一深度适配的平台;通过systemd-resolved与cloud-init的协同,统一DNS解析与云初始化流程,显著提升Docker容器网络鲁棒性与自动化部署可靠性。其长期支持周期、ABI稳定性及对NVIDIA驱动、CUDA

weixin_30832143的博客 500
上一篇: c++ debug ubuntu 编译 /usr/bin/ld: 找不到 -lprotobuf
下一篇: torch和torchvision版本对应关系
shatule
博客等级 码龄8年 8粉丝 35原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值