Inside Geometry Instancing(上)

AnimationInstancing群体渲染 用于实现大批量人物渲染的效果,通过将人物动作打包成二进制文件,渲染时候直接使用这个,降低drawcall,提升性能 立即下载

Inside Geometry Instancing(上)

翻译:clayman
clayman_joe@yahoo.com.cn
仅供个人学习使用,勿用于任何商业用途,转载请注明作者^_^

注:呵呵,发现我对翻译东西上瘾了。这次翻译了《GPU Gem2》中第三章的内容,大家共同学习^_^

在交互式程序中,丰富用户体验的重要方法之一就是呈现一个充满大量各种有趣物体的世界。从数不清的草丛、树木到普通杂物:所有这些都能提高画面最终的效果,让用户保持“幻想状态(suspension of disbelief)”。只有用户相信并且融入了这个世界,才会对这个世界充满感情——这就是游戏开发的圣杯(Holy Grail)。

         从渲染的观点来看,实现这种效果,无非就是渲染大量小物体,一般情况下,这些物体彼此都很类似,只在颜色、位置以及朝向上有细小的差别。举个例子,比如森林中所有树的几何形状都是很类似的,而在颜色和高度上有很大差别。对用户来说,由外形各异的树组成的森林才真实,才会相信它,从而丰富自己的游戏体验。

         但是,使用当前的GPU和图形库渲染大量由少量多边形组成的小物体会带来很大的性能损失。诸如Direct3D和OpenGL之类的图形API都不是为了每帧渲染只有少数多边形的物体数千次而设计的。本文将讨论如何使用Direct3D把同一几何体渲染为大量独特的实体(instances)。下图是Back & White 2中,使用了这一技术的一个例子:

 

3.1 为何使用Geometry Instancing (Why Geometry Instancing)

         在Direct3D中,把三角形数据提交给GPU是一个相对很慢的操作。Wloka 2003显示使用Direct3D在1GHz的CPU上,每秒只能渲染10000到400000批次(batches)。对于现代的CPU,可以预测这个值大概在每秒30000到120000批次之间(对FPS为30frame/sec系统来说大概每帧1000到4000批次)。这太少了!这意味着如果我要渲染一片森林,每批次提交一颗树的数据,那么无论每棵树包含多少多边形,都将无法渲染4000棵树以上——因为CPU已经没有时间来处理其他任务了。这种情况当然是我们不想看到的。在应用程序中,我们希望最小化渲染状态和纹理的改变,同时,在Direct3D中使用一次方法调用,在同一批次中对同一三角形进行多次渲染。这样,就能减少CPU提交批次的时间,把CPU资源留给物理、AI等其他系统。

 

3.2 定义(Definitions)

         我们先来定义一系列与geometry instancing相关的概念。

3.2.1 几何包(Geometry Packet)

         A geometry packet is a description of a packet of geometry to be instanced, a collection of vertices and indices。一个几何包可以使用顶点——包括他的位置、纹理坐标、法线、切线空间(tangent space)以及用于skinning的骨骼信息——以及顶点流中的索引信息来描述。这样的描述,可以直接映射为一个高效的提交几何体的方法。

         几何包是对一个几何体在模型空间进行的抽象描述, 从而可以独立于当前的渲染环境。

         下面是对几何包的一种可能的描述,它不但包含了几何体的信息,同时还包含了物体的边界球体信息:

struct GeometryPacker

{

         Primitive mPrimType;

         void* mVertice;

         unsigned int mVertexStride;

 

         unsigned short* mIndices;

         unsigned int mVertexCount;

         unsigned int mIndexCount;

 

         D3DXVECTOR3 mSphereCentre;

         float mSphereRadius;

}

 

3.2.2 实体属性(Instance Attribute)

         对每个实体来说,典型的属性包括模型到世界的坐标变换矩阵,实体颜色以及由animation player提供的用于对几何包进行skin的骨骼。

struct InstanceAttributes

{

         D3DXMATRIX mModelMatrix;

         D3DCOLOR mInstanceColor;

         AnimationPlayer* mAnimationPlayer;

         unsigned int mLOD;

}

 

3.2.3 几何实体(Geometry Instance)

         几何实体就是一个几何包与特定属性的集合。他直接联系到一个几何包以及一个将要用于渲染的实体属性,包含了将要提交给GPU的关于实体的完整描述。

struct GeometryInstance

{

         GeometryPacket* mGeometryPacket;

         InstanceAttributes mInstanceAttributes;

}

 

3.2.4 渲染及纹理环境(Render and Texture Context)

         渲染环境指的是当前的GPU渲染状态(比如alpha blending, testing states, active render target等等)。纹理环境指的则是当前激活(active) 的纹理。通常使用类来对渲染状态和纹理状态进行模块化。

class RenderContext

{

         public:

         //begin the render context and make its render state active

         void Begin(void);

         //End the render context and restore previous render states if necessary

         void End(void);

        

         private:

         //Any description of the current render state and pixel and vertex shaders.

         //D3DX Effect framework is particularly useful

         ID3Deffect* mEffect;

         //Application-specific render states

         //….

};

class TextureContext

{

         public:

         //set current textures to the appropriate texture stages

         void Apply(void) const;

        

         private :

         Texture mDiffuseMap;

         Texture mLightMap;

         //……..

}

 

3.2.5 几何批次(Geometry Batch)

         几何批次是一系列几何实体的集合,以及用来渲染这个集合的渲染状态和纹理环境。为了简化类的设计,通常直接映射为一次DrawIndexedPrimitive()方法调用。以下是几何批次类的一个抽象接口:

 

class GeometryBatch

{

         public:

         //remove all instances form the geometry batch

         virtual void ClearInstances(void);

         //add an instance to the collection and return its ID. Return -1 if it can’t accept more instance.

         virtual int AddInstance(GeometryInstance* instance);

         //Commit all instances, to be called once before the render loop begins and after every change to the instances collection

         virtual unsigned int Commit(void) = 0;

         //Update the geometry batch, eventually prepare GPU-specific data ready to be submitted to the driver, fill vertex and

         //index buffers as necessary , to be called once per frame

         virtual void Update(void) = 0;

         //submit the batch to the driver, typically impemented eith a call to DrawIndexedPrimitive

         virtual void Render(void) const = 0;

        

         private:

         GeometryInstancesCollection mInstances;

}

3.3 实现(Implementation)

         引擎的渲染器只能通过GeometryBatch的抽象接口来使用geometry instancing,这样能很好隐藏具体的实体化(instancing)实现,同时,提供管理实体、更新数据、以及渲染批次的服务。这样引擎就能集中于分类(sorting)批次,从而最小化渲染和纹理状态的改变。同时,GeometryBatch完成具体的实现,并且与Direct3D进行通信。

         下面使用的伪代码实现了一个简单的渲染循环:

//Update phase

Foreach GeometryBatch in ActiveBatchesList

         GeometryBatch.Update();

 

//Render phase

Foreach RenderJContext

Begin

         RenderContext.BeginRendering();

         RenderContext.CommitStates();

        

         Foreach TextureContext

         Begin

                   TextureContext.Apply();

                   Foreach GeometryBatch in the texture context

                            GeometryBatch.Render();

         End

End

 

         为了能一次更新所有批次并且进行多次渲染,更新和渲染阶段应该分为独立的两部分:这种方法在渲染阴影贴图或者水面的反射以及折射时特别有用。这里我们将讨论4种GeometryBatch的实现,并且通过比较内存占用量、可控性来分析各种技术的性能特性。

         这里是一个大概的摘要:

l          静态批次(static batching):执行instance geometry最快的方法。每个实体通过一次变换移动到世界坐标,附加上属性值,然后就提交给GPU。静态批次很简单,但也是可控性最小的一种。

l          动态批次(Dynamic batching):执行insance geometry最慢的方法。每一帧里,每个经过变换,附加了属性的实体都以流的形式传入GPU。动态批次可以完美的支持skinning,也是可控性最强的。

l          Vertex constants instancing:一种混合的实现方法。每个实体的几何信息都被复制多次,并且一次性把他们复制到GPU的缓存中。通过顶点常量,每一帧都重新设置实体属性,使用一个vertex shader完成gemetry instancing。

l          Batching with Geometry Instancing API。使用DirectX 9提供的Geometry Instancing API,可以获得GeForce 6系列显卡完全的硬件支持,这是一种高效而又具有高度可控性的gemetry instancing方法。与其他几种方法不同的是它不需要把几何包复制到Direct3D的顶点流中。

 

3.3.1 静态批次(Static Batching)

         对静态批次来说,我们希望对所有实体进行一次变换之后,复制到一块静态顶点缓冲中。静态批次最大的优点就是高效,同时几乎市场上所有的GPU都能支持这个特性。

         为了实现静态批次,先创建一个用来填充经过变化后的几何体的顶点缓冲对象(当然也包括索引缓冲)。需要保证这个这个缓冲足够大,足以储存我们希望处理的所有实体。由于我们只对缓冲进行一次填充,并且不再做修改,因此,可以使用Direct3D中的D3DUSAGE_WRITEONLY标志,提示驱动程序把缓冲放到速度最快的可用显存中:

HRESULT res;

res = lpDevice -> CreateVertexBuffer( MAX_STATIC_BUFFER_SIZE, D3DUSAGE_WRITE, 0, D3DPOOL_MANAGED, &mStaticVertexStream, 0 );

ENGINE_ASSERT(SUCCEEDED(res));

         根据应用程序的类型或者引擎的内存管理方式,可以选择使用D3DPOOL_MANAGED或D3DPOOL_DEFAULT标志来创建缓冲。

         接下来实现Commit()方法。它将把需要渲染的经过坐标变换的几何体数据填充到顶点和索引缓冲中。以下是Commit方法的伪代码实现:

Foreach GeometryInstance in Instances

Begin

         transform geometry in mGeometryPack to world space with instance mModelMatrix

         Apply other instnce attributes(like instace color)

         Copy transformed geometry to the Vertex Buffer

         Copy indices ( with the right offset) to the Index Buffer

         Advance current pointer to the Vertex Buffer

         Advance currect pointer to the Index Buffer

End

         好了,接下来就只剩使用DrawIndexedPrimitive()方法,提交这些准备好的数据了。Update()方法和Render()方法的实现都很简单,这里不具体讨论。

         静态批次是渲染大量实体最快的方法,它可以在一个批次中包含不同类型的几何包,但也有一些严重的限制:

l          大内存占用(Large memory footprint):根据几何包大小和希望渲染的实体数量,内存占用量可能会变的很大。对于大场景来说,应该预留出几何体所需的空间。Falling back to AGP memory is possible(注:这里应该指的是当显存不够用时,需要把数据分页存放到AGP memory中),但这会降低效率,因此,应该尽量避免。

l          不支持多种LOD(No support for different level of detal):由于在提交数据时,所有实体都被一次性复制到顶点缓冲中,因此很难对每种环境都选择一个有效的LOD层次,同时,还会导致对多边形数量的预算不正确。可以使用一种半静态的方法来解决这个问题,把特定实体的所有LOD层次都放在顶点缓冲中,每一帧选择不同的索引值,来选择实体的正确LOD。但这样会让实现看起来很笨拙,违反了我们使用这种方法最初的目的:简单并且高效。

l          No support for skinning

l          不直接支持实体移动(No direct support for moving instances):由于效率的原因,实体的移动应该使用vertex shader逻辑和动态批次来实现。最终的解决方案其实就是vertex constants instancing。

接下来的一种方法将解除这些限制,以牺牲渲染速度换取可控性。

 

3.3.2 动态批次(DynamicBatching)

         动态批次以降低渲染效率为代价,克服了静态批次方法的限制。动态批次最大的优点和静态批次一样,也能在不支持高级编程管道的GPU上使用。

         首先使用D3DUSAGE_DYNAMIC和D3DPOOL_DEFAULT标志创建一块顶点缓冲(同样也包括相应的索引缓冲)。这些标志将保证缓冲处于最容易进行内存定位的地方,以满足我们动态更新的要求

HRESULT res;

res = lpDevice->CreateVertexBuffer(MAX_DYNAMIC_BUFFER_SIZE, D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, 0 , D3DPOOL_DEFAULT, &mDynamicVertexStream, 0)

这里,选择正确的MAX_DYNAMIC_BUFFER_SIZE值是很重要的。有两种策略来选择这个值:

l          选择一个可以容纳每一帧里所有可能实体的足够大值。

l          选择一个足够大的值,以保证可以容纳一定量的实体。

第一种策略在一定程度上保证了更新和渲染批次的独立。更新批次意味着对动态缓冲中的所有数据进行数据流化(streaming);而渲染则只是使用DrawIndexedPrimitive()方法提交几何数据。当这种方法将会占用大量的图形内存(显存或者AGP memory),同时,在最差的情况下,这种方法将变的不可靠,因为我们无法保证缓冲在整个应用程序生命期中都足够大。

第二种策略则需要在几何体信息数据流化和渲染之间进行交错:当动态缓冲被填满时,提交几何体进行渲染,同时丢弃缓冲中的数据,准备好填充更多将被数据流化的实体。为了优化性能,使用正确的标志是很重要的,换句话说就是,在每一批实体开始时都使用D3DLOCK_DISCARD标志锁定(locking)动态缓冲,此外,对每个将要数据流化的新实体都使用D3DLOCK_WRITEONLY标志。这个方法的缺点是每次当批次需要进行渲染时,都需要重新锁定缓冲,以数据流化几何体信息,比如实现阴影影射时。

应该根据应用程序的类型和具体要求来选择不同方法。这里,由于简单和清楚的原因,我们选择了第一种方法,但是也添加了一点点复杂度:动态批次天生支持skinning,我们顺便对他进行了实现。

Update方法与之前在 3.3.1 讨论的Commit()方法很类似,但它需要在每一帧都执行。这里是伪代码的实现;

Foreach GeometryInstance in Instances

Begin

         Transform geometry in mGeometryPacket to world space with instance mModelMatrix

         if instance nedds skinning, request a set of bones from mAnimationPlayer and skin geometry

         Apply other instance attributes(like instance color)

         Copy transformd geometry to the Vertex Buffer

         Copy indices (with the right offset) to the Index Buffer

         Advance current pointer to the Vertex Buffer

         Advance current pointer to the Index Buffer

End

         这种情况下,Render()方法只是简单的调用DrawIndexedPrimitive()方法而已。

 

CreateVertexBuffer问题的代码 CreateVertexBufferd的问题 很郁闷的问题 希望帮忙解决一下 立即下载

相关推荐

OpenVPN 新增 windows 客户端

虚拟私人网络(Virtual Private Network,简称VPN)是一种网络技术,它允许用户通过公共网络(如互联网)建立一个安全的连接通道。本文介绍如何添加 windows 客户端。

利昂的技术存档 3765

PixiJS 渲染优化

最近做在线CAD可视化与编辑,对前端的可视化渲染技术进行了选型,对于二维CAD来说一般用canvas就够了,但是canvas每一次平移,缩放,更新数据都需要重新计算渲染所有的图形数据,数据一多就显得非常卡。如果使用三维webgl,在没有任何第三方的开源封装技术下,通过webgl去实现二维也是会遇到很多问题。基于此,找到了PixiJS这个支持canvas和webgl渲染的引擎,关键是非常快(之前在github看到过一个在线的程序测试,有十几种渲染引擎的测试,我对比过确实是最强的,这个网站忘记在哪里了)

揽月凡尘 3484

2025东方财富笔试考什么?cata能力测评攻略|答题技巧真题分享

4月10日-4月20日 专业笔试(行测+金融知识混合双打) 4月25日-5月10日 面试车轮战(AI面+半结构化+压力面) 5月15日起 Offer发放(谈薪必杀技:对标同花顺/雪球)这里不仅是金融极客的乐园,更是**“年薪30万管培生计划”**的主战场——你将用代码重构K线,用算法预判市场,成为资本市场的“数字先知”。东方财富,中国金融信息服务领域的“隐形冠军”,以**“金融数据+互联网”双擎驱动**,打造了覆盖证券、基金、期货的全生态交易平台。:• “我总坚持自己的方案”(HR:团队毒药!

Dgntsj的博客 3259

OGRE——渲染大量物体,批次(batch)

<br />OGRE渲染物体,可以把物体作为InstancedGeometry,StaticGeometry,Entity实例来渲染。<br />区别:<br />InstancedGeometry:Pre-transforms and batches up meshes for efficient use as instanced geometry in a scene。也就是说,把所有网格作为一个instance geometry。<br />this shader instancing impleme

1885

大语言模型(LLM)在组合优化中的新突破:LLM-LNS与FunSearch性能对比

本文深入探讨了大语言模型(LLM)在组合优化中的创新应用,重点对比了LLM-LNS与FunSearch两种方法的性能差异。研究表明,LLM-LNS在物流路径规划、资源调度等场景中展现出显著优势,其双层自演化架构能有效平衡探索与利用,相比传统方法提升效率约43%。文章还提供了实践选择指南,帮助开发者根据具体需求选用合适的技术方案。

weixin_42526415的博客 405

AIPex:AI + 自然语言驱动的浏览器自动化扩展

AIPex是一款革命性的Chrome扩展,通过AI技术实现自然语言驱动的浏览器自动化。它支持30多种自动化工具,包括智能标签页管理(分组、切换、批量操作)、页面内容提取(文本、链接、元数据)、交互元素操作(点击、滚动)以及表单智能填写等功能。用户只需用自然语言下达指令,即可快速完成复杂的浏览器操作,大幅提升工作效率。AIPex特别适合需要处理大量重复性网页操作的用户,如数据分析师、产品经理等。

blues_C的博客 1127

CreateVertexBuffer()

HRESULT CreateVertexBuffer( UINT Length, //顶点缓冲区的大小,按字节数算 DWORD Usage, //顶点缓冲区属性 DWORD FVF,

假装狠牛逼 4569

【视频监控国标GB/T28181】无人机的视频图传技术

然而,随着无人机市场的不断发展和无人机视频图传技术的迅速进步,一些厂家正积极探索更多的传输方式。如今,一些大疆无人机已经具备了4G辅助图传功能,这意味着它们需要在无人机上安装相应的SIM卡,并在有移动互联网信号的情况下,通过互联网进行视频图传。这种技术的应用,不仅提高了无人机的操作灵活性,也使得无人机在各个领域的应用更加广泛。在使用时,用户需时刻注意无人机的飞行距离。在无人机图传系统中,OFDM技术的运用更是如虎添翼,显著增强了视频传输的品质与稳定性,尤其在错综复杂的电磁环境中,更能凸显其不可替代的优势。

开源物联网项目商业化作者 5661

Vulkan学习笔记【七】缓冲

第一个顶点索引位于绑定索引缓冲区内的firstIndex × indexSize + offset的偏移量,其中offset是vkCmdBindIndexBuffer指定的偏移量,indexSize是indexType指定的类型的字节大小。我们只使用一次指令缓冲,并等待从函数返回,直到复制操作完成执行,使用VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT告诉驱动程序我们的意图。然后,我们将使用缓冲区复制命令将数据从暂存缓冲区移动到实际的顶点缓冲区。

weixin_43469171的博客 793

最新Python爬虫实战(入门爬虫篇)——案例17:某天气网40天天气预报数据采集(详细爬虫思路截图+抓包动图演示+完整爬虫代码+详细注释)

本次案例通过分析某天气网的数据接口,成功实现了对40天天气预报数据的批量采集。抓包分析:利用浏览器开发者工具找到隐藏的JSONP数据接口,掌握URL构成规律。请求模拟:构造带有Referer和User-Agent的请求头,添加时间戳参数避免缓存,获取原始数据。数据解析:处理JSONP格式,去除前缀后使用json模块解析,提取所需字段并规范化日期格式。数据存储:利用pandas将结构化数据保存为Excel文件,便于后续分析和使用。动态数据接口的发现与分析JSONP数据的清洗与解析。

努力让自己发光,对的人才能迎着光而来 22万+

基于Simulink的自适应反步法(Adaptive Backstepping)控制​

本文针对非线性系统控制中未知参数和强非线性耦合的挑战,提出基于Simulink的自适应反步法解决方案。通过融合参数在线估计与反步递归设计,该方法显著提升了永磁同步电机(PMSM)速度控制的鲁棒性,使跟踪误差从20%降至3%,参数估计收敛时间小于0.5秒。文章详细阐述了从算法推导到Simulink实现的完整流程,包括系统架构设计、核心算法推导(以PMSM为例)、模块化建模方法、参数优化策略以及工程部署建议。提供的自适应控制器MATLAB代码和关键参数表可直接应用于实际工程,为电机驱动、机械臂等非线性系统控制提

xiaoheshang_123的博客 101

Unity Animation Instancing 官方解决方案初试

Animation Instancing 是unity官方提出的高性能大规模动画解决方案,起初是为了解决企业用户的需求,后来在Github上开放。 Github地址: https://github.com/Unity-Technologies/Animation-Instancing 官方Blog地址: https://connect.unity.com/p/animation-instancing-gao-xing-neng-da-gui-mo-dong-hua-jie-jue-fang-an 项

Hello Captain 5538

原理和代码解读:用Diffusion Models高清图像修复(Image Inpainting)

在最近的Diffusion Models应用中,Image Inpainting+ControlNet/Lora等工作在模特衣服生成、家居场景重建等场景中得到了广泛的应用。这篇博客主要介绍Diffusion Models如何在修复高清图像的。

沉迷单车的追风少年 2497

Inside Geometry Instancing

<br />翻译:clayman<br />clayman_joe@yahoo.com.cn<br />仅供个人学习使用,勿用于任何商业用途,转载请注明作者^_^ <br />注:这篇文章是《GPU Gems2》中的第三章,本人水平有限,不清楚的地方请大家以原文为准<br />  在交互式程序中,丰富用户体验的重要方法之一就是呈现一个充满大量各种有趣物体的世界。从数不清的草丛、树木到普通杂物:所有这些都能提高画面最终的效果,让用户保持“幻想状态(suspension of disbelief)”。只有用户相

痞子龙3D编程 2684

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

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

Inside Geometry Instancing(下)

Inside Geometry Instancing(下) http://blog.youkuaiyun.com/soilwork/article/details/655858 此教程版权归我所有,仅供个人学习使用,请勿转载,勿用于任何商业用途。商业应用请同我联系。 由于本人水平有限,难免出错,不清楚的地方请大家以原著为准。也欢迎大家和我多多交流。 其中部分...

aikb6223的博客 141

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

上一篇: 显示器之死 -_-
下一篇: Inside Geometry Instancing(下)
soilwork
博客等级 码龄23年 290粉丝 116原创
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值