Ring0 inline hook For Delphi.

深入解析Ring3环境下Inline Hook绕过技术与Delphi实战 htmltable {th, td {th {pre {简介:在Windows系统中,Ring3即用户模式,是应用程序运行的常规环境,而Inline Hook作为一种常见的调试与监控手段,通过修改函数入口指令实现控制流劫持,广泛应用于恶意软件分析、逆向工程等领域。本文深入探讨在Ring3下如何有效绕过Inline Hook机制,并结合提供的Delphi源码进行技术剖析。 阅读详情
内嵌钩子呀内嵌钩子呀...
一般两种方法...
[1]jmp
0.获取一个足够的长度...Copy原来的数据保存到一个地方
1.jmp 长跳转到HookProc部分
2.处理完毕后跳转到...会原来抽取的代码...
3.执行完毕后再jmp回到原有指令
[2]返回地址...push xxx+ret
[3]这个是为了bypass某些检测工具---小跳一下...然后大跳一下(抱歉不是CS)
[4]其他跳转法...你喜欢玩EPO吗?呵呵

这里用第二种方法---抱歉我不想别人说我抄袭Ms-Rem的代码...
Copy code
{
  Hook Api Library 0.2 [Ring0] By Anskya
  Email:Anskya@Gmail.com
  ring3 inline hook For Api

Thank:
  前29A高手也一直都是我的偶像...z0mbie大牛...这里膜拜一下
  使用的LDE32引擎是翻译他老人家的...C->Delphi...

说明:
  1.利用堆栈跳转
  没有使用传统的jmp xxxx 长跳转,使用容易理解的push xxxx+ret
  仔细看代码容易理解...封装完好.

  2.内存补丁结构:
  补丁1:|push xxx--钩子处理过程|ret|
  补丁2:|保存原始补丁地址|保存原始地址代码长度|原始地址的代码|push xxxxxx|ret|

更新说明:
  0.2:
    支持Ring0 Inline Hook
  0.1:
    Ring3 Inline Hook
}
unit HookApiLib;

interface

{$DEFINE Ring0}

uses
  LDE32,
{$IFDEF Ring0}
  ntddk,
  macros
{$ELSE}
  Windows
{$ENDIF}
  ;

function HookCode(OldProc, NewProc: Pointer): Pointer;
function UnHookCode(TargetProc: Pointer): Boolean;

implementation

type
  LPfar_jmp = ^_far_jmp;
  _far_jmp = packed record
    PushOpCode: BYTE;
    PushArg: Pointer;
    RetOpCode: BYTE;
  end;
  Tfar_jmp = _far_jmp;

function HookCode(OldProc, NewProc: Pointer): Pointer;
var
  lpFuncProc, lpInlineProc: Pointer;
  InlineLen, OpcodeLen: ULONG;
  stfar_jmp_hook: Tfar_jmp;
{$IFNDEF Ring0}
  OldProtect: ULONG;
{$ENDIF}
begin
  Result := nil;
  if ((OldProc = nil) or (NewProc = nil)) then Exit;

  InlineLen := 0;
  lpFuncProc := OldProc;

  while (InlineLen < SizeOf(Tfar_jmp)) do
  begin
    GetInstLenght(lpFuncProc, @OpcodeLen);
    lpFuncProc := Pointer(ULONG(lpFuncProc) + OpcodeLen);
    InlineLen := InlineLen + OpcodeLen;
  end;

  stfar_jmp_hook.PushOpCode := $68;
  stfar_jmp_hook.PushArg := NewProc;
  stfar_jmp_hook.RetOpCode := $C3;

{$IFDEF Ring0}
  lpInlineProc := ExAllocatePoolWithTag(NonPagedPool, 8 + InlineLen  + SizeOf(Tfar_jmp), PoolWithTag);
{$ELSE}
  lpInlineProc := Pointer(GlobalAlloc(GMEM_FIXED, SizeOf(Pointer) + SizeOf(ULONG) + InlineLen  + SizeOf(Tfar_jmp)));
{$ENDIF}

  if (lpInlineProc = nil) then Exit;
 
  PPointer(lpInlineProc)^ := OldProc;
  Inc(PBYTE(lpInlineProc), SizeOf(Pointer));

  PULONG(lpInlineProc)^ := InlineLen;
  Inc(PBYTE(lpInlineProc), SizeOf(ULONG));

{$IFDEF Ring0}
  memcpy(lpInlineProc, OldProc, InlineLen);
{$ELSE}
  CopyMemory(lpInlineProc, OldProc, InlineLen);
{$ENDIF}
  Inc(PBYTE(lpInlineProc), InlineLen);
  //  改写跳转代码
  with LPfar_jmp(lpInlineProc)^ do
  begin
    PushOpCode := $68;
    PushArg := Pointer(ULONG(OldProc) + InlineLen);
    RetOpCode := $C3;
  end;

{$IFDEF Ring0}
  //  开始嵌入Hook
  if NT_SUCCESS(WriteReadOnlyMemoryMark(OldProc, @stfar_jmp_hook, SizeOf(Tfar_jmp))) then
  begin
    Result := Pointer(ULONG(lpInlineProc) - InlineLen);
  end else
  begin
    ExFreePoolWithTag(lpInlineProc, PoolWithTag);
    Result := nil;
  end; 
{$ELSE}
  //  使内存可写
  VirtualProtect(OldProc, SizeOf(Tfar_jmp), PAGE_EXECUTE_READWRITE, OldProtect);
  //  写入跳转代码
  CopyMemory(OldProc, @stfar_jmp_hook, SizeOf(Tfar_jmp));
  Result := Pointer(ULONG(lpInlineProc) - InlineLen);
  //  写回原属性
  VirtualProtect(OldProc, SizeOf(Tfar_jmp), OldProtect, OldProtect);
{$ENDIF}
end;

function UnHookCode(TargetProc: Pointer): Boolean;
var
  lpFuncProc, lpInlineProc: Pointer;
  InlineLen: ULONG;
{$IFNDEF Ring0}
  OldProtect: ULONG;
{$ENDIF}
begin
  Result := False;
  if (TargetProc = nil) then Exit;
  lpInlineProc := TargetProc;
  Dec(PBYTE(lpInlineProc), SizeOf(Pointer) + SizeOf(ULONG));

  lpFuncProc := PPointer(lpInlineProc)^;
  Inc(PBYTE(lpInlineProc), SizeOf(Pointer));

  InlineLen := PULONG(lpInlineProc)^;
  Inc(PBYTE(lpInlineProc), SizeOf(ULONG));

{$IFDEF Ring0}
  //  开始解除Hook
  if NT_SUCCESS(WriteReadOnlyMemoryMark(lpFuncProc, TargetProc, InlineLen)) then
  begin
    Dec(PBYTE(lpInlineProc), SizeOf(Pointer) + SizeOf(ULONG));
    ExFreePoolWithTag(lpInlineProc, PoolWithTag);
    Result := True;
  end; 
{$ELSE}
  //  使内存可写
  VirtualProtect(lpFuncProc, InlineLen, PAGE_EXECUTE_READWRITE, OldProtect);
  //  写回原有数据
  CopyMemory(lpFuncProc, TargetProc, InlineLen);
  Dec(PBYTE(lpInlineProc), SizeOf(Pointer) + SizeOf(ULONG));

  GlobalFree(ULONG(lpInlineProc));
  Result := True;
  //  写回原属性
  VirtualProtect(lpFuncProc, InlineLen, OldProtect, OldProtect);
{$ENDIF}
end;

end.


下面的Hook情况就完全和...Ring3下一模一样了。。。
Copy code
{
  NtOpenProcess[Inline Hook] By Anskya
  Email: Anskya[at]Gmail.com
}
unit Driver;

interface

uses
  Windows, macros, ntddk, HookApiLib, LDE32;

function _DriverEntry(DriverObject: PDriverObject; RegistryPath: PUnicodeString): NTSTATUS; stdcall;

implementation

type
  LPfar_jmp = ^_far_jmp;
  _far_jmp = packed record
    PushOpCode: BYTE;
    PushArg: Pointer;
    RetOpCode: BYTE;
  end;
  Tfar_jmp = _far_jmp;

type
  TZwOpenProcess = function(ProcessHandle:PHandle; DesiredAccess:TAccessMask; ObjectAttributes:PObjectAttributes; ClientId:PClientId): NTSTATUS; stdcall;

var
  HookActive: Boolean;
  ZwOpenProcessNextHook: TZwOpenProcess;

//  钩子过程
function ZwOpenProcessHookProc(ProcessHandle:PHandle; DesiredAccess:TAccessMask; ObjectAttributes:PObjectAttributes; ClientId:PClientId): NTSTATUS; stdcall;
begin
  DbgPrint('ZwOpenProcess HookProc: NewZwOpenProcess(ProcessHandle:0x%.8X,DesiredAccess:0x%.8X,ObjectAttributes:0x%.8X,ClientId:0x%.8X)',
        ProcessHandle, DesiredAccess, ObjectAttributes, ClientId);

  Result := ZwOpenProcessNextHook(ProcessHandle, DesiredAccess, ObjectAttributes, ClientId);
  DbgPrint('ZwOpenProcess HookProc: NewZwOpenProcess(-):0x%.8X', Result);
end;


//  驱动卸载过程
procedure DriverUnload(DriverObject: PDriverObject); stdcall;
begin
  UnHookCode(@ZwOpenProcessNextHook);
  DbgPrint('DriverUnload(-)');
end;

//  驱动入口点
function _DriverEntry(DriverObject: PDriverObject; RegistryPath: PUnicodeString): NTSTATUS; stdcall;
var
  lpFuncProc: Pointer;
  lpInlineProc: Pointer;
  InlineLen: ULONG;
begin
  DriverObject^.DriverUnload := @DriverUnload;
  Result := STATUS_SUCCESS;
  DbgPrint('DriverEntry(-):0x%.8X', Result);

  HookActive := False;

  if (Not HookActive) then
  begin
    DbgPrint('ZwOpenProcess Ord Address: 0x%.8X', SystemServiceOrd($7A)^);    //  XP Ord!
    DbgPrint('ZwOpenProcess Name Address: 0x%.8X', SystemServiceName(GetImportFunAddr(@ZwOpenProcess))^);
    DbgPrint('ZwOpenProcess HookProc Address: 0x%.8X', @ZwOpenProcessHookProc);

    lpFuncProc := PPointer(SystemServiceOrd($7A))^;
    DbgPrint('ZwOpenProcess New Address: 0x%.8X', lpFuncProc);

    lpFuncProc := PPointer(SystemServiceName(GetImportFunAddr(@ZwOpenProcess)))^;
    DbgPrint('ZwOpenProcess New Address: 0x%.8X', lpFuncProc);

    @ZwOpenProcessNextHook := HookCode(lpFuncProc, @ZwOpenProcessHookProc);

    lpInlineProc := @ZwOpenProcessNextHook;
    Dec(PBYTE(lpInlineProc), SizeOf(Pointer) + SizeOf(ULONG));

    lpFuncProc := PPointer(lpInlineProc)^;
    DbgPrint('OldProc : 0x%.8X', lpFuncProc);
    Inc(PBYTE(lpInlineProc), SizeOf(Pointer));

    InlineLen := PULONG(lpInlineProc)^;
    DbgPrint('OldProc Inline Code Len : %d', InlineLen);
    Inc(PBYTE(lpInlineProc), SizeOf(ULONG));

    DbgPrint('ZwOpenProcess Target Address: 0x%.8X', @ZwOpenProcessNextHook);
  end else
  begin
    DbgPrint('ZwOpenProcess Hooked!!! By Anskya');
  end;
end;

end.


这么写代码纯属娱乐好孩子不好学我哦...非程序员的代码写的就是难看...大家多担待...
完全源代码见附件
Copy code
{
  Hook Api Library 0.2 [Ring0] By Anskya
  Email:Anskya@Gmail.com
  ring3 inline hook For Api

Thank:
  前29A高手也一直都是我的偶像...z0mbie大牛...这里膜拜一下
  使用的LDE32引擎是翻译他老人家的...C->Delphi...

说明:
  1.利用堆栈跳转
  没有使用传统的jmp xxxx 长跳转,使用容易理解的push xxxx+ret
  仔细看代码容易理解...封装完好.

  2.内存补丁结构:
  补丁1:|push xxx--钩子处理过程|ret|
  补丁2:|保存原始补丁地址|保存原始地址代码长度|原始地址的代码|push xxxxxx|ret|

更新说明:
  0.2:
    支持Ring0 Inline Hook
  0.1:
    Ring3 Inline Hook
}


Copy code
{
  LDE32.pas: Z0MBiE DISASM ENGINE[LDE32]
  LDE32 Delphi Coded By Anskya
  Email: [email]Anskya@Gmail.com[/email]

更新说明:
  procedure GetInstLenght(myiptr0: Pointer; osizeptr: PULONG);
  function GetProcLength(myiptr0: Pointer): ULONG;

0.2:
  增加 GetProcLength函数.用于获取一个函数过程的长度.

0.1:
  翻译

  Thank: z0mbie
}
ntOpenProcess(delphi) 含有inlinehook的处理打开进程的源代码。用delphi编写。 立即下载

相关推荐

delphi 超级hook inlinehook 类

delphi的超级hook类 纯原创,找了很久没找到 自己琢磨很久 注入yx。然后就可以愉快的hook了 处理方法暂不支持类方法 可以用了 有问题或建议可以联系我qq。

Delphi实现SSDT Hook

 这里使用DDDK---有点自己修改过的痕迹不过区别不大...自己可以看代码1.KeServiceDescriptorTable是一个很特殊的函数...如果直接使用implib来进行创建库的话你会发现这个函数是被忽略的...因为偏移为0所以这个函数基本上只能起到标志作用没有任何实用价值....一些代码中出现了代码:function SystemService(AFunc:Poi

编程资料收集与共享交流 812

Delphi hook 监视窗口创建

Delphi 使用Hook监视所有窗口创建,目前监视成功,但在卸载时,可能会导致资源管理器和任务管理器出现错误。

Delphi 能不能从Ring 3进入Ring 0

Delphi 能不能从Ring 3进入Ring 0?楼主skyworld_xm(skyworld)2004-11-19 09:58:55 在 Delphi / Windows SDK/API 提问Delphi   能不能从Ring   3进入Ring   0?     有例子吗?     多谢. 问题点数:100、回复次数:20Top 1 楼jinjazz(近身剪)回复于 2004

diligentcat的专栏 1143

DELPHI HOOK 钩子 DLL+调用

DELPHI HOOK 钩子 通过调用API 通过MessageBoxA,MessageBoxW,MessageBoxW,OpenProcess 函数的截取。

X64 inline hook CreateProcessInternalW

X64 inline hook explorer.exe-->CreateProcessInternalW监视进程创建. vc2008+WIN7 64测试通过.

SSDT Hook的妙用-对抗ring0 inline hook

 转载】SSDT Hook的妙用-对抗ring0 inline hook作 者: 堕落天才时 间: 2007-03-10,15:18链 接: http://bbs.pediy.com/showthread.php?threadid=40832********************************************************标题:【转载】SSDT Hook的妙用-对抗r

1958

完美支持64&32位InlineHook,C语言,C++类 都有

Windows 64位和32位Inline Hook的例子。包括C语言代码,和封装好的C++类,绝对超值,超简单实用的例子,可以直接运行,用了绝对说好!

Ring 0 Inline Hook

本文讲 用inline hook的方式修改NtOpenKey函数的一个例子 hook 计算机里面一般是指 挂钩某函数,也可以是替换掉原来的函数。 inline hook 是直接在以前的函数替里面修改指令,用一个跳转或者其他指令来达到挂钩的目的。 这是相对普通的hook来说,因为普通的hook只是修改函数的调用地址,而不是在原来的函数体里面做修改。一般来说 普通的hook比较稳定使用。 inli...

weixin_30785593的博客 233

Navicat Premium 12 永久激活保姆级教程(附最新补丁下载)

本文详细介绍了Navicat Premium 12的高效使用方法,从安装配置到高级功能应用,帮助用户充分发挥这款数据库管理工具的全部潜力。内容包括数据库连接管理、数据查询与编辑、数据同步与结构对比等核心功能,以及性能优化和最佳实践建议,提升数据库管理效率。

weixin_28834765的博客 670

K型热电偶负电压采集难题?3种运放电路设计方案对比(含Multisim仿真)

本文针对K型热电偶在低温测量中产生的负电压采集难题,详细对比了三种运放电路设计方案,包括双电源运放反相放大、单电源仪表放大器和差分放大电路,并结合Multisim仿真数据分析了各方案的性能差异。文章还提供了PCB布局和抗干扰设计的实战技巧,帮助工程师解决热电偶信号采集中的核心挑战。

postgres8guard的博客 1033

【Delphi】 查找一个程序进程 关闭进程

数字签名=E5792EA0273CAFAA09999998BB9BE560。关键字=【Delphi】 查找一个程序进程 关闭进程。采集日期=2023-12-02 12:22:07。采集软件=MKM - 我的知识管理。{查找一个程序进程,关闭进程}编程工具=Delphi 7。

fogbow622的博客 667

一网打尽身份验证与授权:深入剖析ASP.NET Core Identity在C#中的全方位实战应用

ASP.NET Core Identity 是 Microsoft 提供的一个强大且可扩展的身份验证和授权框架,用于构建基于用户账户、角色和权限的Web应用程序。它提供了用户注册、登录、密码管理、多因素认证、角色分配、授权等功能,与ASP.NET Core框架深度集成,简化了安全相关的开发工作。通过上述代码示例和注释,展示了如何安装配置Identity、自定义用户实体与数据库上下文、实现用户注册登录、管理角色与用户角色关系,以及如何使用授权策略保护应用程序资源。,并指定用户和角色类型以及主键类型。

java专栏 1535

【原创】为你的驱动挂上外挂 - 嵌入反汇编引擎

标 题: 【原创】为你的驱动挂上外挂 - 嵌入反汇编引擎 作 者: thisIs 时 间: 2011-09-25,22:11:03 链 接: http://bbs.pediy.com/showthread.php?t=140587 首先来看两段IDA中的代码 上面的图是win xp下 NtOpenProcess 中的代码片段 下面的图是win 7下 PsOp

多媒体编程、网络编程、系统编程、网络安全编程、驱动编程 3467

AUTOSAR系统服务篇 - BswM的使用

本文档是对4.0.3版及更高版本的AUTOSAR模式管理应用的介绍。其主要目的是为AUTOSAR的用户和开发人员提供基于示例的AUTOSAR模式管理不同方面的详细概述,这些示例在文中进行了解释。本文中的代码清单共同构成了示例ECU的配置。第2章解释了基础的模式管理概念,例如一般的模式、如何实现模式切换、模式管理者和模式用户的角色等。其次介绍了应用模式管理和基础软件模式管理的依赖关系,两者密切相关。基础软件模式管理器是AUTOSAR R4.0中的中央模式管理模块。它具有很高的可配置性。

IOT2017的博客 861

YOLOv11 损失函数进阶:Varifocal Loss 让正负样本精度双升

创建self.alpha = alpha # 正样本权重系数self.gamma = gamma # 聚焦系数self.lambda_reg = lambda_reg # 回归损失权重# 分类损失:Varifocal Classification Loss# 正样本权重:基于预测置信度# 计算 BCE 损失并加权cls_loss = cls_loss.sum() / (cls_true.sum() + 1e-6) # 按正样本数归一化。

m0_71589036的博客 448

用Delphi写的ring3下清零结束进程

unitClear0; interface uses windows,SysUtils,TLHelp32; const STATUS_SUCCESS=$00000000; STATUS_ACCESS_VIOLATION=$C0000005; STATUS_UNSUCCESSFUL...

qq_31553911的博客 373

在Simulink中构建永磁同步电机的网络化控制模型,并分析通信网络对系统性能的影响

核心优势通过仿真验证了网络延迟和丢包对PMSM控制性能的影响。提供了改进PI参数或引入自适应控制的解决方案。扩展方向抗干扰控制:结合卡尔曼滤波或滑模控制抑制网络噪声。时间敏感网络(TSN)建模:参考知识库[2]的中断触发方式,实现确定性通信。网络安全仿真:模拟恶意攻击(如数据篡改)对控制系统的威胁。

xiaoheshang_123的博客 173

delphi学习笔记(2) 专家模式

刚学习delphi,发现delphi的自动提示太弱了,没法和易还有其他语言的一些提示插件相比   后来咨询了大牛,大牛说有个CnPack这个东西很强大,所以我也在这里做一个笔记,   给需要的童鞋吧!     http://www.cnpack.org

Safedebug的博客 698

第2章-系统控制原理 -> 经典控制理论

第1章 回到目录 第3章 2 控制原理2.1 控制系统的数学模型2.1.1 时域数学模型2.1.2 复域数学模型2.2 线性系统的稳定性2.2.1 复数域稳定判据2.2.2 频率域稳定判据2.3 线性系统状态空间模型2.3.1 状态空间表达式2.3.2 状态空间系统设计2.4 李雅普诺夫稳定性分析2.4.1 李雅普诺夫稳定性2.4.2 李雅普诺夫稳定判据 2.1 控制系统的数学模型 2.1.1 时域数学模型 2.1.2 复域数学模型 2.2 线性系统的稳定性 2.2.1 复数域稳定判据 2.2....

赵继超的笔记 5577

解决Gradle中NPM命令失效问题

摘要:本文分析了IntelliJ IDEA中Gradle执行npm命令失败的问题,报错显示"npm"文件不存在。通过确认npm安装路径、检查系统PATH与Gradle环境的差异,提出两种解决方案:1) 在build.gradle中使用npm绝对路径;2) 通过launchctl修改用户PATH。实例展示了如何修改Gradle脚本或系统配置来解决该问题,指出跨平台开发中环境变量配置的重要性。文章为开发者提供了处理类似问题的实用方法。

2501_90323865的博客 92

[Delphi][FMX]史上最好用的Delphi的消息推送-D推

Delphi推送 FMX推送 离线推送 消息推送 长连接 个推 极光推送 小米推送 华为推送 百度云推送 安卓推送 IOS推送 D推

wingleo的专栏 2405

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

通过进程ID得到进程名

在内核中,通过进程ID,得到进程名称,有多种方法。我使用了两种方法,第一种是使用ZwOpeProcess得到句柄然后ObReferenceObjectByHandle函数得到PEPROCESS结构,然后char *ProcessName = (char*)EProcess + 0x174;第二种方法是得到PEPROCESS结构之后,使用PsGetProcessImageFileName函数得到进程名。具体代码如下:#include #include UCHAR* PsGetProcessImageF

十年磨一剑,霜刃未曾试! 1万+

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

【Delphi】下如何实现32位和64位都能用的Inline Hook

介绍一个CnPack专家包里常用的较底层的技术Inline Hook(内联挂接),所实现的代码均在CnVcl组件包最新的CnMethodHook.pas中。

sensor_WU 博客 421

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

上一篇: SSDT UnHook For C
下一篇: Make a Windbg By Yourself
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值