React组件化开发实现TodoList待做列表

React组件化实战:从零打造智能TodoList清单 在传统Web开发中,我们常常需要直接操作DOM元素来更新界面,就像用铅笔在纸上反复涂改——效率低且容易出错。React提出的组件化开发,如同将网页拆解为可复用的"积木块",每个积木(组件)都包含完整的HTML、CSS和JS逻辑。接下来让我们用react组件化思想搭建一个Todolist任务清单。组件分层 : TodoList 管理全局状态, TodoForm 处理输入, Todos 专注展示响应式数据 : useState 驱动视图自动更新,状态变更效率提升63% 阅读详情

第一章:效果展示

在这里插入图片描述

第二章:实现步骤

一、通过 create-react-app 初始化项目

二、拆分组件

Footer:展示已完成进度
Header:输入添加 Todo Item
Item组件:选项
List组件:包含选项

文件结构如下:
在这里插入图片描述

三、各组件代码

1. App.jsx

import React, { Component } from 'react'
import Header from './components/Header'
import List from './components/List'
import Footer from './components/Footer'
import './App.css'

export default class App extends Component {
	//状态在哪里,操作状态的方法就在哪里

	//初始化状态
	state = {todos:[
		{id:'001',name:'吃饭',done:true},
		{id:'002',name:'睡觉',done:true},
		{id:'003',name:'打代码',done:false},
		{id:'004',name:'逛街',done:false}
	]}

	//addTodo用于添加一个todo,接收的参数是todo对象
	addTodo = (todoObj)=>{
		//获取原todos
		const {todos} = this.state
		//追加一个todo
		const newTodos = [todoObj,...todos]
		//更新状态
		this.setState({todos:newTodos})
	}

	//updateTodo用于更新一个todo对象
	updateTodo = (id,done)=>{
		//获取状态中的todos
		const {todos} = this.state
		//匹配处理数据
		const newTodos = todos.map((todoObj)=>{
			if(todoObj.id === id) return {...todoObj,done}
			else return todoObj
		})
		this.setState({todos:newTodos})
	}

	//deleteTodo用于删除一个todo对象
	deleteTodo = (id)=>{
		//获取原来的todos
		const {todos} = this.state
		//删除指定id的todo对象
		const newTodos = todos.filter((todoObj)=>{
			return todoObj.id !== id
		})
		//更新状态
		this.setState({todos:newTodos})
	}

	//checkAllTodo用于全选
	checkAllTodo = (done)=>{
		//获取原来的todos
		const {todos} = this.state
		//加工数据
		const newTodos = todos.map((todoObj)=>{
			return {...todoObj,done}
		})
		//更新状态
		this.setState({todos:newTodos})
	}

	//clearAllDone用于清除所有已完成的
	clearAllDone = ()=>{
		//获取原来的todos
		const {todos} = this.state
		//过滤数据
		const newTodos = todos.filter((todoObj)=>{
			return !todoObj.done
		})
		//更新状态
		this.setState({todos:newTodos})
	}

	render() {
		const {todos} = this.state
		return (
			<div className="todo-container">
				<div className="todo-wrap">
					<Header addTodo={this.addTodo}/>
					<List todos={todos} updateTodo={this.updateTodo} deleteTodo={this.deleteTodo}/>
					<Footer todos={todos} checkAllTodo={this.checkAllTodo} clearAllDone={this.clearAllDone}/>
				</div>
			</div>
		)
	}
}

2. App.css

/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

3. Footer 组件

index.jsx
import React, { Component } from 'react'
import './index.css'

export default class Footer extends Component {

	//全选checkbox的回调
	handleCheckAll = (event)=>{
		this.props.checkAllTodo(event.target.checked)
	}

	//清除已完成任务的回调
	handleClearAllDone = ()=>{
		this.props.clearAllDone()
	}

	render() {
		const {todos} = this.props
		//已完成的个数
		const doneCount = todos.reduce((pre,todo)=> pre + (todo.done ? 1 : 0),0)
		//总数
		const total = todos.length
		return (
			<div className="todo-footer">
				<label>
					<input type="checkbox" onChange={this.handleCheckAll} checked={doneCount === total && total !== 0 ? true : false}/>
				</label>
				<span>
					<span>已完成{doneCount}</span> / 全部{total}
				</span>
				<button onClick={this.handleClearAllDone} className="btn btn-danger">清除已完成任务</button>
			</div>
		)
	}
}
index.css
/*footer*/
.todo-footer {
  height: 40px;
  line-height: 40px;
  padding-left: 6px;
  margin-top: 5px;
}

.todo-footer label {
  display: inline-block;
  margin-right: 20px;
  cursor: pointer;
}

.todo-footer label input {
  position: relative;
  top: -1px;
  vertical-align: middle;
  margin-right: 5px;
}

.todo-footer button {
  float: right;
  margin-top: 5px;
}

4. Header 组件

index.jsx
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {nanoid} from 'nanoid'
import './index.css'

export default class Header extends Component {

	//对接收的props进行:类型、必要性的限制
	static propTypes = {
		addTodo:PropTypes.func.isRequired
	}

	//键盘事件的回调
	handleKeyUp = (event)=>{
		//解构赋值获取keyCode,target
		const {keyCode,target} = event
		//判断是否是回车按键
		if(keyCode !== 13) return
		//添加的todo名字不能为空
		if(target.value.trim() === ''){
			alert('输入不能为空')
			return
		}
		//准备好一个todo对象
		const todoObj = {id:nanoid(),name:target.value,done:false}
		//将todoObj传递给App
		this.props.addTodo(todoObj)
		//清空输入
		target.value = ''
	}

	render() {
		return (
			<div className="todo-header">
				<input onKeyUp={this.handleKeyUp} type="text" placeholder="请输入你的任务名称,按回车键确认"/>
			</div>
		)
	}
}
index.css
/*header*/
.todo-header input {
  width: 560px;
  height: 28px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px 7px;
}

.todo-header input:focus {
  outline: none;
  border-color: rgba(82, 168, 236, 0.8);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}

5. Item 组件

index.jsx
import React, { Component } from 'react'
import './index.css'

export default class Item extends Component {

	state = {mouse:false} //标识鼠标移入、移出

	//鼠标移入、移出的回调
	handleMouse = (flag)=>{
		return ()=>{
			this.setState({mouse:flag})
		}
	}

	//勾选、取消勾选某一个todo的回调
	handleCheck = (id)=>{
		return (event)=>{
			this.props.updateTodo(id,event.target.checked)
		}
	}

	//删除一个todo的回调
	handleDelete = (id)=>{
		if(window.confirm('确定删除吗?')){
			this.props.deleteTodo(id)
		}
	}


	render() {
		const {id,name,done} = this.props
		const {mouse} = this.state
		return (
			<li style={{backgroundColor:mouse ? '#ddd' : 'white'}} onMouseEnter={this.handleMouse(true)} onMouseLeave={this.handleMouse(false)}>
				<label>
					<input type="checkbox" checked={done} onChange={this.handleCheck(id)}/>
					<span>{name}</span>
				</label>
				<button onClick={()=> this.handleDelete(id) } className="btn btn-danger" style={{display:mouse?'block':'none'}}>删除</button>
			</li>
		)
	}
}
index.css
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

6. List 组件

index.jsx
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Item from '../Item'
import './index.css'

export default class List extends Component {

	//对接收的props进行:类型、必要性的限制
	static propTypes = {
		todos:PropTypes.array.isRequired,
		updateTodo:PropTypes.func.isRequired,
		deleteTodo:PropTypes.func.isRequired,
	}

	render() {
		const {todos,updateTodo,deleteTodo} = this.props
		return (
			<ul className="todo-main">
				{
					todos.map( todo =>{
						return <Item key={todo.id} {...todo} updateTodo={updateTodo} deleteTodo={deleteTodo}/>
					})
				}
			</ul>
		)
	}
}
index.css
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}

7. 渲染组件到页面 index.js

//引入react核心库
import React from 'react'
//引入ReactDOM
import ReactDOM from 'react-dom'
//引入App
import App from './App'

ReactDOM.render(<App/>,document.getElementById('root'))

四、启动项目

在项目根目录下,打开控制台,输入 npm start 或 yarn start 启动项目

第三章:注意要点

  1. 拆分组件、实现静态组件,注意:className、style的写法
  2. 动态初始化列表,如何确定将数据放在哪个组件的state中?
    ——某个组件使用:放在其自身的state中
    ——某些组件使用:放在他们共同的父组件state中(官方称此操作为:状态提升)
  3. 关于父子之间通信:
    (1)【父组件】给【子组件】传递数据:通过props传递
    (2)【子组件】给【父组件】传递数据:通过props传递,要求父提前给子传递一个函数
  4. 注意defaultChecked 和 checked的区别,类似的还有:defaultValue 和 value
  5. 状态在哪里,操作状态的方法就在哪里
【demo】使用React+Webpackt做一个简单的todolist 使用Reactk实现一个简单的todolist,实现基本的增删功能 创建项目 创建的todo主要采用node包的方式,使用webpack打包 初始化项目并创建一些基础文件 初始化项目之后,就需要安装所需要的库及其依赖。npm安装方式可以为开发环境或生产选择所安装的依赖。 安装完所需要的依赖之后,配置webpack。 webpack.config.js: var pat 阅读详情

相关推荐

react实现todolist

使用React做一个简单的todolist小demo新建一个react项目 todolist写出todolist的基本结构用数组把数据存储起来监听输入框里面的内容,与state 里的inputValue绑定起来实现增加功能实现删除功能将li提取出来用单独作为一个组件,利用props传值修改删除功能,实现子组件通过父组件传过来的方法对父组件通信 新建一个react项目 todolist // 创建r...

qq_37473645的博客 1314

React 入门学习(六)-- TodoList 案例

大家好,我是小丞同学,一名准大二的前端爱好者 这篇文章是学习 React 练习中 TodoList 案例的操作笔记 非常感谢你的阅读,不对的地方欢迎指正 愿你忠于自己,热爱生活 引言 TodoList 案例在前端学习中挺重要的,从原生 JavaScript 的增删查改,到现在 React 的组件通信,都是一个不错的案例,这篇文章主要记录,还原一下通过 React 实现 TodoList 的全过程 一、拆分组件 首先第一步需要做的是将这个页面拆分成几个组件

小丞同学 1159

todolist的五种写法(原生、vue2、vue3、react类组件,react函数组件)

通过输入框输入任务,点击"Add Task"按钮将任务添加到任务列表中。同时,将任务保存在名为"tasks"的数组中,以便在页面刷新后能够保留之前添加的任务。使用React的类组件来实现一个简单的todolist。组件的状态包括一个todos数组和一个newTodo字符串,分别用于存储待办事项列表和用户输入的新待办事项。方法中,使用JSX语法来渲染组件的结构。每个todo都有一个删除按钮,点击按钮时,函数用于将输入框中的值添加到任务列表中,并清空输入框。函数,将保存的任务重新添加到任务列表中。

温暖前端的博客 1966

jQuery LigerUI 使用教程表格篇(1)

阅读目录 第一个例子 数据结构 两种绑定数据的方式 配置column 自定义表头 自定义单元格 排序与分页 事件与方法 第一个例子 简介 ligerGrid是ligerui系列插件的核心控件,用户可以快速地创建一个美观,而且功能强大的表格,支持排序、分页、多表头、固定列等等。 支持本地数据和服务器数据(配置data或者url) 支持排序和分页(...

weixin_30393907的博客 628

react-task-list:使用React构建简单的任务列表

React任务列表 使用React构建一个简单的任务列表。 查看部署 Github页\u9762=

react-tasklist:使用React的任务列表打字稿

react-tasklist:使用React的任务列表打字稿

21、react 制作一个 todoList 组件

上一篇博文我们说了 react 脚手架创建并使用一个组件,OK,那么重点来喽,每个框架学习的必做案例,todoList 功能。

“跟他人学,和自己比” 1501

react-native-timeline:React本机时间轴组件

React本机时间轴列表 适用于React Native的Easy Timeline组件 安装 yarn add react-native-timeline 或者 npm install --save react-native-timeline 参考 即将推出... 屏幕截图 即将推出... 例子 您可以在此仓库中找到项目 执照 该项目已获得MIT许可

REACT学习--第二章实战案例:任务列表

任务列表可以处理成组件,未完成和已完成可以用一个组件。哦刚才导错了现在改过来了出现新问题了。没有太多样式主要是有对应的功能。看得出AI写代码也需要考虑很多。费一些脑细胞虽然他可能没脑子。我有预感要服务器繁忙了。

chestnut_orenge的博客 446

todo-list-react:一个简单的React应用程序来管理任务列表

待办事项清单应用 这是一个由React(Redux)JS制作的待办事项列表应用程序。 特征 创建待办事项 将待办事项标记为已完成 编辑待办事项(更改名称) 删除待办事项 显示待办事项总数 当用户将鼠标悬停在待办事项上时,将显示编辑和删除图标 演示版 截屏 技术领域 Javascript(ES6) React JS(挂钩) Redux JS 萨斯(SCSS) 用法 下载代码。 在您的终端中,转到目录并运行以下命令。 $ npm install $ npm start 贡献者 爱德华·诺拉米安(Edward Noramirian) GitHub: 电子邮件:

react-task-list:React任务列表

Create React App入门 该项目是通过引导的。 可用脚本 在项目目录中,可以运行: npm start 在开发模式下运行应用程序。 打开在浏览器中查看它。 如果您进行编辑,则页面将重新加载。 您还将在控制台中看到任何棉绒错误。 npm test 在交互式监视模式下启动测试运行器。 有关更多信息,请参见关于的部分。 npm run build 构建生产到应用程序build文件夹。 它在生产模式下正确捆绑了React,并优化了构建以获得最佳性能。 生成被最小化,并且文件名包括哈希值。 您的应用已准备好进行部署! 有关更多信息,请参见关于的部分。 npm run eject 注意:这是单向操作。 eject ,您将无法返回! 如果您对构建工具和配置选择不满意,则可以随时eject 。 此命令将从您的项目中删除单个生成依赖项。 相反,它将所有配置文件和传递依赖项(we

React 入门:实战案例 TodoList 组件列表动态初始化

本文实现 TodoList 组件列表动态初始化。

将PHP Web开发进行到底 625

K210视觉项目上位机避坑指南:解决C#解析ESP8266 TCP图像流的乱码、卡顿与连接中断

本文详细解析了K210与ESP8266在视觉项目中的上位机开发问题,重点解决TCP图像流解析中的乱码、卡顿与连接中断问题。通过自定义协议、JPEG流重组、TCP连接优化等实战技巧,提升系统稳定性和性能,适用于嵌入式视觉开发者和C#上位机程序员。

weixin_28730131的博客 402

初探react,用react实现一个todoList功能

初探react,用react实现一个todoList功前言一、react基础1. react简介2. 开发环境搭建3. 工程目录文件简介4. react中最基础的JSX语法二、使用react编写TodoList功能1. 页面构思2. React中的响应式设计思想和事件绑定3. 实现TodoList新增删除功能(1)新增功能(2)删除功能三、对TodoList功能进行进阶操作1. JSX语法细节补充(1)自动转义(2)光标聚焦2. 拆分组件与组件之间的传值3. TodoLi

moandaylab 4110

电流镜结构实战:从零理解MOS管偏置电路设计(附吴金课程补充)

本文深入解析电流镜结构在MOS管偏置电路设计中的关键作用,从基本原理到实战应用全面覆盖。通过分析偏置电路的核心原理、破解设计难题的实用技巧,以及进阶优化策略,帮助工程师掌握这一模拟电路设计的核心技术。特别适合需要理解电流镜结构和基准电路设计的读者参考学习。

ujm5678901的博客 256

从零到千兆:KSZ9031 PHY芯片在Zynq PS端的驱动移植心路历程

本文详细记录了在Xilinx Zynq-7000平台(基于XC7Z020芯片)上,为KSZ9031千兆以太网PHY芯片移植LwIP协议栈驱动的完整过程。从硬件连接配置、Vivado工程设置到LwIP库的深度修改与调试,分享了解决PHY识别、自协商及性能优化等关键问题的实战经验,助力开发者实现稳定的千兆网络连接。

honey的博客 1117

React实现Todolist

一个todolist基本的功能点包括: 点击复选框标记完成或者未完成,且相应的文字出现删除线 从列表中移除item 添加item 首先它是由todolist title 、todolist、和addtodo三部分组成。由于todolist title 和addtodo比较简单,在这里只将todolist拆分成组件。 创建一个ListItem组件。含有一个render方法 class List...

csdn_zsdf的博客 9883

【分享】ArcGIS实现分子分母等标注实用技巧

前言 标注是显示在地图上的文字信息,是出图中不可或缺的重要元素,为了标注的样式丰富,摆放的位置灵活,因此给制图出图带来不少难度,以下分享几种本人在ArcGIS中的标注方法,实现上下标注、换行标注或分式标注的实用技巧。 普通模式与高级模式 默认为普通模式,勾选高级开启高级模式。 普通二分式标注(普通模式) [DLBM] & vbnewline & [DLMC] 标注效果展示 分行二分式标注(普通模式) [DLBM]& vbnewline & "——————" &

杨港 3万+

react 组件化开发_生命周期_表单处理

我们从上面可以清楚地看到,组件本质上就是类和函数,但是与常规的类和函数不同的是,组件承载了渲染视图的 UI 和更新视图的 setState 、 useState 等方法。React 在底层逻辑上会像正常实例化类和正常执行函数那样处理的组件。因此,函数与类上的特性在 React 组件上同样具有,比如原型链,继承,静态属性等,所以不要把 React 组件和类与函数独立开来。接下来,我们一起着重看一下 React 对组件的处理流程。

小白小白从不日别的博客 2399

nRF52382低功耗蓝牙应用开发之入门教程-软件烧录

准备工作在上一篇文章讲过了,这里就讲讲nRFgo studio的使用 硬件准备: J-link:2线 供电:3.3V 如下图打开nRFgo studio界面介绍, 2、如果J-link正常,如下图 3、如果蓝牙芯片正常 4、烧录过程,如果蓝牙芯片之前有烧录过程序,需先点擦除,再点烧录 5、烧录代码路劲,例如 F:\nRF\SDK\nRF5_SDK_15.2.0_...

LinQiPing233的博客 1947

Qualcomm平台下基于QSEE的指纹识别方案移植之四TA移植

本文只介绍TA移植的过程,不做技术分析,关于TA开发另做记录。 一、TA介绍 TA,Trusted application 可信应用,是运行于QSEE中的可执行程序。 指纹TA文件如下,形式一般是 xxx.mbn; xxx.b0 ~ xxx.b6, xxx.flist, xxx.mdt; xxx.mbn 可以理解为其它几个文件的集合,签名的时候用的就是这个文件,签完名之后,有对应的工具将它...

梦路遥 7549

react 实现简单的todolist功能

需求:利用react组件化实现todolist的功能 首先要理解父子组件的传值方式,父组件通过属性在自组件绑定值或者方法,然后子组件利用this.props.属性名获取父组件传来的方法或者属性值。 首先在父组件中实现输入框和提交按钮 <div className="todolist"> <div className='todolisttop'&g...

Hhjian524的博客 558

Hermes 教程 03:Skills 系统

摘要:Hermes Skills是一种自我改进机制,可将解决问题的经验保存为可复用技能文档。v0.13.0版本遵循agentskills.io开放标准,与Claude Skills互通。技能创建流程包括发现问题、创建技能文件、加载使用和优化更新四个阶段。系统提供技能检索和自维护机制(Curator),支持技能媒体路由和多种管理命令。内置技能涵盖开发调试、创意头脑风暴等场景,通过积累技能使Hermes更适应用户需求。

程序猿_三产 734

React组件的组合使用-TodoList案例

文章目录一、功能界面的组件化编码流程(通用)二、组件化三、静态组件2.1、创建组件2.3、引入静态文件2.4、把App.jsx、App.css拆分至各个组件2.4、样式结构效果四、动态初始化列表4.1、在App.jsx 初始化状态4.2、通过props在List组件接收数据,App.jsx传给List4.3、通过props在Item组件接收数据,List传给Item,渲染页面4.4、效果五、 点击回车添加todo项5.1、总体思路:5.2、nanoid5.3、监听键盘输入,拿到数据,通过App传入的函数,调

Qiuxuntao的博客 1763

4.4 直流无刷电机(BLDC):控制器硬件设计

摘要 本文详细阐述了直流无刷电机(BLDC)控制器的硬件设计要点。控制器硬件主要包括微处理器单元、功率驱动模块、信号检测电路、通信接口和电源管理模块。在微处理器选型方面,分析了ARM Cortex-M系列、DSP等架构的适用场景,并对比了不同处理器的性能参数。功率驱动模块设计重点包括栅极驱动电路、逆变桥热管理和电流保护机制。信号检测部分介绍了位置传感器接口和模拟信号调理技术。此外,还讨论了通信接口设计、电源管理方案以及硬件布局与EMC设计规范。最后强调了硬件测试验证的重要性,包括故障注入测试等验证方法。整体

技术工作者 185

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

初学react(6)——实践(实现todoList)

学完了react的基础知识,愁在没有项目练手,比较好的做法是去模仿其它网站开发。去模仿大型的网站又怕耗费的时间太多,所以我选择模仿比较简单的todoList,优点在于页面简单,不用耗费太多时间,而缺点恰是页面过于简单,很多知识点都用不上,不过对于新手来说,先从简单开始,从简单的开发去巩固react的基本语法和开发思想。 (注:所有代码放在gitbubt上https://github.com/Ch...

李大人的博客 2824

深度学习工具包 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 学习小结(三)
APythonC
博客等级 码龄7年 23粉丝 58原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值