ProtoBuf

Protobuf使用实例 前面章节已经讲述了protobuf的理解,这里直接开门见山,给出一个实,来具体看下是如何使用的。 本案例参考博客: google protobuf安装与使用 案例的主要功能(google提供的基本案例) 该程序示例的大致功能是,定义一个Persion结构体和存放Persion的AddressBook,然后一个写程序向一个文件写入该结构体信息,另一个程序从文件中读出该信息并打印到输出中。 1.add... 阅读详情

ProtoBuf简述

protocol buffers 是一种语言无关、平台无关、可扩展的序列化结构数据的方法,可用于通信协议、数据存储等。

使用流程:

  1. 创建 .proto 文件,定义数据结构
  2. 编译 .proto文件生成接口
  3. 调用接口实现序列化、反序列化以及读写

安装

不同版本的protobuf无法互相兼容,ROS安装时会一并安装,路径为/usr/bin/protoc,若需要依赖其他版本可安装在不同路径下

  1. 安装依赖 sudo apt-get install autoconf automake libtool curl make g++

  2. 生成Makefile ./autogen.sh && ./configure

    如需多版本并存或修改安装路径,可设置目录/configure --prefix=/usr/protobuf

  3. 检查编译结果 make check

  4. 安装到系统路径下 sudo make install

  5. 设置系统环境

    单版本安装

    Ubuntu默认安装在/usr/local/lib目录下

    • 创建文件 sudo gedit /etc/ld.so.conf.d/libprotobuf.conf
    • 填入内容 /usr/local/lib(若修改了路径,使用修改过的)
    • 更新 sudo ldconfig

    多版本安装

    • 创建软链接 sudo ln -s /usr/protobuf/bin/protoc /usr/local/bin/protoc3.6
    • 更新sudo ldconfig
  6. 测试 protoc --version

ProtoBuf语法

  • 定义结构体

    • message <name> {}
    • 结构体语法 : 字段规则 类型 名称 = 字段编号
    message Person {
      string name = 1;
      int32 id = 2;
      string email = 3;
      }
    
  • 定义枚举

    • enum <name> {}
    • 枚举语法 : 名称 = 枚举编号
    • 枚举常量值必须在32位整数范围内,负值无效
      enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
      }
    
  • 字段规则

    注意:proto3已舍弃required字段,optional字段也无法显示使用(因为缺省默认就设置为optional),同时弃用默认值设置,默认值大多为0、空、false。

    • proto2
      • [default = XXX] 设置默认值
      • required 字段只能也必须出现1次
      • optional 字段可出现0次或1次
      • repeated 字段可出现任意多次(包括 0),[packed = true]选项可提高编码效率
    • proto3
      • singular 字段可出现0个或1个该字段。这是 proto3 语法的默认字段规则,一般无需声明
      • repeated 字段可出现任意多次(包括 0),可视为动态大小的数组
    • reserved 字段设置为保留项,主要用于已经删除字段的禁用
  • 字段类型

    protobuf属性C++属性备注
    boolbool
    stringstring一个字符串必须是utf-8编码或者7-bit的ascii编码的文本,长度不能超过 2^32
    bytesstring可能包含任意顺序的字节数据,但长度不能超过 2^32
    doubledouble固定8个字节
    floatfloat固定4个字节
    int32int32使用变长编码,对于负数编码效率较低,如果经常使用负数,建议使用sint32
    int64int64使用变长编码,对于负数编码效率较低,如果经常使用负数,建议使用sint64
    uint32uint32使用变长编码
    uint64uint64使用变长编码
    sint32int32使用变长编码,符号整型。负值的编码效率高于常规的 int32 类型
    sint64int64使用变长编码,符号整型。负值的编码效率高于常规的 int64 类型
    fixed32uint32定长4字节,如果数据>2^28,编码效率高于unit32
    fixed64uint64定长8字节,如果数据>2^56,编码效率高于unit64
    sfixed32int32总是4字节
    sfixed64int64总是8字节
  • 字段编号

    • 0 ~ 536870911(除去 19000 到 19999 之间的数字)
    • 标签号1-15比起更大数字需要少一个字节进行编码,可将常用或重复的元素设置为此类标签

ProtoBuf生成

通过命令

protoc -I=<SRC_DIR> --cpp_out=<DST_DIR> <SRC_DIR>/xxx.proto

  • SRC_DIR: .proto所在的源目录
  • –cpp_out: 生成c++代码
  • –python_out:生成python代码,_pb2.py文件
  • DST_DIR: 生成代码的目标目录
  • xxx.proto: 要针对哪个proto文件生成接口代码
# 寻找 Protobuf 库
find_package(Protobuf REQUIRED)

# 生成protobuf的lib
file(GLOB PROTO_LIST "proto/*.cc")
add_library(proto
  STATIC
    ${PROTO_LIST})
target_include_directories(proto PUBLIC ${PROTOBUF_INCLUDE_DIRS})
target_link_libraries(proto PUBLIC ${PROTOBUF_LIBRARIES})

# 链接执行文件
add_executable(protobuf_test 
    src/protobuf_test.cpp)
target_include_directories(protobuf_test PUBLIC ${PROJECT_SOURCE_DIR}/proto)
target_link_libraries(protobuf_test proto)

通过CMake

自动生成对应的C++头文件和源文件

protobuf_generate_cpp (<SRCS> <HDRS>
    [DESCRIPTORS <DESC>] [EXPORT_MACRO <MACRO>] [<ARGN>...])
  • SRCS Variable to define with autogenerated source files
  • HDRS Variable to define with autogenerated header files
  • DESCRIPTORS Variable to define with autogenerated descriptor files, if requested.
  • EXPORT_MACRO is a macro which should expand to __declspec(dllexport) or __declspec(dllimport) depending on what is being compiled.
  • ARGN .proto files

protobuf消息编译库proto,后续调用直接使用该库即可。

project(proto)

# 寻找 Protobuf 库
find_package(Protobuf REQUIRED)

# 检测是否找到 Protobuf
if(PROTOBUF_FOUND)
  message("** protobuf found")
else()
  message(FATAL_ERROR "Cannot find Protobuf")
endif()

# 寻找所有的proto文件
file(GLOB PROTO_FILES ${PROJECT_SOURCE_DIR}/*.proto)
message("** PROTO_FILES = ${PROTO_FILES}")
# Generate the .h and .cxx files 必须配合 add_executable() 或者 add_library() 才能正常使用
protobuf_generate_cpp(PROTOBUF_SRCS PROTOBUF_HDRS ${PROTO_FILES})

# 增加 proto 描述文件的静态库
add_library(${PROJECT_NAME} STATIC ${PROTOBUF_SRCS} ${PROTOBUF_HDRS})
target_include_directories(${PROJECT_NAME} PUBLIC ${PROTOBUF_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} PUBLIC ${PROTOBUF_LIBRARIES})

接口调用

构造protobuf数据

在生成的C++接口内,会根据设置数据类型生成对应的函数接口,singular(单组数据)和repeated(多组数据)定义的类型生成的api存在差异。

singular

  • double/int

    // double x = 1;
    void clear_x();
    static const int kXFieldNumber = 1;
    double x() const;
    void set_x(double value);
    
    // int32 id = 2;
    void clear_id();
    static const int kIdFieldNumber = 2;
    ::google::protobuf::int32 id() const;
    void set_id(::google::protobuf::int32 value);
    
  • bytes/string

    在C++中bytes和string的实现都是std::string类型,区别在于string类型序列化调用了VerifyUTF8StringNamedField函数检验string中是否有非法的UTF-8字符,而bytes类型没有检验。

    string类型不能直接通过set赋值,需设置string变量后,将string变量通过set进行赋值。

    // bytes data = 1;  
    void clear_data();
    static const int kDataFieldNumber = 1;
    const ::std::string& data() const;
    void set_data(const ::std::string& value);
    #if LANG_CXX11
    void set_data(::std::string&& value);
    #endif
    void set_data(const char* value);
    void set_data(const void* value, size_t size);
    ::std::string* mutable_data();
    ::std::string* release_data();
    void set_allocated_data(::std::string* data);
    
  • 嵌套message

    // .test.test_2_msg c = 3;
    bool has_c() const;
    void clear_c();
    static const int kCFieldNumber = 3;
    const ::test::test_2_msg& c() const;
    ::test::test_2_msg* release_c();
    ::test::test_2_msg* mutable_c();
    void set_allocated_c(::test::test_2_msg* c);
    

    通过set_allocated_和mutable_传入已定义值,在关闭程序时会引起的double free core dump,参考c++ Protobuf中set_allocated引起的double free core dump

    正确定义:

    int good_case1(){
        a* aa = new a();
        b bb;
        aa->set_aa(1);
        bb.set_allocated_aaa(aa);
        return 0;
    }
    
    void good_case2(){
        a aa;
        b bb;
        aa.set_aa(1);
        bb.mutable_aaa()->MergeFrom(aa);
    }
    
  • descriptor

    #include <google/protobuf/message.h>
    namespace google::protobuf
    
    const Descriptor* descriptor = msg->GetDescriptor();
    

repeated

  • double/int

     // repeated int32 e = 5;
     int e_size() const;
     void clear_e();
     static const int kEFieldNumber = 5;
     ::google::protobuf::int32 e(int index) const;
     void set_e(int index, ::google::protobuf::int32 value);
     void add_e(::google::protobuf::int32 value);
     const ::google::protobuf::RepeatedField< ::google::protobuf::int32 >&
         e() const;
     ::google::protobuf::RepeatedField< ::google::protobuf::int32 >*
         mutable_e();
    
  • 嵌套message

      // repeated .test.test_2_msg d = 4;
      int d_size() const;
      void clear_d();
      static const int kDFieldNumber = 4;
      ::test::test_2_msg* mutable_d(int index);
      ::google::protobuf::RepeatedPtrField< ::test::test_2_msg >*
          mutable_d();
      const ::test::test_2_msg& d(int index) const;
      ::test::test_2_msg* add_d();
      const ::google::protobuf::RepeatedPtrField< ::test::test_2_msg >&
          d() const;
    

序列化和反序列化

调用接口实现序列化、反序列化以及读写

  • 序列化

    • bool SerializeToString(string* output) const

      序列化消息并将字节存储在给定的字符串中。请注意,字节是二进制的,而不是文本,只是使用 string 类作为容器。

      文件中显示为乱码,通过gedit修改会损坏数据,可以通过vim修改。

    • bool SerializeToOstream(ostream* output) const

      将message写入给定的C++的ostream

  • 反序列化

    • bool ParseFromString(const string& data)

      解析给定字符串到message

    • bool ParseFromIstream(istream* input)

      解析给定C++ istream到message

参考

[翻译] ProtoBuf 官方文档(一)- 开发者指南

语言指导(proto3)

[翻译] ProtoBuf 官方文档(九)- (C++开发)教程

Protocol Buffer Basics: C++

CMake 生成 ProtoBuf

[转]Protobuf3 语法指南

Ubuntu18.04同时安装两个版本的protobuf(protoc)

UE4接入protobuf 准备 UE4.25.4:当前最新版本 protobuf:3.11.2(为什么选择这个版本呢,因为最新的3.14不兼容,至少我不知道怎么做兼容,没尝试其他版本,有兴趣的可以自己试一下更高版本) 步骤 1.下载protobuf3.11.2,https://github.com/protocolbuffers/protobuf/releases?after=v3.12.4 2.解压后修改源码(下面代码块里+的意思是加入后面的信息,+本身不拷贝进去) src/google/protobuf/compiler/cp 阅读详情

相关推荐

cmake 中使用 protobuf 生成文件

protobuf 提供了自动生成文件的功能,我直接看的cmake文件,里面没说函数说明,我没有全部弄明白,但可以正常使用: add_library(myTarget ${src}) protobuf_generate( TARGET myTarget EXPORT_MACRO myExports PROTOC_OUT_DIR ${CMAKE_CURRENT_SOURCE_...

LaineGates的专栏 4592

不同版本的protobuf版本兼容

不同版本的protobuf版本兼容,可以修改不同版本的文件名(确保生成的类名不一致),修改probuf包路径,这样内部的。代码中用try catch兼容即可。同名message不会冲突。

yuhui666666的博客 2488

升级Golang中Protobuf的一些注意事项

Protobuf的新版本可能引入了一些不兼容的更改,这可能会导致代码中的问题。因此,在升级之前,建议仔细查阅Protobuf的更新日志和版本迁移指南,以了解潜在的兼容性问题。升级Golang中的Protobuf可能会带来一些挑战,但通过遵循上述注意事项,你应该能够顺利进行升级。记住,在升级之前,仔细查阅文档,了解新版本的更改和兼容性要求,并测试你的代码以确保一切正常运行。命令行工具和相应的插件来生成Protobuf代码。确保使用与新版本Protobuf兼容的插件版本,并检查生成的代码是否与你的预期一致。

ZwqDatabase的博客 742

CMake使用protobuf生成c++代码

目录标题CMake编译protobuf生成c++代码1. protobuf_generate_cpp生成源码2.使用execute_process命令生成源码3.使用add_custom_target与add_custom_command生成源码4.总结 CMake编译protobuf生成c++代码 本文为个人使用cmake编译protobuf生成源码的经验总结,下面将介绍三种生成protobuf源码的cmake编写方式 1. protobuf_generate_cpp生成源码 cmake提供了FindPr

qq_37868450的博客 1万+

protobuf深坑-版本冲突-彻底解决

由于安装了anaconda ,caffe,后面又安装了pytorch,mmdetection,tensorboardX,导致环境中protoc和protobuf相当混乱 后面在编译caffe的时候,已经编辑不过去了。 1:一般protobuf安装有3种方式 apt-get install libprotobuf-dev protobuf-compiler[安装在系统] pip i...

微风❤水墨 1万+

protobuf-使用protobuf的反射来生成Message并赋值

1、测试用例: syntax = "proto2"; package dong; message PersonInfo{ required string name = 1; required uint32 age = 2; required uint32 phone_num = 3; } message Person{ repeated PersonInfo people = 1;...

小米的修行之路 3706

[C++][ProtoBuf][初识ProtoBuf]详细讲解

[C++][ProtoBuf][初识ProtoBuf]详细讲解

SnowK博客 4549

protobuf的安装与使用–版本不兼容问题

1.安装(使用3.4.1版本) 1.1下载并解压缩 地址:https://github.com/google/protobuf/releases/download/v3.4.1/protobuf-cpp-3.4.1.tar.gz 1.2.安装(先cd probuf-3.4.1进入目录下,再执行以下命令) 1.2.1默认安装步骤(需root权限):(不采用此种方法,因为会与ROS中的老版本的protobuf产生冲突) $ ./autogen.sh ##下载自github的代码需要执行此行来生成configure文件 $ ./configure $ make $ make check $

【CMake/Protobuf】CMake 下使用 protobuf

两个或多个proto文件不在一个目录,如果直接使用protobuf_generate_cpp来生成,直接会报错。 若将多个proto文件放到同一个目录...然后import proto文件名即可,虽然这样可以,但显然是不适合大型的项目,那如何解决此类问题可参考本文

gcs_20210916的博客 1万+

Intel RealSense D435 深度相机详解

Intel RealSense D435 深度相机是 Intel 推出的一款基于深度感知技术的相机,广泛应用于机器人、无人机、增强现实(AR)、虚拟现实(VR)、3D扫描、智能监控等领域。D435 是 RealSense 系列中较为高端的深度相机之一,结合了深度传感和 RGB 摄像技术,为用户提供高精度的深度数据和高质量的图像捕捉能力。

crasher123的博客 2965

问题:dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)

 1. 问题:Ubuntu安装软件的过程中出现依赖项的问题 “E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).” 按照指示执行如下两条命令都没有解决问题。 sudo apt-get -f install sudo apt-get --fix-broken ...

gloria_littlechi的博客 2万+

[C++][ProtoBuf][ProtoBuf上手]详细讲解

[C++][ProtoBuf][ProtoBuf上手]详细讲解

SnowK博客 5399

全网最详细单细胞保姆级分析教程(一) ---pbmc

通过观察热图,可以了解不同细胞在主成分上的分布情况,以及主成分与细胞特征之间的关系。数据归一化是数据分析中的常见步骤,旨在消除数据集中不同特征之间的量纲差异,并使它们在相同的尺度上进行比较。函数会根据指定的主成分维度计算数据点之间的距离,并找到每个数据点的邻居。函数会根据数据点之间的相似性将其分组到不同的聚类中。数据缩放是数据分析中的常见步骤,旨在将数据的特征值调整到相似的范围,以避免某些特征对分析结果的过度影响。通过可视化维度载荷,可以了解哪些特征对主成分的形成起到了重要作用,以及不同特征之间的相关性。

ZxVSaccount的博客 6716

protobuf service详解

这里写目录标题定义serviceUserServiceRpc类 和 UserServiceRpc_stub类UserServiceRpc类成员分析 定义service .proto文件的代码如下: syntax = "proto3"; // 声明了protobuf的版本 package fixbug; // 声明了代码所在的包(对于C++来说是namespace) //定义下面的选项,表示生成service服务类和rpc方法描述,默认不生成 option cc_generic_services = tr

TABE_的博客 8611

【深度排查】VScode 远程 SSH 连接失败:从网络握手到服务部署的全链路诊断指南

本文详细解析了VScode远程SSH连接失败的常见原因及解决方案,从基础网络排查到SSH服务配置,再到VScode特有的问题处理。特别针对Ubuntu和TrueNAS系统提供了具体配置建议,帮助开发者快速解决'Could not establish connection'等连接问题,提升远程开发效率。

weixin_30301449的博客 449

如何用 Claude Code 做大型项目重构与架构优化

本文介绍了如何利用Claude Code参与大型项目重构。文章指出,大型项目重构的最大难点在于理解系统结构和控制风险,而非单纯修改代码。作者提出了五步重构法:首先分析项目结构,其次梳理模块依赖关系,然后发现架构问题,接着设计分阶段重构方案,最后逐步实施。重点强调了Claude Code的核心价值在于帮助开发者理解复杂系统、分析模块依赖、发现结构问题、评估改动风险,而非仅作为代码生成工具。文章建议将Claude Code作为架构助手,通过分阶段小范围重构来降低风险,而非一次性全面重构。

sg_knight的专栏 1579

【cmake】利用cmakeList链接protobuf

利用cmakeList链接protobuf include(FindProtobuf) find_package(Protobuf REQUIRED "2.5.0") if (Protobuf_FOUND) # 需要特别注意Protobuf_FOUND的大小写 INCLUDE_DIRECTORIES(${PROTOBUF_INCLUDE_DIR}) else (Protobuf_F...

远方不远 6593

FFTW3库在Windows中的安装和使用

Windows 32位平台下载:FFTW Installation on Windows。

weixin_45397344的博客 955

protobuf 安装笔记

protobuf xls2protobuf不是c++用的,python整理表格的 https://github.com/JumboWu/xls2protobuf

jacke121的专栏 2863

npm install 时出现npm error code ENOTFOUND和npm error network request to https://registry.npmjs.org的解决方案

本文主要介绍了npm install 时出现npm error code ENOTFOUND和npm error network request to https://registry.npmjs.org 的解决方案,希望能对使用npm的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 6万+

uniapp微信小程序 - 解决输入框input软键盘弹起时页面整体上移问题,页面上推导致顶部出现元素遮挡问题,uniapp软键盘导致页面上移头部内容被错位遮住错乱,让页面头固定在顶部不动不会受影响!

解决uni-app微信小程序底部input输入框,键盘弹起时页面整体上移问题,当键盘弹起时,会导致页面整体上移,页面头固定在顶部不动,微信小程序键盘弹起时,底部输入框抬起至键盘上方,顶部导航栏固定不动,uni-app输入框,输入框在底部;当弹出键盘时,页面整体上移,页面头信息会消失不见,小程序底部input输入框,input组件弹起系统键盘时,键盘会顶住页面导致页面会上移,当键盘弹起时整个页面被挤压,导致元素上移或被覆盖,输入框能自动抬起至键盘上方,顶部导航栏保持固定,不被顶上去,如何解决这个问题,动态高度

✅ 精选推荐文章 1万+

【ProtoBuf】了解ProtoBuf和安装ProtoBuf

ProtoBuf

加油,考上985的研究生 2207

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

《Protobuf 通讯录开发》

使用 Protocol Buffers(Protobuf)来构建通讯录,能够高效地进行结构化数据的存储与传输。下面从消息定义、代码生成、不同语言实现以及调试和优化方面,为你详细介绍如何实现一个基于 Protobuf 的通讯录:

fwfxhhx的博客 1094

深度学习工具包 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'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('DeepLearnToolbox'));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('state',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'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',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 = 'sigm';%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, 'Too big error');```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('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';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)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';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, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% 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'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 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, 'Too big error');```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('state',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, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',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, 'Too big error');%% ex3 neural net with dropoutrand('state',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, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % 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, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % 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, 'Too big error');%% 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('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % 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, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

protobuf序列化

debug是在开发过程中使用的release是在发行的时候使用的在release模式下打断点不停。

m0_69093426的博客 1235

protobuf协议_protobuf 异常死锁分析

最近在开发中,有个模块在测试时偶尔会出现卡死现象,进程状态处于futex状态。网络搜索发现这种状态下,进程大概率发生了死锁。 在开发中,死锁并不陌生。只要能有堆栈就很容易解决。使用stace 命令发现进程处于FUTEX_WAIT_PRIVATE 状态,明确发生了死锁。strace-p+进程ID接下来要需要gdb分析进程的堆栈,明确出现死锁的原因。可以使用gdb ...

weixin_39778150的博客 775

Qt使用protobuf笔记

解决使用protobuf库过程中出现的编译问题。protobuf和XML,json一样的数据结构。

Qt君 2488
上一篇: 运动控制——模型预测控制MPC
下一篇: ROS基础——命令
white_Learner
博客等级 码龄10年 1430粉丝 74原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值