【react】基础知识补充及原理【粗略版】

React 18之状态批处理 react在3月29号正式发布了18版本, 此次更新包括: 状态自动批处理,新的客户端和服务器渲染api, 过渡以及一些新的hook, 本章先说一下状态批处理的变化 状态自动批处理 18版本之前, 在合成事件之外的原生事件中(例如 setTimeout, onclick, promise) , 更新状态并不会进行批量处理(合并), 在18版本后优化了这个问题 import { useState } from 'react' function App() { const [num1, se.. 阅读详情

1.补充知识

1.PureComponent和React.Component的区别

PureComonent默认给类组件添加了一个shouldComponentUpdate的钩子函数,在这个钩子中,会对新旧状态及属性做一个浅比较,以此达到优化组件渲染的目的。

2.基于ref获取DOM元素的语法

1.给原生元素设置ref

给需要获取dom的元素设置ref='xxx',然后使用this.refs.xxx进行获取,不建议使用,在React.StrictMode模式下会报错

render() {
   return <div>
      <h2 className="title" ref="titleBox">温馨提示</h2>
   </div>;
}
componentDidMount() {
   console.log(this.refs.titleBox);
}

将ref设置为一个函数,并将ref的形参(dom元素)挂载到实例上

render() {
   return <div>
      <h2 className="title" ref={x => this.box2 = x}>友情提示</h2>
   </div>;
}
componentDidMount() {
   console.log(this.box2);
}

基于React.createRef()创建一个ref对象,初始化时为null 

box3 = React.createRef();

render() {
   return <div>
      <h2 className="title" ref={this.box3}>郑重提示</h2>
   </div>;
}
componentDidMount() {
   console.log(this.box3.current);
}

2.给组件设置ref

类组件:获取当前组件的实例,通常用于父子组件传值及方法调用

class Demo extends React.Component {
    render() {
        return <div>
            //子组件
            <Child1 ref={x => this.child1 = x} />
        </div>;
    }
    componentDidMount() {
        console.log(this.child1);
    }
}

 函数组件:获取函数组件内部某个元素。需要使用React.forwardRef()包裹子组件,这是函数子组件将拥有除props外的另一个形参:ref。通过把该形参设置给函数子组件中的某个元素,来达到获取函数子组件中dom元素的目的。

import React from "react";

const Child2 = React.forwardRef(function Child2(props, ref) {
    // 该ref形参为给子组件设置的ref值: x => this.child2 = x
    return <div>
        子组件2
        <button ref={ref}>按钮</button>
    </div>;
});

class Demo extends React.Component {
    render() {
        return <div>
            <Child2 ref={x => this.child2 = x} />
        </div>;
    }
    componentDidMount() {
       console.log(this.child2); //子组件内部的button按钮
    }
}

3.React中的插槽

基于子组件中props.children获取传递的插槽信息(子节点信息)。

  + 调用组件时,基于双闭合调用方式把插槽信息(子节点信息)传递给组件,组件内部进行渲       染

const DemoOne = function Demo(props) {
    let { title, children } = props;
    
    return <div>
      <h2>{title}</h2>
      <br/>
      {children}
    </div>;
};

//传递时
<Demo title="demo">
  //编译为vdom后作为props.children的值
  <div>我是插槽内容</div>
</Demo>

具名插槽

import React from 'react';
const DemoOne = function Demo(props) {
    let { title, children } = props;
    // 对children的类型做处理
    // 可以基于 React.Children 对象中提供的方法,对props.children做处理: 
    count\forEach\map\toArray... 在这些方法的内部,已经对children的各种形式做了处理
  
    children = React.Children.toArray(children);
    let headerSlot = [],
        footerSlot = [],
        defaultSlot = [];
    children.forEach(child => {
        // 传递进来的插槽信息,都是编译为virtualDOM后传递进来的,而不是传递的标签
        let { slot } = child.props;
        if (slot === 'header') {
            headerSlot.push(child);
        } else if (slot === 'footer') {
            footerSlot.push(child);
        } else {
            defaultSlot.push(child);
        }
    });

    return <div>
        {headerSlot}
        <br />
        <h2>{title}</h2>
        <br />
        {footerSlot}
    </div>;
};


<Demo title="学插槽">
  <span slot="footer">我是页脚</span>
  <span>我是匿名的</span>
  <span slot="header">我是页眉</span>
</Demo>

4.setState(partialState, callback)

  • callback 发生在 componentDidUpdate 周期函数之后
  • 特殊点:如果基于shouldComponentUpdate阻止了视图更新,componentDidUpdate钩子不会执行,但是callback会执行

tips:类似于Vue的$nextTick

5.setState的异步(react18)

在react18中,setState是异步的,无论是合成事件,周期函数,定时器等等。这时setState实现对状态的批处理,即将需更新的状态放入更新队列【updater】中进行处理。批处理有效减少更新次数,降低性能消耗

在这段代码中,三句setState代码不会立即更新状态及视图,代码顺次执行,遇到setState则将其加入更新队列中,最后让更新队列中的任务统一更新/渲染一次(批处理)。故上述代码render只执行一次,而三个console.log也只是打印更新之前的值。 

handle = () => {
        let { x, y, z } = this.state;
        this.setState({ x: x + 1 });
        console.log(this.state.x);

        this.setState({ y: y + 1 });
        console.log(this.state.y);

        this.setState({ z: z + 1 });
        console.log(this.state.z);
    };

   render() {
     console.log('我是render');
     ...
   }

tips:批处理的机制是微任务吗?如果不是,那么和微任务有什么区别?或者说是一种类异步操作

在定时器中时,批处理将如何进行?

这里将不等待setTimeout执行,而是先将setTimeout之外的两个setState先放入更新队列批处理渲染一次;然后1000ms后setTimeout执行,再将定时器内部的setState放入更新队列中批处理渲染

handle = () => {
        let { x, y, z } = this.state;
        this.setState({ x: x + 1 });
        this.setState({ y: y + 1 });
        console.log(this.state);

        setTimeout(() => {
            this.setState({ z: z + 1 });
            console.log(this.state);
        }, 1000);
    };

render() {
     console.log('我是render');
     ...
   }

tips:如果setTimeout不传入时间呢?

在多个时间差距不大或者时间差距极小的定时器中,分别有setState,那么批处理如何进行

在当前相同时间段内【浏览器此时可以处理的事情中】,遇到setState会立即放入更新队列

handle = () => {
        let { x, y, z } = this.state;

        setTimeout(() => {
            this.setState({ x: x + 1 });
            console.log(this.state);
        }, 1000);

        setTimeout(() => {
            this.setState({ y: y + 1 });
            console.log(this.state);
        }, 1000);

        setTimeout(() => {
            this.setState({ z: z + 1 });
            console.log(this.state);
        }, 1000);
    };

render() {
     console.log('我是render');
     ...
   }

上述代码中,由于setTimeout同时执行,时间差距极小,故setState批处理渲染一次。那么在不断更改三个setTimeout的时间中,时间差距大于2ms,就有可能被分开批处理。

6.setState的同步(react18以下)

 react18以下,在合成事件【jsx元素中基于onXxx绑定的事件】,周期函数中,setState的操作是异步的;而在定时器,手动获取DOM元素事件绑定【元素.addEventListener()】等,它将变为同步操作(立即更新状态)

handle = () => {
        let { x, y, z } = this.state;
        this.setState({ x: x + 1 });
        this.setState({ y: y + 1 });
        console.log(this.state);

        setTimeout(() => {
            this.setState({ z: z + 1 });
            console.log(this.state);
        }, 1000);
    };

render() {
     console.log('我是render');
     ...
   }

该段代码先执行打印【我是render】(此结果由setTimeout外的两个setState批处理执行得到);1s后,打印z为处理后的值,即说明定时器执行时,setState为同步,此时console.log能打印最新的z值。

7.setState的第一个参数为函数时 

setState((prevState) => { //prevState: 存储之前的状态值

   return {

      xxx: xxx

   }

})

多次修改同一个state值时,可以通过该方式获取上一轮的state值

handle = () => {
        //x为0
        for(let i=0;i<20;i++){
          //a代码
          this.setState({x: x+1});

          //b代码
          this.setState(prevState => {
             return {
                x: prevState + 1
             }
          });
        }
    };

render() {
     console.log('我是render');
     ...
   }

上述a代码由于批处理机制的原因会打印1;而b代码则是将setState的第一个参数:函数放入更新队列,把函数依次执行,最终得到叠加后的x值,进行一次渲染。

8.flushSync

 flushSync 可以刷新【updater】更新队列,即让修改状态的任务立即批处理一次。

这是一个实验性的api,不利于性能,谨慎使用。

import { flushSync } from 'react-dom';

handle = () => {
        let { x, y, z } = this.state;

        this.setState({ x: x + 1 });
        console.log(this.state.x);
        
        //此处去刷新队列,会得到最新的x和y
        flushSync(() => {
          this.setState({ y: y + 1 });
          console.log(this.state.y);
        });
        
        //此时的z会是最新的x值和y值之和
        this.setState({ z: z + 1 });
        console.log(this.state.z);
    };

   render() {
     console.log('我是render');
     ...
   }

 

 

React18 setState是同步还是异步? executionContext代表了react当前的调度状态, 如果退出了react的调度这个值就会重新变成NoContext. 也就是说, 如果你调用setState的时候并不处于react的调度状态中, 那么就会同步的去执行你的setState.这也是为什么一旦我们使用一些异步操作就会导致setState变成同步的原因, 而在react 18中这段代码变成了这样。在编写UI测试时,可以将渲染、用户事件或数据获取等任务视为与用户界面交互的“单元”。 阅读详情

相关推荐

有史以来最小的GIF/png/jpg/jpeg

昨天我对图像进行了 base64 编码,这样我就可以将它发送到 CouchDB 以测试我正在为客户编写的一些代码。它让我想起了我之前在远程服务器上设置 cookie 时所做的事情。基本上,一个小的 PHP 脚本被放在远程服务器上,它接受几个 GET 参数并根据它们的值设置一些 cookie。然后脚本输出一个 1x1 的透明 GIF。本地服务器上的 PHP 脚本生成了一个 IMG 标签,该标签链接到该图像并根据本地服务器上的 COOKIES 设置参数。

凌凌1301的博客 1417

vue中nextTick函数和react类似实现

Vue 3 仍然遵循异步更新策略,即当组件状态发生变化时,Vue 不会立即更新 DOM,而是将这些更新任务放入一个队列中。)发生变化时,React 不会立即重新渲染组件和更新 DOM,而是将这些更新操作放入一个队列中。当事件循环回到浏览器主线程时,React 会批量处理这些更新,一次性重新渲染受影响的组件并更新真实的 DOM。那样精确地绑定到 React 更新周期,但对于大多数需要在 DOM 更新后执行操作的场景来说,这两种方法通常是足够可靠的。,可以实现类似的在 DOM 更新后执行操作的需求。

Yan的博客 4549

基于Halcon与C#的PCB焊接缺陷智能检测系统开发实战(附完整源码与项目文档)

本文详细介绍了基于Halcon与C#的PCB焊接缺陷智能检测系统开发实战,涵盖机器视觉技术、硬件选型、图像处理算法及C#上位机开发。通过实战案例展示如何实现高效、准确的PCB焊接缺陷检测,提升生产效率与质量,并附完整源码与项目文档。

mango的博客 219

React中的flushSync与Vue中的nextTick的比较

在React中,当需要更新UI时,React会将更新操作放入一个队列中,然后异步地执行这些更新操作。和React类似,当需要更新UI时,Vue也会将更新操作放入一个队列中,然后异步地执行这些更新操作。但是有时候,我们需要在DOM更新之后立即执行一些操作,比如获取更新后的DOM元素。nextTick会在DOM更新之后执行回调函数,确保我们可以在更新后立即访问到最新的DOM元素。总的来说,flushSync和nextTick都是非常有用的工具,它们可以帮助我们更好地处理异步更新,提升应用的性能和用户体验。

weixin_54931655的博客 3624

Zemax非序列模式微透镜阵列仿真:从建模到优化完整指南

光线追迹是光学系统仿真的核心技术,其原理基于几何光学与物理光学的光线传播模型,通过精确计算光线在光学元件中的折射、反射与散射路径,实现对系统性能的预测与评估。在微透镜阵列等复杂多通道光学系统中,传统序列模式因光线路径受限而难以准确模拟串扰与杂散光,非序列光线追迹技术则凭借其灵活的空间传播机制成为关键手段。该技术广泛应用于激光整形、光束匀化、3D传感及光场成像等领域,能够有效支持阵列结构设计与优化。Zemax非序列模式为微透镜阵列仿真提供了完整的建模、优化与公差分析流程,是光学工程师进行复杂系统设计的核心工具

weixin_29967003的博客 337

CubeMX配置ADC+DMA避坑实战:如何避免采样过快导致的系统崩溃

本文针对STM32开发中常见的ADC采样过快导致程序卡死问题,提供了基于CubeMX的实战避坑指南。通过分析ADC与DMA协作机制,详解时钟配置、采样时间、DMA缓冲区长度及中断设置等关键步骤,帮助开发者从源头规避系统崩溃风险,实现稳定可靠的数据采集。

weixin_28273593的博客 324

React hooks 学习笔记 - useEffect

概念理解:什么是Effect Pure function(纯函数) 给一个 function 相同的参数,永远会返回相同的值,并且没有副作用;这个概念拿到 React 中,就是给一个 Pure component 相同的 props, 永远渲染出相同的视图,并且没有其他的副作用;纯组件的好处是,容易监测数据变化、容易测试、提高渲染性能等; 副作用(Side Effect)是指一个 functio...

kotoriyou的博客 1721

数学建模美赛O奖论文研读启示录——从模仿开始

数学建模美赛O奖论文哪些地方比较出彩?我们可以从中学到什么东西?可以从哪些地方进行模仿?我总结了一些O奖论文里我认为比较好的地方,跟大家一起学习交流!

小宇的修炼之路 5429

React16常用api解析以及原理剖析

React16常用api解析以及原理剖析 目录 Vue 与 React 两个框架的粗略区别对比 react 16 版本常见 api react 生命周期 react 事件机制 react.Component 如何实现组件化以及高阶组件的应用 setState 异步队列数据管理 react Fiber 架构分析 react hooks dom 的 diff 算法 snabbdo...

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

从流量到凭证:实战解析SMB协议中的NTLMv2/v1哈希提取与破解

本文详细解析了SMB协议中NTLMv2/v1哈希的提取与破解实战技巧。从流量捕获、哈希格式处理到Hashcat高效破解,提供了一套完整的操作指南。文章特别强调了NTLMv2和NTLMv1哈希的区别及处理要点,并分享了防护建议与检测方法,帮助安全人员提升渗透测试效率。

weixin_30642561的博客 116

Matlab基于PSO-MVMD粒子群算法优化多元变分模态分解

Matlab基于PSO-MVMD粒子群算法优化多元变分模态分解

机器学习之心的博客,关注并私信文章链接,获取对应文章源码和数据。 518

react-router 的API及原理

由于篇幅限制,pdf文档的详解资料太全面,细节内容实在太多啦,所以只把部分知识点截图出来粗略的介绍,每个小节点里面都有更细化的内容!点击【学习资料】即可获取!知识点截图出来粗略的介绍,每个小节点里面都有更细化的内容!点击【学习资料】即可获取![外链图片转存中…(img-B5pmSE0B-1711720787078)][外链图片转存中…(img-C3QBdqlD-1711720787079)]点击【学习资料】

2401_84003941的博客 941

Coze工作流的代码无法安装第三方模块(依赖)怎么办?(如何解决Coze工作流代码缺少模块(依赖)的问题)

Coze工作流的代码无法安装第三方模块(依赖)怎么办?(如何解决Coze工作流代码缺少模块(依赖)的问题)

XiaoqiangClub的博客 4365

前端 SPA 单页应用数据统计解决方案 (ReactJS / VueJS)

前端 SPA 单页应用数据统计解决方案 (ReactJS / VueJS) 一、百度统计的代码: UV PV 统计方式可能存在问题 在 SPA 的前端项目中 数据统计,往往就是一个比较麻烦的事情,React 和 Vue 也是一样。 在 发现问题之前,我们得来思考下 百度统计的 统计原理 是什么? 1-1: 百度统计代码 var _hmt = _hmt || []; (fu...

ankuailan3925的博客 794

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

WINCC7.3破解文件

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

react16常见api以及原理剖析

Vue与React两个框架的粗略区别对比Vue 的优势包括:模板和渲染函数的弹性选择简单的语法及项目创建更快的渲染速度和更小的体积React 的优势包括:更适用于大型应用和更好的可...

前端下午茶 863

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

2024年最全React:基础知识学习,前端开发应该如何准备面试

React是用于构建用户界面的JavaScript 库,围绕React的技术栈主要包括:React, redux, react-redux, react-router, …React.createElement(“button”, {onClick: ()=>{console.log(“点击了按钮”)}}, “这是按钮标签包裹的内容”)概念:React将DOM抽象为虚拟DOM,虚拟DOM其实就是用一个对象来描述DOM,通过对比前后两个对象的差异,最终只把变化的部分重新渲染,提高渲染的效率。

2401_84411323的博客 328

深度学习工具包 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 初探 [八] react-router 基本使用与侧边栏切换功能

react-router 说明 1、react-router 相关理解 2、SPA的理解 3、路由的理解 4、前端路由的实现 react-router 的基本使用 =====督促自己完成======

Sandy_zhi的博客 1842

mongodb 导出数据表_MongoDB/Express/ReactJS/Node打造前后端分离精品项目《豆书》之项目介绍...

本课程配套视频教程 https://www.bilibili.com/video/BV12f4y127EA/本课程配套图文教程 https://www.jianshu.com/nb/46065998本课程配套图文教程 https://www.songbo.info/column/5豆约翰理念目前互联网上各种学习资源很多,讲知识点的多,讲综合实战项目的少,豆约翰准备填补这个“空白”。约翰老师认为在项...

weixin_29091105的博客 151

【React】React源码梳理笔记(十一)

前言 结合前面知识,本篇粗略实现下fiber。 虚拟dom处理 先对babel转译的createElement进行编写,完成基础功能,再给react-dom。 createElement.js function createElement(type, config, ...children) { delete config.__self; delete config.__s...

不忘初心,坚定道路! 234

react 得到param_「推荐」React 通信之 Redux,看这一篇就能掌握

背景React 组件 componentDidMount 的时候初始化 Model,并监听 Model 的 change 事件,当 Model 发生改变时调用 React 组件的 setState 方法重新 render 整个组件,最后在组件 componentWillUnmount 的时候取消监听并销毁 Model。第一部分 Redux的出现存在即合理如下图左侧所示,react单向流动的特性,导...

weixin_34138673的博客 182
上一篇: vxe-table使用碰到的问题
谭CV
博客等级 码龄9年 73粉丝 85原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值