React高级用法

React 高级技巧用法笔记 学一门框架,首先要熟悉官方文档,不然框架总会学得有所欠缺。尤其当使用过React一段时候后,对此深有体会。于是便依据官方文档做了以下的学习笔记。 阅读详情

HOC

  • 含义:就是高阶组件,组件作为参数,返回的还是组件的函数
  • 特点:
    • 纯函数
    • 入参组件无法修改
    • 无副作用
  • 使用HOC的原因或好处
    1. 实现了重复代码抽离,组件复用,逻辑复用等问题
    2. 实现条件渲染
    3. 拦截入参组件的生命周期 拦截组件的渲染的性能 日志打点

HOC的实现方式

1. 属性代理 (对传入组件属性上的一些操作)

含义:就是用组件包裹一层代理组件,在代理组件上,可以做一些,对源组件的强化操作。
代理props

function HOC(WrappedComponent){
    const newProps = {name:'kevin'};
    return props => <WrappedComponent {...props} {...newProps}/>
}
// 类组件
function HOC(WrappedComponent){
    return class extends React.Component {
        render(){
            const newProps = {name:'kevin'};
            return props => <WrappedComponent {...this.props} {...newProps}/>
        }
    }
}
  • 抽象state
    function HOC(WrappedComponent){
        return class extends React.Component {
            constructor(props){
                super(props);
                this.state = {
                    name:'kevin'
                }
                this.onChange = this.onChange.bind(this)
            }
            onChange = (e)=>{
                this.setState({
                    name:e.target.value
                })
            }
            render(){
                const newProps={
                    value:this.state.name,
                    onChange:this.onChange,
                }
                return <WrappedComponent {...this.props} {...newProps}/>
            }
        }
    }
    
  • 条件渲染
    function HOC(WrappedComponent){
        return props => (
            <div>
                {
                    props.isShow ? <WrappedComponent {...this.props} /> : <p>暂无数据展示</p>
                }
            </div>
        )
    }
    function HOC(WrappedComponent){
        return class extends React.Component {
            render(){
                const newProps = {name:'kevin'};
                return props => (
                    <div style = {{width:'200px'}}>
                        <WrappedComponent {...this.props} {...newProps}/>
                    </div>
                )
            }
        }
    }
    

2. 反向继承

含义:继承传入的组件内容,即包装后的组件继承了原始组件本身,本质上是类的继承。

const HOC = WrappedComponent => {
    return class extends WrappedComponent {
        render(){
            return super.render();
        }
    }
}
// 针对组件的生命周期进行处理
function HOC(WrappedComponent){
    const didMount = WrappedComponent.prototype.componentDidMount;
    return class extends WrappedComponent{
        async componentDidMount(){
            if(didMount){
                await didMount.apply(this);
            }
        }
        render(){
            return super.render();
        }
    }
}
  • 操作state
  function HOC(WrappedComponent){
      const didMount = WrappedComponent.prototype.componentDidMount;
      const state = WrappedComponent.prototype.state;
      return class extends WrappedComponent{
                  constructor(props){
                      super(props);
                      this.state = {
                          number:0
                      }
                  }
                  async componentDidMount(){
                      if(didMount){
                          await didMount.apply(this);
                      }
                      this.setState({
                          number:123,
                          ...state,
                      })
                  }
                  render(){
                      return super.render();
                  }
              }
  }
  • 条件渲染
const HOC = (WrappedComponent) => {
  return class extends WrappedComponent {
      render(){
          if(this.props.isShow){
              return super.render();
          }else{
              return <div>暂无数据</div>
          }
      }
  }
}
  • 修改返回的react结构
const HOC = (WrappedComponent) => {
  return class extends WrappedComponent {
      render(){
          const tree = super.render();
          const newProps = {};
          if(tree?.type === 'input'){
              newProps.value = '🐂开始自律';
          }
          const props = {
              ...tree.props,
              ...newProps,
          }
          return React.cloneElement(tree,props,tree.props.children)
      }
  }
}
  • 代码复用

       // import fetchMovieListByType from '.xxx';
       // import MovieList from './components/xxxx';
    
        class Comody extends React.Component {
            state = {
                movieList:[]
            }
            async componentDidMount(){
                const movieList = await fetchMovieListByType("Comody");
                this.setState({
                    movieList
                })
            }
            render(){
                return <MovieList data={this.data.movieList} emptyTips="empty Comody">
            }
        }
    
        class Action extends React.Component {
            state = {
                movieList:[]
            }
            async componentDidMount(){
                const movieList = await fetchMovieListByType("Action");
                this.setState({
                    movieList
                })
            }
            render(){
                return <MovieList data={this.data.movieList} emptyTips="empty Action">
            }
    
        }
    

    使用HOC

    const withFetchimgHoc = (WrappedComponent,fetchingMethod,defaultProps) => {
        return class extends React.Component {
            async componentDidMount(){
                const movieList = await fetchingMethod();
                this.setState({
                    movieList
                })
            }
            render(){
                return <WrappedComponent data={this.data.movieList} {...defaultProps} {...this.props}>
            }
        }
    }
    
    withFetchimgHoc(MovieList,fetchMovieListByType("Action"),{emptyTips:'empty Action'})
    withFetchimgHoc(MovieList,fetchMovieListByType("Comody"),{emptyTips:'empty Comody'})
    
  • 组件渲染所耗费的时间

    class Home extends React.component {
        render(){
            return <h1>Hello chongqing</h1>
        }
    }
    function withTime(wrappedComponent){
        let state,end;
        return class extends wrappedComponent {
            constructor(props){
                super(props);
                start = 0;
                end = 0;
            }
            componentWillMount(){
                super?.componentWillMount();
                start = +Date.now()
            }
            componentDidMount(){
                super?.componentDidMount();
                end = +Date.now();
                this.logger(`使用组件渲染时间:${end - start}ms`)
            }
            render(){
                return super.render();
            }
        }
    }
    

Hooks

React Hooks: https://zh-hans.react.dev/reference/react
Hooks 用于函数式组件

1.useState

const [state,setState] = useState(0);

2.useEffect

// 模拟数据交互
function getUserInfo(a){
    return new Promise((resolve) => {
        setTimeout(()=>{
            resolve({
                name:a,
                age:18,
            })
        },500)
    })
}
const Demo = ({a}) => {
    const [userMessage,setUserMessage] = useState({});
    const [number,setNumber] = useState(0);

    const div = useRef();
    const handleResize = () =>{};

    useEffect(() => {
        getUserInfo(a).then(res => {
            setUserMessage(res);
        })
        console.log(div.current);
        window.addEventListener('resize',handleResize)
        /**
         * 只有当 props -> a 和 state -> number改变的时候,useEffect副作用函数重新执行
         *  如果此时数组为空,证明函数只有在初始化的时候执行一次相当于componentDidMount 
         */
    },[a,number]) // 可以是 deep object
    
    useEffect(()=> {
        const timer = setInterval(()=>console.log(666),1000);
        window.addEventListener('resize',handleResize);
        // 此函数用于消除副作用  => 可以认为是退出组件的时候去执行
        return function () {
            clearInterval(timer);
            window.removeEventListener('resize',handleResize)
        }
    },[a])
    /*------useEffect 不能用于异步,即不能如下:------------*/ 
    useEffect(async ()=>{
        // 请求数据
        const res = await getUserInfo(payload);
    },[a,number])
    useEffect(()=>{
        // declare the async data fetching function
        const fetchData = async()=>{
            const data = await fetch('https://xxx.com');
            const json = await data.json();
        }
        // call the function
        const result = fetchData().then(console.error);
        // ❌ 无效
        setData(result);
    },[])
    /*------改进------------*/
    useEffect(()=>{
        const fetchData = async()=>{
            const data = await fetch('https://xxx.com');
            const json = await response.json();
            setData(json);
        }
        // call the function
        fetchData()
            // make sure to catch any error
            .catch(console.error)
    },[])
    // 或者
    useEffect(()=>{
        fetchData();
    },[])
    const fetchData = async()=>{}
    return (
        <div ref={div}>
            <span>{userMessage.name}</sapn>
            <span>{userMessage.age}</sapn>
            <div onClick={()=>setNumber(2)}>{number}</div>
        </div>
    )
}

3.useLayoutEffect

  • 功能类似,对比一下具体执行顺序是怎样的
    • useEffect: 组件更新挂载 VDOM -> 触发真实页面DOM更新 -> 触发useEffect callback //触发所谓的第一个方法 页面闪动
    • useLayoutEffect: 组件更新挂载 VDOM -> useLayoutEffect callback -> 渲染DOM的更新 类似卡顿效果

4.useRef

作用:获取真实元素DOM标签的方式

const DemoUseRef = () => {
    const dom = useRef(null);
    const handleSubmit = () => {
        console.log(dom.current)
    }
    return (
        <div>
            <div ref={dom}>div</div>
        </div>
    )
}
// 只想存储一个值,而不触发页面的渲染、视图的更新  => 变量更新
const currentRef = useRef(1);
currentRef.current = 2;

5.useContext

作用:类似于从全局中管控一个上下文的状态

/* 用useContext方式*/
const DemoContext = () => {
   const value = useContext(Context);
   return <div>my name is {value.name}</div>
}
/* 用Context.Consumer方式 */
const DemoContext1 = () => {
   return (
       <Context.Consumer>
           {(value) => <div>my name is {value.name}</div>}
       </Context.Consumer>
   )
}
export default () => {
   return (
       <div>
           <Context.Provider value = {{name:'🐂 二娃'}}>
               <DemoContext/>
               <DemoContext1/>
           </Context.Provider>
       </div>
   )
}

6.useReducer

const DemoUseReducer = () => {
   /* number为更新后的state值,dispatchNumber 为当前的派发函数*/
   const[number,dispatchNumber] = useReducer((state,action) => {
       const {payload,name} = action;
       /*return 的值为新的state*/
       switch(name){
           case 'a':
               return state + 1;
           case 'b':
               return state - 1;
           case 'c':
               return payload;
       }
       return state;
   },0);
   return (
       <div>
           当前值{number}
           {/*派发更新*/}
           <button onClick={() =>dispatchNumber({name:'a'})}>增加</button>
           <button onClick={() =>dispatchNumber({name:'b'})}>减少</button>
           <button onClick={() =>dispatchNumber({name:'c',payload:888})}>赋值</button>
           {/*把dispatch 和state传递给子组件*/}
           <MyChildren dispatch={dispatchNumber} State={{number}}/>
           <Context.Provider value = {{dispatchNumber , number}}>
           </Context.Provider>
       </div>
   )
}

7. useMemo useCallback

进行性能优化

useMemo(()=>{
   <div>
   list.map(i => (
       <span>{i.xxx}</span>
   ))
},[list])
  • useMemo :返回callback的运行结果 // 开发中用useMemo作为缓存的依赖项
  • useCallback : 用于缓存需要在组件中多次调用的回调函数。它接受两个参数:回调函数和依赖数组。当依赖数组中的任何一个值发生变化时,useCallback 将会返回一个新的回调函数,否则将会返回之前缓存的回调函数。返回的就是callback的函数 // 在开发中用useCallback作为缓存的一个方法,在需要时调用

自定义hooks

强调的是一种函数式编程的思维
const [] = useXXX();

import {useEffect} from 'react';
const useTitle = (title) => {
    useEffect(() => {
        document.title = title;
    },[]);
}
export default useTitle
// 在别的react组件这样去调用
import useTitle from './xxx';
const App = () => {
    useTitle("1243");
    return <div>234</div>
}
React 性能优化与高级用法:从理论到实战的全面指南 通过深入理解 React 的渲染机制和性能优化原理,结合本文介绍的实战技巧和高级用法,我们可以构建出高性能、可维护的 React 应用。在实际开发中,要根据应用的具体情况选择合适的优化策略,并使用性能分析工具持续监控和改进应用性能。 阅读详情

相关推荐

React-高级教程完整版

React 高级教程完整版这标题可能有点不太贴切或符合内容,从官方上来区分这部分内容确实属于高级部分,只是由于个人原因,在后面的一些章节并没有记录在列。也为了承接上一篇,因此勉强将标题定位:“React 高级教程完整版”纯属针对个人学习记录成果,无他~~~属性类型检测(Typechecking With PropTypes)React 内置了一系列的类型那个检测功能,通过 Comp.propType

风起叶落,若是不知,岂会心动! 8246

21个React性能优化技巧

React 为高性能应用设计提供了许多优化方案,本文列举了其中的一些最佳实践。 在以下场景中,父组件和子组件通常会重新渲染: 在同一组件或父组件中调用 setState 时。 从父级收到的“props”的值发生变化。 调用组件中的 forceUpdate。 下面是提升 React 应用性能的 21 个技巧。 使用纯组件 如果 React 组件为相同的状态和 props 渲染相同的输出,则可以将其视为纯组件。 对于像 this 的类组件来说,React 提供了 PureCompon...

shadowfall的博客 921

React Navigation在移动应用中的高级用法

本文深入探讨了React Navigation库在移动应用开发中的使用,特别是如何结合StackNavigator和TabNavigator来构建复杂的导航结构。通过具体的代码示例和详细的解释,我们了解了如何为应用的不同部分创建独立的导航栈,并通过配置选项来调整标签栏的行为和样式。此外,还介绍了如何在iOS上使用模态导航来提供额外的用户交互。

weixin_33205138的博客 726

React 高级用法

简单点说,就是组件作为参数,返回值也是组件的函数,它是纯函数,不会修改传入的组件,也不会使用继承来复制其行为。使用一个函数接受一个组件作为参数传入,并返回一个继承了该传入组件的类组件,且在返回组件的 render() 方法中返回 super.render() 方法。反向继承:从“继承”角度出发,从内部操作wrappedComp,可以操作组件内部的state,生命周期和render等,功能能加强大;开发友好,可扩展性强,抽离公共的方法或组件,Hook 使你在无需修改组件结构的情况下复用状态逻辑;

weixin_44885577的博客 1033

【阅读文献笔记】FoundationStereo: Zero-Shot Stereo Matching

提出首个零样本泛化立体匹配基础模型设计 STA 模块融合单目先验提出 AHCF 模块增强代价滤波构建 100 万合成数据集 FSD + 自净化流程。

qq_46460379的博客 1265

CESM笔记——CESM1.0-CESM1.2.2-CESM2.1.3三个版本模式工作流对比

最近测试了CESM1.0,CESM1.2.2和CESM2.1.3三个版本,不同版本在workflow上有一些区别,来做点笔记。 CESM1.0 测试compset:B_2000,F_2000 workflow: 1. create_newcase -case ~/CESM/cesm1_0/script/B_2000 -compset B_2000 -res f19_g16 -mach tianhe 2. cd B_2000 (optional) env_mach_pes.xml ##修改核数,

砍柴姑娘Jourosy的博客 4952

React内存分析工具reactjs-interview-questions:Chrome DevTools高级用法

在现代前端开发中,React应用越来越复杂,组件层级越来越深,状态管理越来越庞大。随之而来的内存泄漏(Memory Leak)、性能瓶颈和资源浪费问题也日益突出。据统计,超过60%的React应用在生产环境中存在不同程度的内存问题。 **读完本文你将掌握:** - Chrome DevTools内存分析的核心功能 - React应用常见内存泄漏模式及检测方法 - 性能分析工具的高级使用技巧 - ...

gitblog_00831的博客 666

软件测试 | 手把手教你如何使用 Charles 抓包工具(电脑+手机端)

软件测试 | 手把手教你如何使用 Charles 抓包工具(电脑+手机端)一、Charles简介二、Charles下载与安装三、Charles配置(1)Charles-PC端的配置如下:(2)过滤网络请求:(3)Charles抓取HTTPS请求包前置条件:(4)Charles抓取HTTPS双向认证包:关注我,免费领取学习资料 嘿。大家好,我是4U: 做过 APP 测试的同学都会接触抓包工具,通过抓包工具可以获取到客户端与服务端接口的交互数据,在实际测试APP的过程中,我们往往会发现服务端返回 的参数字段错

leboxy的博客 4167

React Hooks 的高级用法

useState 回调函数参数详细解读,useEffect清理副作用,如何获取当前鼠标位置,自定义hooks 的高阶用法,useEffect发送请求,useRef 操作DOM 的具体步骤, react 实现跨级组件通讯,useContext的用法, useContext与``的区别

wbskb的博客 2180

PC网站实现微信扫码登录功能(二)

上篇我们介绍了怎么申请账号以及最后拿到appId和appSecret,如果有不清楚的可以看一下 PC网站实现微信扫码登录功能(一) 下面我就来说一下怎样在PC端怎么实现扫码登录功能。 一、进入官方文档网站 https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html 其实官网对过程描述的已经非常细致了。并且提供了两种扫码方式。一种是跳转二维码扫描页面,另一种是内嵌式二维码。大家可以

qq_35771266的博客 3万+

Obsidian的Git插件设置配置全流程 -- 简单的电脑端多平台同步方案及常见问题

Git同步obsidian的保姆级教程和常见问题

weixin_44370439的博客 1万+

bulletproof-react数据缓存:React Query高级用法与优化

在现代React应用开发中,高效的数据缓存机制是提升用户体验的关键因素。bulletproof-react项目通过精心设计的React Query集成,为开发者提供了一套完整的数据缓存解决方案。本文将深入探讨项目中React Query的高级用法和优化策略。 ## 为什么选择React Query? React Query(现称为TanStack Query)是一个强大的数据同步库,专门用于管...

gitblog_00486的博客 718

React Hook 高级用法

一. Hook高级使用 1.1. useReducer很多人看到useReducer的第一反应应该是redux的某个替代品,其实并不是。useReducer仅仅是useState的一种替代...

小生方勤 583

ubuntu 安装node和npm

在ubuntu中经常需要用到node ,npm,因为npm基本会和node同时安装,所以只需要安装node即可。可以使用 nvm(Node Version Manager)来管理你的 Node.js 版本。

风吹落叶的博客 2296

SAP-ABAP:SAP创建CDS视图(SQL语句创建)实例详解

通过Eclipse和ADT创建CDS视图是SAP开发中的一项重要技能。CDS视图不仅简化了数据建模,还提供了高性能和灵活性。掌握CDS视图的开发和使用,可以帮助你更好地支持SAP S/4HANA和Fiori应用的开发。

baidu_35680696的博客 1828

React - 高级用法

函数可以作为 参数 和 返回值。类似于vue中 调用子组件的方法 refs.xxx()对应Vue,就是provide,inject。Deps: 依赖项改变了,我就再次执行;Deps: 依赖项改变了,我就再次执行;形成一个生成与消费模式的上下文。用来指代具体的dom节点。函数:返回值进行缓存;

ragga-time 698

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

React-Router 高级用法

使用对象而非 JSX 来配置路由 曾经的写法: Router> Route path="/" component={App}> IndexRoute component={Dashboard} /> Route path="about" component={About} /> Route path="inbox" component={Inbox}>

YuqiRealm.com 5004

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

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】JSX:从基础语法到高级用法的深入解析

JSX(JavaScript XML)是一种语法扩展,它让我们可以在 JavaScript 中编写类似 HTML 的代码。它与 JavaScript 紧密结合,并在编译时被转换为 JavaScript 对象。

lph159的博客 3134

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

提升React应用用户体验:React Router Hash Link的5个高级用法

你是否在使用React Router时遇到过页面锚点跳转失效的问题?React Router Hash Link正是解决这个痛点的终极解决方案!这个强大的库为React Router添加了完整的哈希链接功能,让你轻松实现页面内的平滑滚动导航。本文将为你揭秘React Router Hash Link的5个高级用法,帮助你将React应用的用户体验提升到新高度。 ## 1. 基础安装与快速上手

gitblog_00872的博客 964

玩转React: Hooks 高级用法与最佳实践

介绍了React Hooks的常用Hook以及它们对应的工作流程和原理。

weixin_46529755的博客 1368

React Native性能分析工具:React DevTools高级用法

你是否曾遇到React Native应用在复杂交互时出现卡顿?是否困惑于为何看似简单的组件树却导致了严重的性能瓶颈?React DevTools(React开发工具)不仅是组件调试的基础工具,更是性能优化的强大武器。本文将深入解析React DevTools的高级功能,带你掌握组件渲染追踪、性能分析、状态调试等进阶技巧,让你在15分钟内从"盲调性能"转变为"精准优化"。 读完本文你将获得: - ...

gitblog_00665的博客 662

React Helmet高级用法:动态生成meta标签

你是否曾为React应用的SEO优化而烦恼?是否想让不同页面自动生成个性化的meta标签?本文将带你掌握React Helmet的高级用法,轻松实现meta标签的动态生成,提升应用的搜索引擎可见性和社交媒体分享效果。读完本文,你将能够:动态设置页面标题和描述、根据不同路由自动切换meta标签、在服务器端渲染中正确处理head信息,以及解决常见的SEO问题。 ## 什么是React Helmet ...

gitblog_00010的博客 1126
上一篇: react基础
下一篇: 【“小龙虾”OpenClaw面试题,抓紧收藏、赶快吸收】
Json_tan
博客等级 码龄7年 27粉丝 13原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值