React16源码: React中Fiber对象的源码实现

React 之 简易实现 Fiber架构 文章目录fiber架构是什么?它解决了什么问题?fiber 的核心思想,实现 fiber 我们需要做到什么?如何做?Fiber reconcileCommit 阶段实现useState管理状态更新 此篇文章是在学习一步一步实现fiber架构的同时,从另外一个由总到分的角度来总结fiber架构的实现思路。文章末尾有一些学习参考文章可以借鉴。 fiber架构是什么?它解决了什么问题? 当我们项目过于复杂,渲染树过于庞大的时候,那么我们的递归渲染会耗时很长,而且很难被中断,fiber 的主要原理就是让我们在 di 阅读详情

关于 Fiber 对象

  • 在FiberRoot里面,它也会为我们去创建的一个对象叫做 Fiber
  • 在 React16 之后, 非常核心,非常重要的一个东西
  • A. 每个 ReactElement 都会对应一个 Fiber 对象
  • B. 它会记录节点的各种状态
    • 比如,class component,它的state和props
    • 这些东西是记录在 Fiber 对象上面的
    • 在 Fiber 更新之后才会更新到 class component 上面的 this.state, this.props 里面
    • 并不是通过 class component 自己去调理的这个过程
    • 这些过程都是在 Fiber 上面进行操作的,只是在更新了这个节点之后
    • 它才会把这个属性放到this上面,因此也给了react实现 hooks 一个方便
    • 因为hooks是用在function component里面的,里面没有this
    • 我们本身记录state还有props都不是在class component的对象上面,而是在 Fiber 上面
    • 我们有能力记录这个状态之后,也可以让function component更新的过程当中去拿到这个更新之后的state
    • 所以Fiber有一个非常重要的作用,就是记录节点的各种状态
  • C. 串联整个应用
    • 在 ReactElement 中,通过 props.children 属性把整个应用串联起来
    • 每一个节点都可以通过一个属性去拿到它的子节点
    • 在 Fiber 里面,它也是有这么一个能力来帮助我们记录整个应用的一个树形结构的一个状态,把每一个节点给它串联起来
    • 在 Fiber 里面它是如何进行一个串联的呢?需要先回顾一下 ReactElement 的串联方式, 结合前文中的举例,如下
                  App
                   |
              render() return
                   |
                  div
                  / \
                 /   \
        children[0]  children[1]
                /       \
              /          \
             /            \
          Input          List
            |               \
      render() return     render() return 
            |                 \
          input        (span  span  span  button)
      
    • 上面就是 ReactElement 基于 render() 函数 return 了子节点,由此构建的树形结构
    • Fiber 里面也有这个能力记录整个应用的树形结构和状态,把每个节点串联起来
                
                   -----current-----> 
        FiberRoot                     RootFiber
                   <---stateNode-----    |   
                                         |
                                       child  
                                         |
                                         ↓
                                        App
                                         |
                                       child
                                         |
                                         ↓
                                         |
                                        div
                                        / \
                                       /   \
                                   child   child
                                     /       \
                                    /         \
                                   /           \
                                Input-sibling-> List
                                  |               \
                                child            child
                                  |                \
                                  ↓                 \
                                input               span --sibling--> span --sibling--> span --sibling--> button
      
    • 被首先创建的 FiberRoot 有一个 current 属性,指向一个 Fiber对象,我们叫做 RootFiber
    • 因为 FiberRoot 在 ReactDOM.render 时,接受了 一个参数是 App
    • App 这个 ReactElement 它对应的Fiber对象就是 RootFiber 的 child
    • App 的 child 就是 div 节点,因为它的 render 函数渲染出来之后就是一个 div 的唯一子节点
    • 这个 div 接收到的 props.children 是一个数组,这个数组的第一个节点会作为它的 child, 其指向 Input 组件对应的 Fiber对象
    • List 也是作为 div的 props.children 的一项,它是 Input 对应Fiber对象的 sibling 兄弟节点
    • 也就是说,每个节点只会存储它的第一个子节点,不会把它的子节点都存放在一起,通过上述单项的指向来进行存储
    • 对于 Input 组件来说,它的 child 就是其 render 函数 return 的一个 input 原生标签
    • 对于 List 组件来说,它返回的是一个数组,它的第一个子节点就是 span, 剩下的兄弟节点通过 sibling 来连接
    • 而每个子节点都会有一个 return 属性指向自己的父节点,上述图示中并没有标示出来
    • 我们进行节点的查找就会非常方便,只需要通过 child 一路向下查找,直接到叶子节点
    • 基于这种方式来遍历整个应用,即通过react的这种数据结构,把整个 Fiber树给它串联起来,提供给我们一个方便高效的遍历方式
    • 现在看下 Fiber 的属性,源码在: https://github.com/facebook/react/blob/v16.6.0/packages/react-reconciler/src/ReactFiber.js
      // A Fiber is work on a Component that needs to be done or was done. There can
      // be more than one per component.
      export type Fiber = {|
        // These first fields are conceptually members of an Instance. This used to
        // be split into a separate type and intersected with the other Fiber fields,
        // but until Flow fixes its intersection bugs, we've merged them into a
        // single type.
      
        // An Instance is shared between all versions of a component. We can easily
        // break this out into a separate object to avoid copying so much to the
        // alternate versions of the tree. We put this on a single object for now to
        // minimize the number of objects created during the initial render.
      
        // Tag identifying the type of fiber.
        tag: WorkTag, // 标记不同的组件类型,有原生dom节点的组件, 有 class component, function component, 各种各样的组件都有对应的类型
      
        // Unique identifier of this child.
        key: null | string, // ReactElement 里面的key
      
        // The value of element.type which is used to preserve the identity during
        // reconciliation of this child.
        elementType: any, // ReactElement.type, 就是调用 createElement 的第一个参数
      
        // The resolved function/class/ associated with this fiber.
        type: any, // 异步组件 resolved 之后返回的内容, 一般是 function 或 class
      
        // The local state associated with this fiber.
        stateNode: any, // 跟当前Fiber相关的本地状态,在浏览器环境中就是DOM节点,对应节点实际的实例,比如 class component 对应 class 的实例, dom组件对应dom节点的实例,function component 没有实例,就没有 stateNode, 有了它在应用更新完成后,就可以把 最新的 state,props 等放到节点上
      
        // Conceptual aliases
        // parent : Instance -> return The parent happens to be the same as the
        // return fiber since we've merged the fiber and instance.
      
        // Remaining fields belong to Fiber
      
        // The Fiber to return to after finishing processing this one.
        // This is effectively the parent, but there can be multiple parents (two)
        // so this is only the parent of the thing we're currently processing.
        // It is conceptually the same as the return address of a stack frame.
        return: Fiber | null,
      
        // Singly Linked List Tree Structure.
        child: Fiber | null,
        sibling: Fiber | null,
        index: number,
      
        // The ref last used to attach this node.
        // I'll avoid adding an owner field for prod and model that as functions.
        ref: null | (((handle: mixed) => void) & {_stringRef: ?string}) | RefObject, // ref 属性
      
        // Input is the data coming into process this fiber. Arguments. Props.
        pendingProps: any, // This type will be more specific once we overload the tag. // 新的变动,带来的新的 props,就存在 pendingProps 属性上
        memoizedProps: any, // The props used to create the output. // 上一次更新结束之后的 props
      
        // A queue of state updates and callbacks.
        updateQueue: UpdateQueue<any> | null, // 该 Fiber 对应的组件产生的 update 会存放在这个队列里面
      
        // The state used to create the output
        memoizedState: any, // 上次渲染完成之后的 state,比如我们执行setState,会算出一个新的state,算出是要经过 updateQueue计算的, 计算完之后覆盖 memoizedState 值
      
        // A linked-list of contexts that this fiber depends on
        firstContextDependency: ContextDependency<mixed> | null, // 一个列表,存放这个Fiber依赖的context
      
        // Bitfield that describes properties about the fiber and its subtree. E.g.
        // the ConcurrentMode flag indicates whether the subtree should be async-by-
        // default. When a fiber is created, it inherits the mode of its
        // parent. Additional flags can be set at creation time, but after that the
        // value should remain unchanged throughout the fiber's lifetime, particularly
        // before its child fibers are created.
        mode: TypeOfMode, // 用于描述当前Fiber和它子树的Bitfield, 共存的模式表示这个子树是否默认是异步渲染的, Fiber 被创建的时候会继承父Fiber, 其他的标识也可以在创建的时候被设置,但在创建之后不应该再被修改,特别是他的子Fiber创建之前, 对应比如: ConcurrentMode, StrictMode,
      
        // Effect
        effectTag: SideEffectTag, // 副作用,用来记录 Side Effect
      
        // Singly linked list fast path to the next fiber with side-effects.
        nextEffect: Fiber | null, // 副作用, 单链表用来快速查找下一个 side effect
      
        // The first and last fiber with side-effect within this subtree. This allows
        // us to reuse a slice of the linked list when we reuse the work done within
        // this fiber.
        firstEffect: Fiber | null, // 副作用,子树中第一个 side effect
        lastEffect: Fiber | null, // 副作用,子树中最后一个 side effect
      
        // Represents a time in the future by which this work should be completed.
        // Does not include work found in its subtree.
        expirationTime: ExpirationTime, // 当前节点产生的更新任务的过期时间, 代表任务在未来的哪个时间点应该被完成,不包括他的子树产生的任务
      
        // This is used to quickly determine if a subtree has no pending changes.
        childExpirationTime: ExpirationTime, // 它的子节点如果产生更新,记录子节点的过期时间, 快速确定子树中是否有不在等待的变化
      
        // This is a pooled version of a Fiber. Every fiber that gets updated will
        // eventually have a pair. There are cases when we can clean up pairs to save
        // memory if we need to.
        alternate: Fiber | null, // 在Fiber树更新的过程中,每个Fiber都会有一个跟其对应的Fiber,我们称它为 current <==> workInProgress的对应关系, 在渲染完成之后他们会交换位置,在更新过程中,会根据整个Fiber对象,创建一个 workInProgress, current是当前的, workInProgress 是要进行一个更新的, 在更新完成后,workInProgress 状态会更新成一个新的,current就变成老的,最终节点渲染到 dom 上面,workInProgress 会变成current,再下一次更新到来的时候,会保持着两个对象都存在,这个在 react 中叫做 double buffer, 是用来提高性能的
      
        // Time spent rendering this Fiber and its descendants for the current update.
        // This tells us how well the tree makes use of sCU for memoization.
        // It is reset to 0 each time we render and only updated when we don't bailout.
        // This field is only set when the enableProfilerTimer flag is enabled.
        actualDuration?: number,
      
        // If the Fiber is currently active in the "render" phase,
        // This marks the time at which the work began.
        // This field is only set when the enableProfilerTimer flag is enabled.
        actualStartTime?: number,
      
        // Duration of the most recent render time for this Fiber.
        // This value is not updated when we bailout for memoization purposes.
        // This field is only set when the enableProfilerTimer flag is enabled.
        selfBaseDuration?: number,
      
        // Sum of base times for all descedents of this Fiber.
        // This value bubbles up during the "complete" phase.
        // This field is only set when the enableProfilerTimer flag is enabled.
        treeBaseDuration?: number,
      
        // Conceptual aliases
        // workInProgress : Fiber ->  alternate The alternate used for reuse happens
        // to be the same as work in progress.
        // __DEV__ only
        _debugID?: number,
        _debugSource?: Source | null,
        _debugOwner?: Fiber | null,
        _debugIsCurrentlyTiming?: boolean,
      |};
      
    • Fiber里面三个重要的属性: return, child, sibling 可以帮助把应用中的所有节点一一串联
      • return: 指向它在Fiber节点树中的 parent, 用来处理完这个节点之后,向上返回
      • child: 单链表树结构, 指向自己的第一个子节点
      • sibling: 指向自己的兄弟结构,兄弟节点的return指向同一个父节点
    • 上述 Effect 相关的属性,都是副作用,是用来标记 Dom 节点要进行那些更新的工具,以及标记是否要执行组件生命周期的内容
    • 上述 Duration 相关属性,是渲染时间相关的,和 React DEV TOOL 有相关关系
    • 其他属性,都在代码中备注
前端宝典之三:React源码解析之Fiber架构 本文主要内容: 1、React Concurrent 2、React15架构 3、React16架构 4、Fiber架构 5、任务调度循环和fiber构造循环区别 阅读详情

相关推荐

【react】什么是fiber?fiber解决了什么问题?从源码角度深入了解fiber运行机制与diff执行

我在[react] 什么是虚拟dom?虚拟dom比操作原生dom要快吗?虚拟dom是如何转变成真实dom并渲染到页面的?一文中,介绍了虚拟的概念,以及中虚拟的使用场景。那么按照之前的约定,本文来聊聊中另一个非常重要的概念,也就是。那么通过阅读本文,你将了解到如下几个知识点:同样,若文中涉及到的源码部分,我依然会使用的版本,保证文章的结论不会过于老旧;其次,的概念理解起来其实比较枯燥,但我会尽量描述的通俗易懂一点,那么本文开始。我们学习任何东西,一定会经历两个阶段,一是这个东西是什么?二是这个东西有什么用(解

行星飞行的博客 1万+

React 实现 Fiber 算法

介绍: fiber 算法的核心 API 是 requestIdleCallback,利用浏览器的空余时间执行任务,如果有更高优先级的任务要执行时,当前执行的任务可以被终止,优先执行高级别任务。 React 16 之前的版本问题: React 16 之前的版本比对更新 VirtualDOM 的过程是采用循环加递归实现的,这种比对方式有一个问题,就是一旦任务开始进行就无法中断,如果应用中组件数量庞大,主线程被长期占用,直到整棵 VirtualDOM 树比对更新完成之后主线程才能被释放,主线程才能执行其他任务。

m0_50729201的博客 846

React-从源码分析React Fiber工作原理

本文的demo仓库在https://github.com/qiqingjin/blog/tree/master/React_Redux,喜欢请star哟~ 为什么要重写React React16 以前 React16 以前,对virtural dom的更新和渲染是同步的。就是当一次更新或者一次加载开始以后,diff virtual dom并且渲染的过程是一口气完成的。如果组件...

柒青衿的博客 1万+

React Fiber 虚拟 DOM 实现原理与Diff 算法实现原理

因为JavaScript是单线程的,一旦组件开始更新,主线程就一直被React控制,当js在处理大型计算的时候会导致页面出现卡帧的现象,更严重的会出现页面“假死”;而 Fiber 能将大型的计算拆分成一个个小型计算,然后按照执行顺序异步调用,这样就不会长时间霸占线程,UI也能在俩次小型计算的执行间隙进行更新,从而给与用户及时的反馈。fiber是个链表,有type,props,return,child 和 sibing 属性,指向第一个子节点和相邻的兄弟节点,从而构成 fiber tree;

subsistent的博客 998

React源码解读之React Fiber

该文章涉及的源码部分基于React v17.0.2该文章涉及的源码部分基于React v17.0.2。

weixin_59558923的博客 443

Windows下用Docker部署RagFlow的5个常见错误及解决方法(附详细日志分析)

本文针对Windows系统下使用Docker部署RagFlow的常见难题,提供了详细的避坑指南。文章深度剖析了WSL2配置、端口冲突、文件权限、资源限制及网络通信这五个典型错误场景,并结合具体日志分析,给出了经过验证的解决方案,帮助开发者高效完成部署。

weixin_29233857的博客 180

React源码之Fiber架构

对于Fiber我们可以理解为存储在内存中的Dom对于React15在render阶段的reconcile是不可打断的,如果在操作大量的dom时,会存在卡顿,因为浏览器将所有的时间都交给了js引擎线程去执行,此时GUI渲染线程被阻塞,导致页面出现卡顿,无法响应用户对应的事件。

认定的总要想办法去完成。 1616

时序数据库避坑指南:TDengine与IoTDB在车联网场景的7个关键对比

本文对比了时序数据库TDengine与IoTDB在车联网场景下的7个关键差异,包括数据模型设计、边缘-云端协同能力、车规级函数库、存储压缩算法等。通过真实案例和性能测试,帮助企业在新能源汽车大数据处理中选择合适的时序数据库,优化存储成本和实时告警性能。

rust6ferris的博客 454

React 16.7 Fiber源码解读 (一)之数据结构

React Fiber提出有一段时间了,关于它的文章汗牛充栋,从React 16.0 到React 16.4 (项目使用版本) 再到最新的 React 16.7,尽管大致框架没变,但是实现细节一直在变,在不同时间点发布的React Fiber源码间切换难免会有错乱。因此决定对Fiber运行框架基于最新React 16.7做一个大致的梳理

辰辰沉沉大辰沉 3938

深入解析rknn-toolkit2混合量化:如何为RK3588和RK356X选择最佳量化策略

本文深入解析了RKNN-Toolkit2混合量化技术,针对瑞芯微RK3588和RK356X芯片的硬件特性差异,提供了最佳量化策略选择指南。通过混合量化技术,开发者可以在保持较高推理效率的同时显著降低精度损失,特别适用于边缘计算场景。文章详细介绍了混合量化的技术原理、实战流程及芯片专属优化策略,帮助开发者充分利用硬件特性提升模型性能。

dog123的博客 259

通用、可复用的 AI Skill 开发基本流程

-----name:唯一标识符(建议用领域-功能格式):自然语言描述触发条件(AI 依赖此判断是否激活)tags(可选):便于分类和搜索version:支持后续迭代步骤输出物1. 定范围触发场景描述2. 写元数据name3. 填内容结构化 Markdown 文件4. 做验证可运行 + 符合规范5. 去集成放入对应 IDE 目录6. 持续维护跟进框架更新通过这套流程,你不仅可以开发(Hooks 最佳实践)(原生 WebGL 优化)(Pandas/Numpy 高效写法)

lpfasd123的博客 733

React 源码讲解第 4 节- Fiber 对象

本小节介绍 Fiber 对象的含义、类型以及具体包含哪些属性。

杏子 821

博途PLC S7-1200/1500 ModbusTcp通信SCL代码篇(轮询)

博途PLC MODBUS TCP的详细讲解和注意事项,可以参看下面这篇博文,这里不在赘述。这篇作为SCL代码篇主要给出SCL语言下的轮训写法和注意事项。博途PLC1200/1500PLC ModbusTcp通信(轮询处理)_RXXW_Dor的博客-优快云博客。............

RXXW_Dor的博客 8429

React中createRoot函数原理解读——Element对象与Fiber对象、FiberRootNode与HostRootNode

Element 对象是描述 UI 结构的纯 JS对象,通常由 React.createElement 或 JSX 语法创建,表示页面的静态结构;而 Fiber 对象 是 React 的内部数据结构,代表应用的每个组件,负责存储组件的状态、更新任务和渲染信息,是 React 渲染和调度的核心。FiberRootNode 是管理整个应用渲染的根容器,保存与宿主环境相关的信息,并协调 Fiber 树的更新;HostRootFiber 则是 Fiber 树的根节点,表示应用的入口,保存应用的根组件及其更新状态

警警的博客 1621

PID、模糊PID、SkyHook、LQR、H2/H∞、ADRC等悬架控制合集

PID、模糊PID、SkyHook、LQR、H2/H∞等悬架控制合集

Mr.邹的博客 2014

杰理SDK入门教程(一):编译环境的安装和程序下载

本文档提供了杰理SDK在Windows系统下的开发环境配置与代码编译指南。主要内容包括:1) 开发环境安装步骤,需下载Code::Blocks和杰理工具链;2) 编译过程中常见问题的解决方案,如安全警告提示和链接文件缺失问题;3) 代码编译流程说明,包括打开工程、连接开发板、执行编译等步骤。文档特别强调了强制升级模式的操作方法,并指出需避免点击运行/调试按钮。最后提示了杀毒软件可能误报工具链的注意事项。

qq_42014563的博客 2744

react底层原理解析之fiber

Fiber的特点/作用 Fiber能够使得动画、布局和页面交互变得更加的流畅。 一:Fiber的概念   React Fiber是react执行渲染时的一种新的调度策略,JavaScript是单线程的,一旦组件开始更新,主线程就一直被React控制,这个时候如果再次执行交互操作,就会卡顿。   React Fiber就是通过对象记录组件上需要做或者已经完成的更新,一个组件可以对应多个Fiber。 ...

吴小迪的博客 4万+

量化交易 米筐 多因子合成(回测中使用)

多因子合成 1、因子合成 将一些相关(高、低)的因子合成一个因子 方法: 使用PCA方式(使用于较强相关性) 2、核心代码 将因子 inc_revenue_ttm 和 operating_revenue_growth_ratio_ttm 合成为一个因子 inc_operating from sklearn.decomposition import PCA pca = PCA(n_components=1) # 因子合并 fund['inc_operating'] = pca.fit_transform(fu

廷益_飞鸟的博客 1063

React15和React16生命周期对比,初识Fiber

React15和React16生命周期对比,初识Fiber

why404 1533

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

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

【React架构 - Fiber构造循环】

React架构中两大事件循环之一在协调器Reconciler中的Fiber构造循环

weixin_44273311的博客 2323

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

React fiber源码理解

前言 我们知道,React Fiber是React v16中新的reconciliation引擎,是React团队用时2年对Stack Reconciler版本的核心算法进行的重写。它的主要目标是实现虚拟DOM的增量渲染,可以将渲染工作拆分成块并将其分散到多个帧的能力。在新的更新到来时,可以暂停、中止或复用工作的能力,可以为不同类型的更新分配优先级顺序的能力。这是React设计的一种体现,相比于...

大灰狼的小绵羊哥哥的博客 1096

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

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

React 源碼解析 - Fiber/Reconcile 系列:Fiber 與 Diff

React 源碼解析 - Fiber/Reconcile 系列:Fiber 與 Diff前言正文從 DOM 到 Fiber 對象DOMVDOMReact 元素(React Element)Fiber 對象Side EffectsEffects listReact 架構關於 ReconcilerStack ReconcilerFiber Reconciler深入 Reconciliation 工作流程找出兩棵 React element tree 差異三大策略React Diff 算法具體過程對比不同 typ

weixin_46803507的博客 1252

React Fiber架构原理剖析

在 React 16 之前,VirtualDOM 的更新采用的是Stack架构实现的,也就是循环递归方式。不过,这种对比方式有明显的缺陷,就是一旦任务开始进行就无法中断,如果遇到应用中组件数量比较庞大,那么VirtualDOM 的层级就会比较深,带来的结果就是主线程被长期占用,进而阻塞渲染、造成卡顿现象。为了避免出现卡顿等问题,我们必须保障在执行更新操作时计算时不能超过16ms,如果超过16ms,就需要先暂停,让给浏览器进行渲染,后续再继续执行更新计算。而Fiber架构就是为了支持“可中断渲染”而创建的。.

lt_xiaodou的博客 3571

【React源码08】深入学习React 源码实现——Fiber架构双缓冲(current 与 workInProgress)机制

React的双缓冲机制(current与workInProgress)是Fiber架构的核心特性,通过两棵Fiber树的交替使用实现高效的UI更新。在更新过程中,React基于current树创建workInProgress树,所有更新操作在workInProgress树上进行,完成后通过commitRoot提交并切换指针。这种机制允许React保留当前状态,并支持中断/恢复渲染。源码中createWorkInProgress函数负责节点的创建/复用,通过alternate指针实现双树快速切换。

silverclayz的技术分享 944

深入理解React的Fiber架构

以上内容虽无法覆盖Fiber的方方面面,但可以确保你学完后对Fiber会有一个整体上的认识,并且让你在以后阅读互联网上其它关于Fiber架构的文章时,不再因为基础知识困惑,而是能够根据已有的思路轻松地拓展你大脑里关于Fiber架构的知识网。

mzp520lf的博客 2932

万字长文介绍React Fiber架构的原理和工作模式

这篇文章从React Fiber架构的原理和源码入手,为你织开一面关于Fiber架构的基础知识网络。

BigYe_ChengPu的博客 2385
上一篇: React16源码: React中FiberRoot的源码实现
下一篇: React16源码: React中的update和updateQueue的源码实现
Wang's Blog
博客等级 码龄12年 7433粉丝 2421原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值