protobuf反射详解

ProtoBuf-反射原理与使用 文章目录前言相关应用场景一、ProtoBuf 反射原理概述1、获取message和service的属性和方法1.1 使用protoc将proto文件生成.h和.cc文件1.2 只使用proto文件,不使用protoc进行编译1.3 非 .proto 文件 ,转换成.proto2、调用message的属性和方法2.1根据type name反射自动创建实例3、通过实例instance 的反射接口reflection对其pb字段读写获取反射Reflection接口,并且**值写入**的代码如下:线程安全二、反射. 阅读详情

本文主要介绍protobuf里的反射功能,使用的pb版本为2.6.1,同时为了简洁,对repeated/extension字段的处理方法没有说明。

最初是起源于这样一个问题:
给定一个pb对象,如何自动遍历该对象的所有字段?

即是否有一个通用的方法可以遍历任意pb对象的所有字段,而不用关心具体对象类型。 
使用场景上有很多:
比如json格式字符串的相互转换,或者bigtable里根据pb对象的字段自动写列名和对应的value。

例如定义了pb messge类型Person如下:

  1. Person person;
  2. person.set_name("yingshin");
  3. person.set_age(21);

能否将该对象自动转化为json字符串{"name":"yingshin","age":21},或者自动的写hbase里的多列:

keycolumn-namecolumn-value
uidnameyingshin
uidage21

如果设置了新的字段,比如person.set_email("izualzhy@163.com"),则自动添加新的一列:

keycolumn-namecolumn-value
uidemailizualzhy@163.com

答案就是 pb的反射功能。

我们的目标是提供这样两个接口:

  1. //从给定的message对象序列化为固定格式的字符串
  2. void serialize_message(const google::protobuf::Message& message, std::string* serialized_string);
  3. //从给定的字符串按照固定格式还原为原message对象
  4. void parse_message(const std::string& serialized_string, google::protobuf::Message* message);

接下来逐步介绍下如何实现。

1. 反射相关接口

要介绍pb的反射功能,先看一个相关的UML示例图:

pb-reflection

各个类以及接口说明:

1.1 Message

Person是自定义的pb类型,继承自Message. MessageLite作为Message基类,更加轻量级一些。
通过Message的两个接口GetDescriptor/GetReflection,可以获取该类型对应的Descriptor/Reflection。

1.2 Descriptor

Descriptor是对message类型定义的描述,包括message的名字、所有字段的描述、原始的proto文件内容等。
本文中我们主要关注跟字段描述相关的接口,例如:

  1. 获取所有字段的个数:int field_count() const
  2. 获取单个字段描述类型FieldDescriptor的接口有很多个,例如
  1. const FieldDescriptor* field(int index) const;//根据定义顺序索引获取
  2. const FieldDescriptor* FindFieldByNumber(int number) const;//根据tag值获取
  3. const FieldDescriptor* FindFieldByName(const string& name) const;//根据field name获取
1.3 FieldDescriptor

FieldDescriptor描述message中的单个字段,例如字段名,字段属性(optional/required/repeated)等。
对于proto定义里的每种类型,都有一种对应的C++类型,例如:

  1. enum CppType {
  2. CPPTYPE_INT32 = 1, //TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32
  3. }

获取类型的label属性:

  1. enum Label {
  2. LABEL_OPTIONAL = 1, //optional
  3. LABEL_REQUIRED = 2, //required
  4. LABEL_REPEATED = 3, //repeated
  5. MAX_LABEL = 3, //Constant useful for defining lookup tables indexed by Label.
  6. }

获取字段的名称:const string& name() const;。

1.4 Reflection

Reflection主要提供了动态读写pb字段的接口,对pb对象的自动读写主要通过该类完成。
对每种类型,Reflection都提供了一个单独的接口用于读写字段对应的值。

例如对于读操作:

  1. virtual int32 GetInt32 (const Message& message,
  2. const FieldDescriptor* field) const = 0;
  3. virtual int64 GetInt64 (const Message& message,
  4. const FieldDescriptor* field) const = 0;

特殊的,对于枚举和嵌套的message:

  1. virtual const EnumValueDescriptor* GetEnum(
  2. const Message& message, const FieldDescriptor* field) const = 0;
  3. // See MutableMessage() for the meaning of the "factory" parameter.
  4. virtual const Message& GetMessage(const Message& message,
  5. const FieldDescriptor* field,
  6. MessageFactory* factory = NULL) const = 0;

对于写操作也是类似的接口,例如SetInt32/SetInt64/SetEnum等。

2. 反射示例

示例主要是接收任意类型的message对象,遍历解析其中的每个字段、以及对应的值,按照自定义的格式存储到一个string中。同时重新反序列化该string,读取字段以及value,填充到message对象中。例如:

其中Person是自定义的protobuf message类型,用于设置一些字段验证我们的程序。
单纯的序列化/反序列化功能可以通过pb自带的SerializeToString/ParseFromString接口完成。这里主要是为了同时展示自动从pb对象里提取field/value,自动根据field/value来还原pb对象这个功能。

  1. int main() {
  2. std::string serialized_string;
  3. {
  4. tutorial::Person person;
  5. person.set_name("yingshin");
  6. person.set_id(123456789);
  7. person.set_email("zhy198606@gmail.com");
  8. ::tutorial::Person_PhoneNumber* phone = person.mutable_phone();
  9. phone->set_type(tutorial::Person::WORK);
  10. phone->set_number("13266666666");
  11. serialize_message(person, &serialized_string);
  12. }
  13. {
  14. tutorial::Person person;
  15. parse_message(serialized_string, &person);
  16. }
  17. return 0;
  18. }

其中Person定义是对example里的addressbook.proto做了少许修改(修改的原因是本文没有涉及pb里数组的处理)

  1. package tutorial;
  2. message Person {
  3. required string name = 1;
  4. required int32 id = 2; // Unique ID number for this person.
  5. optional string email = 3;
  6. enum PhoneType {
  7. MOBILE = 0;
  8. HOME = 1;
  9. WORK = 2;
  10. }
  11. message PhoneNumber {
  12. required string number = 1;
  13. optional PhoneType type = 2 [default = HOME];
  14. }
  15. optional PhoneNumber phone = 4;
  16. }
3. 反射实例实现
3.1 serialize_message

serialize_message遍历提取message中各个字段以及对应的值,序列化到string中。
主要思路就是通过Descriptor得到每个字段的描述符:字段名、字段的cpp类型。
通过Reflection的GetX接口获取对应的value。

  1. void serialize_message(const google::protobuf::Message& message, std::string* serialized_string) {
  2. const google::protobuf::Descriptor* descriptor = message.GetDescriptor();
  3. const google::protobuf::Reflection* reflection = message.GetReflection();
  4. for (int i = 0; i < descriptor->field_count(); ++i) {
  5. const google::protobuf::FieldDescriptor* field = descriptor->field(i);
  6. bool has_field = reflection->HasField(message, field);
  7. if (has_field) {
  8. //arrays not supported
  9. assert(!field->is_repeated());
  10. switch (field->cpp_type()) {
  11. #define CASE_FIELD_TYPE(cpptype, method, valuetype)\
  12. case google::protobuf::FieldDescriptor::CPPTYPE_##cpptype:{\
  13. valuetype value = reflection->Get##method(message, field);\
  14. int wsize = field->name().size();\
  15. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));\
  16. serialized_string->append(field->name().c_str(), field->name().size());\
  17. wsize = sizeof(value);\
  18. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));\
  19. serialized_string->append(reinterpret_cast<char*>(&value), sizeof(value));\
  20. break;\
  21. }
  22. CASE_FIELD_TYPE(INT32, Int32, int);
  23. CASE_FIELD_TYPE(UINT32, UInt32, uint32_t);
  24. CASE_FIELD_TYPE(FLOAT, Float, float);
  25. CASE_FIELD_TYPE(DOUBLE, Double, double);
  26. CASE_FIELD_TYPE(BOOL, Bool, bool);
  27. CASE_FIELD_TYPE(INT64, Int64, int64_t);
  28. CASE_FIELD_TYPE(UINT64, UInt64, uint64_t);
  29. #undef CASE_FIELD_TYPE
  30. case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
  31. int value = reflection->GetEnum(message, field)->number();
  32. int wsize = field->name().size();
  33. //写入name占用字节数
  34. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));
  35. //写入name
  36. serialized_string->append(field->name().c_str(), field->name().size());
  37. wsize = sizeof(value);
  38. //写入value占用字节数
  39. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));
  40. //写入value
  41. serialized_string->append(reinterpret_cast<char*>(&value), sizeof(value));
  42. break;
  43. }
  44. case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
  45. std::string value = reflection->GetString(message, field);
  46. int wsize = field->name().size();
  47. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));
  48. serialized_string->append(field->name().c_str(), field->name().size());
  49. wsize = value.size();
  50. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));
  51. serialized_string->append(value.c_str(), value.size());
  52. break;
  53. }
  54. case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
  55. std::string value;
  56. int wsize = field->name().size();
  57. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));
  58. serialized_string->append(field->name().c_str(), field->name().size());
  59. const google::protobuf::Message& submessage = reflection->GetMessage(message, field);
  60. serialize_message(submessage, &value);
  61. wsize = value.size();
  62. serialized_string->append(reinterpret_cast<char*>(&wsize), sizeof(wsize));
  63. serialized_string->append(value.c_str(), value.size());
  64. break;
  65. }
  66. }
  67. }
  68. }
  69. }
3.2 parse_message

parse_message通过读取field/value,还原message对象。
主要思路跟serialize_message很像,通过Descriptor得到每个字段的描述符FieldDescriptor,通过Reflection的SetX填充message。

  1. void parse_message(const std::string& serialized_string, google::protobuf::Message* message) {
  2. const google::protobuf::Descriptor* descriptor = message->GetDescriptor();
  3. const google::protobuf::Reflection* reflection = message->GetReflection();
  4. std::map<std::string, const google::protobuf::FieldDescriptor*> field_map;
  5. for (int i = 0; i < descriptor->field_count(); ++i) {
  6. const google::protobuf::FieldDescriptor* field = descriptor->field(i);
  7. field_map[field->name()] = field;
  8. }
  9. const google::protobuf::FieldDescriptor* field = NULL;
  10. size_t pos = 0;
  11. while (pos < serialized_string.size()) {
  12. int name_size = *(reinterpret_cast<const int*>(serialized_string.substr(pos, sizeof(int)).c_str()));
  13. pos += sizeof(int);
  14. std::string name = serialized_string.substr(pos, name_size);
  15. pos += name_size;
  16. int value_size = *(reinterpret_cast<const int*>(serialized_string.substr(pos, sizeof(int)).c_str()));
  17. pos += sizeof(int);
  18. std::string value = serialized_string.substr(pos, value_size);
  19. pos += value_size;
  20. std::map<std::string, const google::protobuf::FieldDescriptor*>::iterator iter =
  21. field_map.find(name);
  22. if (iter == field_map.end()) {
  23. fprintf(stderr, "no field found.\n");
  24. continue;
  25. } else {
  26. field = iter->second;
  27. }
  28. assert(!field->is_repeated());
  29. switch (field->cpp_type()) {
  30. #define CASE_FIELD_TYPE(cpptype, method, valuetype)\
  31. case google::protobuf::FieldDescriptor::CPPTYPE_##cpptype: {\
  32. reflection->Set##method(\
  33. message,\
  34. field,\
  35. *(reinterpret_cast<const valuetype*>(value.c_str())));\
  36. std::cout << field->name() << "\t" << *(reinterpret_cast<const valuetype*>(value.c_str())) << std::endl;\
  37. break;\
  38. }
  39. CASE_FIELD_TYPE(INT32, Int32, int);
  40. CASE_FIELD_TYPE(UINT32, UInt32, uint32_t);
  41. CASE_FIELD_TYPE(FLOAT, Float, float);
  42. CASE_FIELD_TYPE(DOUBLE, Double, double);
  43. CASE_FIELD_TYPE(BOOL, Bool, bool);
  44. CASE_FIELD_TYPE(INT64, Int64, int64_t);
  45. CASE_FIELD_TYPE(UINT64, UInt64, uint64_t);
  46. #undef CASE_FIELD_TYPE
  47. case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
  48. const google::protobuf::EnumValueDescriptor* enum_value_descriptor =
  49. field->enum_type()->FindValueByNumber(*(reinterpret_cast<const int*>(value.c_str())));
  50. reflection->SetEnum(message, field, enum_value_descriptor);
  51. std::cout << field->name() << "\t" << *(reinterpret_cast<const int*>(value.c_str())) << std::endl;
  52. break;
  53. }
  54. case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
  55. reflection->SetString(message, field, value);
  56. std::cout << field->name() << "\t" << value << std::endl;
  57. break;
  58. }
  59. case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: {
  60. google::protobuf::Message* submessage = reflection->MutableMessage(message, field);
  61. parse_message(value, submessage);
  62. break;
  63. }
  64. default: {
  65. break;
  66. }
  67. }
  68. }
  69. }
ProtoBuf详解 protobuf的介绍与使用 阅读详情

相关推荐

Protobuf C++ API 简介

descriptor.h #include <google/protobuf/descriptor.h> namespace google::protobuf 这个文件包含了描述protocol message类型信息的类。 关键类有: Descriptor:描述protocol message的类型信息 FieldDescriptor:描述message的某个字段 Descrip...

freshman94的博客 5323

protobuf深入讲解

工作中的总结: Protobuf是一款与平台无关、语言无关、可扩展的序列化结构数据格式。很适合用做数据存储和作为不同应用,不同语言之间进行相互通信的数据交换格式。一个proto文件可以声明多个message,在编译的时候他们将会编译成不同的类。其中每个message中声明字段的类型有required、optional 、repeated三种类型,required声明的字段其值时必须要设置的,op...

w_yqrx123的博客 1307

protobuf的静态编译及反射的使用示例

protobuf编译、protobuf反射运用、完整代码

li__________的博客 1672

C++ protobuf反射特征工程正确姿势

搞定这篇protobuf反射不用愁

qq_18447271的博客 2030

Google Protobuf自动反射功能

Google Protobuf自动反射功能

chenglinhust的专栏 5006

protobuf反射机制

参考: https://xiongjun.info/2016/02/16/mqueue4/ http://blog.csdn.net/solstice/article/details/63001081. 网络编程中使用protobuf的两个问题Google Protocol Buffers (Protobuf) 是一款非常优秀的库,它定义了一种紧凑的可扩展二进制消息格式,特别适合网络数据传输。它

yvhqbat的博客 3053

ProtoBuf 反射详解

Protocol Buffer 简称 ProtoBuf,是用于结构化数据串行化的灵活、高效、自动的方法,又如 XML,不过它更小、更快、也更简单。你可以定义自己的数据结构,然后使用代码生成器生成的代码来读写这个数据结构。你甚至可以在无需重新部署程序的情况下更新数据结构。 本文主要介绍 protobuf 里的反射功能,使用的pb版本为2.6.1,同时为了简洁,对 repeated/extensio...

2246

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;...

小米的修行之路 3709

ProtoBuf(Google Protocol Buffers)—— 反射原理以及反射具体流程介绍

ProtoBuf—— 反射原理解析ProtoBuf—— 反射原理1、反射原理1.1、反射机制的背景1.2、定义1.3、反射原理关注的一些问题1.4、反射原理的优势和应用2、ProtoBuf反射原理——获取并改造 元信息2.1 、 .proto 文件2.2 、 反射原理过程2.3 、 反射相关的类和API2.3.1、google::protobuf::Message2.3.2、 google::protobuf::Descriptor2.3.3、 google::protobuf::Reflection2.

JMW1407的博客 7846

【asrpro语音模块+语音控制小风扇】

智能语音控制小风扇,使用ASRPRO语音模块只要一句话就能设置小风扇不同挡位的风力。图形化编程简单有效的控制输出PWM的占空比。

qq_57234300的博客 1万+

STM32 上 FreeRTOS 的启动与任务调度详解

4. SysTick定时器:FreeRTOS启动调度器后,会接管STM32的SysTick定时器,用于生成系统节拍,因此不要在HAL库中重复配置SysTick(比如HAL_Init()中已配置,无需再手动调用SysTick_Config()),否则会导致系统节拍异常,任务延迟不准。2. 任务栈大小需按需配置,不是越大越好(浪费RAM),也不能太小(会导致栈溢出),比如简单的传感器读取任务,1024字(4096字节)足够,复杂任务(比如串口接收+数据解析)可调整为2048字。

qq_40170041的博客 873

protobuf java 自动反射_深入 ProtoBuf - 反射原理解析

在介绍了 ProtoBuf 序列化原理之后,本文介绍 ProtoBuf 的反射技术原理。反射技术简介对于反射大家应该不会陌生,如果你接触过一些框架(如 ORM、IOC、OSGi 等) 的内部实现,应该更能体会反射技术的应用可谓无处不在。笔者读研期间所在实验室的核心技术并与反射息息相关,在反射基础之上衍生出了许多非常有趣的应用。关于反射可讲的东西很多,后续想单独写一篇文章介绍,这里先只做一个简介。反...

weixin_27427619的博客 777

PX4实战(一):PX4简介及系列文档目录

PX4从入门到精通第一篇,讲解PX4软件的作用、软件下载、环境搭建、软件架构,后续代码讲解计划等。

PX4-SLAM-PNC 6192

protobuf java 反射

需求: 线上需要一份数据,这份数据是存储在hbase中的(比如对于某一个实体,其各个字段是存储在hbase的各个列的)。而希望最终导出的文件的每一行是一个 protobuf 的message,以方便解析和维护。 具体做法: 定义一个 protobuf  message,其各个 field 的名字与 hbase 各列的 key 的名字对应,将 hbase 中各列对应的 value 取出来,填充

5569

华为OD机试真题-查找单入口空闲区域(Py/Java/C/C++/Js/Go)

华为OD机试(机考)双机位C卷 【查找单入口空闲区域】,提供Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,以及在线OJ模拟做题。华为OD机试 - 查找单入口空闲区域。

qq_45776114的博客 1276

OpenDataLab 大模型训练数据集下载记录

大模型 训练数据集

u013558123的博客 3504

protobuf java 自动反射_protobuf通过反射来赋值

最近因为项目逻辑方面都做的差不多了,于是赶紧去做做测试工作,免得项目上线之后出问题,于是打算用配置的形式做一个类似与白盒测试工具的东西出来。因为项目使用pb来做协议通讯,所以配置的xml也是类似于pb,将pb的字段和类型配置进去,然后加上值,一个协议结构就可以了,现在只能通过修改值来做测试,后面会改动的更智能化一些,例如某个行为的次数,某个行为更随机等等。去读了一下陈硕的关于pb处理协议的反射,学...

weixin_29686935的博客 987

第32篇:Vibe Coding时代:LangGraph + Redis 任务状态持久化实战,解决服务重启后任务状态丢失问题

LangGraph + Redis任务状态持久化方案 本文针对Agent任务状态丢失问题,提出基于Redis的持久化解决方案。当服务重启时,传统内存存储方式会导致任务状态丢失,影响用户体验和运维排查。 核心方案 使用Redis Hash存储任务状态,key格式为agent:task:{task_id} 设计完整状态字段包括task_id、status、progress等关键信息 实现task_store模块提供CRUD操作接口 在Agent执行各节点更新Redis中的任务状态 技术实现 通过Celery执行

sundong_81的博客 49

Protobuf 反射技术简介

* 反射创建实例 *//* 反射相关接口 */reflecter->SetString(&instance, field, "鸡你太美");// 获取属性的值.return 0;利用上述 ProtoBuf 的反射能力,我们将能够实现许多强大的功能。例如各种 pb2json 库底层多是利用 ProtoBuf 的反射能力,实际上ProtoBuf 自身对编码结果反序列化并构建内存对象的过程用的也正是反射。获取程序元信息。

谢谢大家的关注 1554

芯片验证 | FPGA 原型验证

一文带你搞定FPGA 原型验证

叫好与叫座虽然不是对立面,但想在同一个作品中达到双重效果很难。 1576

51单片机+L298驱动步进电机+L297测速+LCD1602显示+按键调试+Proteus仿真

51单片机+L298驱动步进电机+L297测速+LCD1602显示+按键调试+Proteus仿真 *Proteus仿真 L298N是双H桥式驱动器。 L297是步进电机控制集成芯片(包括环形分配器),可产生四相驱动信号,应用于微处理机控制两相双极性和四相单极性步进电机。电动机可由半阶梯、正常和斩波驱动模式驱动,同时设于晶片内的PWM斩波线路容许以开关形式控制线路的电流。此器件只需要时钟、方向和模式输入信号。相位是由内部产生的,因此可减轻微处理机和程序设计的负担。 实例代码 /************

perseverance51博客 4589

深入 ProtoBuf - 反射原理解析

在介绍了 ProtoBuf 序列化原理之后,本文介绍 ProtoBuf 的反射技术原理。 反射技术简介 对于反射大家应该不会陌生,如果你接触过一些框架(如 ORM、IOC、OSGi 等) 的内部实现,应该更能体会反射技术的应用可谓无处不在。 笔者读研期间所在实验室的核心技术并与反射息息相关,在反射基础之上衍生出了许多非常有趣的应用。关于反射可讲的东西很多,后续想单独写一篇文章介绍,这里先只做一个简介。 反射概念最早出现于人工智能领域,20 世纪 70 年代末被引入到程序语言设计中。1982 年 MI

iopoint的专栏 909

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

protobuf 反射使用总结

protobuf 反射使用总结

编程猿来如此 2058

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

protobuf C++ 利用反射获取消息内容

protobuf经常会被大家使用,下面演示一下protobuf反射的使用。 void PrintProtoMsg(const google::protobuf::Message& message) { const google::protobuf::Descriptor *des = message.GetDescriptor(); const google::protobuf::Reflection *ref = message.GetReflection(); int

veghlreywg的博客 3623

深度学习工具包 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")

上一篇: tensorflow compile
下一篇: ffmpeg 编译
chary8088
博客等级 码龄23年 330粉丝 150原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值