IOS之触摸与手势

54、iOS触摸与手势识别开发指南 本博客详细介绍了iOS开发中的触摸事件处理和手势识别机制,包括四种触摸通知方法的使用、手动实现滑动检测、使用UIGestureRecognizer进行自动手势识别以及多手指滑动的实现。通过示例项目TouchExplorer和Swipes,演示了如何检测点击、滑动等常见手势,并探讨了自定义手势识别器的实现方法。内容适合有一定iOS开发基础、希望提升手势交互功能开发能力的开发者。 阅读详情

一、触摸事件的处理方式
1.在IOS上,事件有多种形式:触摸事件,运动事件,远程控制事件。
2.触摸事件的处理方法
响应者类通过复写以下方法,可以监听触摸事件
(1)当一个或者多个手指触摸屏幕时:
- (void)touchesBegan:(NSSet *)touches withEvent:
(2)当一个或多个手指在屏幕上移动时:
- (void)touchesMoved:(NSSet *)touches withEvent:
(3)当一个或者多个手指离开屏幕时:
- (void)touchesEnded:(NSSet )touches withEvent:(UIEvent )event;
(4)当触摸序列被系统事件(诸如电话呼入)所取消时:
- (void)touchesCancelled:(NSSet *)touches withEvent:


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //1.是否响应交互事件,默认为yes,UIImageView默认no
        //self.userInteractionEnabled = NO;

        //2.多点触摸,默认是no
        self.multipleTouchEnabled= YES;

    }
    return self;
}

----------

//1.触摸开始(当用户触摸屏幕时调用视图如下方法)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //UITouch --- 手指头的个数,一个touch表示一根手指(触摸点)
    //NSSet集合,保存UITouch对象,有几个触摸点,set里面就有几个触摸对象

    //点击的次数
    UITouch *touch = [touches anyObject];
    NSLog(@"tap count :%ld",touch.tapCount);

    //触摸的阶段,触摸事件在屏幕上有一个周期,即触摸开始、移动、结束和中途取消。而通过phase可以查看当前触摸事件在一个周期中所处的状态。
    NSLog(@"phase :%ld",touch.phase);

    //在视图上的位置坐标,这里返回的位置是针对VIEW的坐标系
    CGPoint point = [touch locationInView:self];
    NSLog(@"location in View:%@",NSStringFromCGPoint(point));

    //在window上的位置
    CGPoint windowPoint = [touch locationInView:[UIApplication sharedApplication].keyWindow];
    NSLog(@"location in window :%@",NSStringFromCGPoint(windowPoint));

    //在视图上前一个点的坐标
    CGPoint prepoint = [touch previousLocationInView:self];
    NSLog(@"previouslocation in preview :%@",NSStringFromCGPoint(prepoint));


}

----------

//2.触摸移动
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    //在视图上的位置坐标
    CGPoint point = [touch locationInView:self];
    NSLog(@"location in View:%@",NSStringFromCGPoint(point));

    //在视图上前一个点的坐标
    CGPoint prepoint = [touch previousLocationInView:self];
    NSLog(@"previouslocation in preview :%@",NSStringFromCGPoint(prepoint));

    //触摸的阶段
    NSLog(@"phase :%ld",touch.phase);

}

----------

//3.触摸结束
//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    UITouch *touch = [touches anyObject];
//    //触摸的阶段
//    NSLog(@"phase :%ld",touch.phase);
//}
//触摸取消,一般用不到
//- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

@end

eg:下面介绍一个处理轻击事件的Demo:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(20, 20, 100, 100);
    [button setTitle:@"ClickAction" forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(buttonAction:)
     forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

}
----------
- (void)buttonAction:(UIButton *)btn
{
    NSLog(@"action");
}
----------
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if (touch.tapCount == 1)//单机
    {
        [self performSelector:@selector(singleTap)
                   withObject:nil
                   afterDelay:.2];
    }else if (touch.tapCount == 2)//双击
    {

        //*先取消单机,这一点很重要*
        [NSObject cancelPreviousPerformRequestsWithTarget:self
                                                 selector:@selector(singleTap)
                                                   object:nil];
        [self doubleTap];
    }       
}


----------

- (void)singleTap
{
    NSLog(@"单击");
}

- (void)doubleTap
{
     NSLog(@"双击");
}

2.运动事件

  • (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
  • (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
  • (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
    3.远程控制:(比如耳机线按钮控制音乐播放)
  • (void)remoteControlReceivedWithEvent:(UIEvent *)event;

二、事件传递的过程
这里写图片描述
这里写图片描述

三、响应者链
响应者对象是一个能接受并处理事件的对象。UIResponser是所有响应者对象的基类。
响应者链表示一系列的响应者对象。事件被交由第一响应者对象处理,如果第一响应者不处理,事件被沿着响应者链向上传递,交给下一响应者(next responder)。
下面是一个next responder的view的类目

#import "UIView+ViewController.h"

@implementation UIView (ViewController)

- (UIViewController *)viewController
{
    id next = [self nextResponder];
    while (next != nil) {

        if ([next isKindOfClass:[UIViewController class]]) {
            UIViewController *viewCtrl = next;
            return viewCtrl;
        }

        next = [next nextResponder];
    }
    return nil;
}

@end

四、手势识别器
UIGestureRecognizer类是用于检测和识别用户使用设备时所用的手势。它是一个抽象类,定义了所有手势的基本行为。以下是UIGestureRecognizer子类,用于处理具体的用户手势行为:

UITapGestureRecognizer(轻击)
UIPinchGestureRecognizer(捏合)
UIPanGestureRecognizer(平移)
UISwipeGestureRecognizer(清扫)
UILongPressGestureRecognizer(长按)
UIRotationGestureRecognizer(旋转)

其中注意的是区别两种手势(一只手单击、双击)

这里写图片描述
eg:

  //一只手单击
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapOnce)];
    tap1.numberOfTapsRequired = 1;
    tap1.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tap1];

 //一只手双击
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapTwice)];
    tap2.numberOfTapsRequired = 2;
    tap2.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tap2];
    [tap1 requireGestureRecognizerToFail:tap2];
----------
   //两只手单击
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapOnce)];
    tap3.numberOfTouchesRequired = 2;
    [self.view addGestureRecognizer:tap3];

    //两只手双击
    UITapGestureRecognizer *tap4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapTwice)];
    tap4.numberOfTapsRequired = 2;
    tap4.numberOfTouchesRequired = 2;
    [self.view addGestureRecognizer:tap4];

    //区别两种手势
    [tap3 requireGestureRecognizerToFail:tap4];
----------
     //一只手向右轻扫
    UISwipeGestureRecognizer *swip2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip2Action)];
    swip2.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swip2];   
----------  
    //捏合手势
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchAction:)];

    [self.view addGestureRecognizer:pinch];
----------
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    [self.view addGestureRecognizer:longPress];
----------
//长按手势
- (void)longPressAction:(UILongPressGestureRecognizer *)sender
{
     NSLog(@"长按");
    if (sender.state == UIGestureRecognizerStateBegan)
    {
        NSLog(@"开始");
    }else if (sender.state == UIGestureRecognizerStateChanged)
    {
        NSLog(@"移动");
    }else if (sender.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"结束");
    }
}

57、iOS 触摸与手势开发全解析 本文深入讲解了iOS开发中触摸事件和手势识别的处理方法,涵盖touchesBegan、touchesMoved等四个触摸通知方法,通过TouchExplorer应用展示了如何跟踪触摸信息,同时通过Swipes应用对比了手动检测滑动手势与使用UIGestureRecognizer自动识别手势的实现方式及优劣。适合iOS初学者及希望提升交互处理能力的开发者参考学习。 阅读详情

相关推荐

54、iOS 应用中触摸与手势识别开发指南

本文详细介绍了在iOS应用中实现触摸与手势识别的开发指南,涵盖tap、touch、滑动、多击等常见手势的检测与处理方法。通过使用UIGestureRecognizer及其子类,开发者可以轻松实现丰富的用户交互体验。内容包括触摸事件的基础处理、手势识别器的配置与优化,以及实际应用案例的解析,适用于希望提升应用交互性的iOS开发者。

brown的博客 145

iOS 手势识别(点按、长按、轻扫)

通过touches方法监听view触摸事件有以下几个缺点 1.必须得自定义view,在自定义的View当中去实现touches方法. 2.由于是在view内部的touches方法中监听触摸事件,因此默认情况下,无法让其他外界对象监听view的触摸事件 3.不容易区分用户的具体手势行为(不容易区分是长按手势,还是缩放手势)这些等. iOS 3.2之后,苹果推出了手势识别功能

LayneCheung 2594

27、iOS 手势识别与触摸处理全解析

本博客全面解析了iOS开发中的手势识别与触摸处理机制,涵盖手势识别器基础、子类化、委托方法、结合使用场景、3D Touch按压手势、触摸传递流程、命中测试原理以及优化技巧等内容。通过代码示例和流程图,帮助开发者深入理解并实现复杂的手势交互场景,如多手势组合、自定义手势识别器以及触摸性能优化,从而提升应用的交互体验和性能表现。

fox11的博客 87

iOS触摸优先级&&多手势处理

一张图说明iOS触摸优先级 手势识别器 -> 响应链的 onTouchBegin、onTouchMoved… 若手势识别器已经处理了,那么不会传递到响应链,相应的onTouchBegin、onTouchMoved…也不会被调用 多个手势的处理 通过设置gestureRecognizer的delegate,delegate实现: - (BOOL)gestureRecognizer:(...

mingC0758的博客 3989

42、iOS触摸与手势开发全解析

本文深入讲解了iOS开发中触摸与手势处理的核心技术,涵盖触摸探索、滑动检测和多点击检测三个完整应用示例,并详细展示了如何使用系统提供的手势识别器及自定义触摸逻辑。内容还包括对每个应用的拓展与优化思路,帮助开发者提升用户交互体验并掌握高级交互设计技巧。

s8t9u0v1w的博客 80

9、iOS 触摸事件处理与手势识别全解析

本文深入解析了iOS开发中的触摸事件处理与手势识别机制,涵盖了响应者链的工作原理、四个触摸通知方法的使用、手势识别器的应用以及自定义手势识别器的实现。通过示例项目TouchExplorer,帮助开发者更好地理解触摸事件的传递和处理方式,并提供了解决手势冲突的方法。适用于希望提升iOS应用交互体验的开发者参考。

devops8pract的博客 99

iOS多点触摸与手势

转自: http://book.51cto.com/art/201110/297453.htm 4.2.2 iOS多点触摸与手势 iOS赋予用户至少3.5英寸的宽广视野,在当时可谓令人眼前一亮。在这不大不小的舞台上,手指可以灵活地跳动,而在此之前,传统的触屏手机都只能用单指,而且很多都是电阻屏。但是自从iOS 横空出世之后,一切都改变了。 1)多点触摸 iOS彻底打破了传统

wangwei0327的专栏 1536

60、iOS开发:触摸手势与定位功能全解析

本文详细解析了iOS开发中的触摸手势与定位功能。内容涵盖触摸手势的检测、自定义手势的实现步骤,以及Core Location框架的基本使用和高级应用,如地理围栏和方向速度检测。同时,还介绍了手势优化、资源管理及用户体验方面的注意事项,帮助开发者打造更加实用和高效的iOS应用。

blue42的博客 139

iOS触摸事件与手势识别详解

一、iOS触摸事件 1.触摸事件的类型    触摸事件的类型一共有四个,一次完整的触摸,至少包括开始和结束两个事件    1>触摸开始,用手指(一根或者多根)按在屏幕上    2>触摸移动,手指在屏幕上发生移动(有可能会发生)    3>触摸结束,手指从屏幕上离开    4>触摸被取消,因为系统事件(例如电话呼叫)一次触摸事件被取消 2.触摸对象UITou

linfuran的博客 584

17、iOS 开发:触摸事件与手势识别全解析

本文深入解析了iOS开发中的触摸事件处理与手势识别机制,详细介绍了UIView的触摸事件回调方法,以及如何使用UIGestureRecognizer的不同子类(如UITapGestureRecognizer、UIPinchGestureRecognizer等)来实现丰富的用户交互。同时,还涵盖了手势冲突处理、触摸事件与手势协同工作的技巧,并通过多个代码示例展示了实际应用场景。适合希望提升iOS应用交互设计水平的开发者参考。

green的博客 134

58、iOS触摸事件与手势处理全解析

本文深入解析了iOS开发中的触摸事件与手势处理机制,涵盖响应链的工作原理、多点触控架构、四个触摸通知方法的使用,并通过两个实际应用(TouchExplorer和Swipes)展示了如何检测触摸事件和滑动手势。文章还分析了滑动手势的检测原理,介绍了开发中需要注意的问题、常见问题的解决方案以及应用的扩展与优化方向。通过本文,开发者可以全面掌握iOS触摸交互的核心知识,并应用于实际开发中,提升应用的交互体验。

blue42的博客 117

iOS基础 - 触摸事件与手势识别

一、iOS的输入事件 UIKit可识别三种类型的输入事件: 触摸事件 运动(加速计)事件 远程控制事件 二、UIEvent iOS中许多事件对象都是UIEvent类的实例,记录事件产生的时刻和类型 UIEvent类事件类型的enum常量: typedef NS_ENUM(NSInteger, UIEventType) { UIEventTypeTouches, UIEventT

1207

12V电源电路五层防护设计实战指南

12V电源电路是工业控制、车载电子和智能终端中最基础的供电架构,其可靠性不取决于稳压精度,而取决于对反接、浪涌、短路、过温等典型故障的响应能力。理解TVS钳位原理、P-MOSFET防反接机制及eFuse可编程限流逻辑,是构建鲁棒电源系统的核心。技术价值在于将保护从‘事后补救’升级为‘事前拦截’,显著提升产品MTBF并降低售后返修率。典型应用场景涵盖PLC辅助电源、ADAS摄像头供电、IoT网关主板等严苛环境设备。本文聚焦12V输入端到负载输出端的五层串行防护链设计,深度融合TVS选型、MOSFET导通阈值与

weixin_30983965的博客 295

ios自用学习笔记-触摸事件与手势识别

触摸事件与手势识别是ios中比较核心的功能,因为ios设备通常就只有5个实体按钮:音量大小,静音,开关与home键。因此了解、使用触摸事件与手势识别是学习ios的重点内容。 一、触摸事件 触摸事件主要有以下几个方法: -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; -(void)touchesMoved:(N

用博客见证自己的成长 956

基于 YOLO + SAM 的自动图像标注实战

摘要: 本文提出一种基于YOLO检测和SAM分割的自动化数据标注流水线方案,通过YOLO定位目标并生成检测框,再以检测框为提示驱动SAM完成精细分割,最终输出YOLO格式的标注文件。该方案将人工标注升级为半自动流程,显著提升标注效率,尤其适用于多类别、大规模图像的实例级标注需求。代码模块化设计支持模型灵活替换,并集成异常处理与进度可视化功能。虽依赖YOLO检测质量且对小目标存在局限,但作为工程落地方案,可有效降低私有数据集构建成本,适用于工业检测、遥感等场景的冷启动标注。

qq_64366203的博客 1144

ollama服务暴露公网?三步搞定Nginx反向代理配置(避坑指南)

本文详细介绍了如何通过Nginx反向代理安全地将Ollama服务暴露到公网,避免直接修改OLLAMA_HOST带来的安全隐患。文章提供了从SSL证书部署到高级安全加固的全流程实战指南,包括IP白名单、基础认证、速率限制等企业级安全措施,帮助用户实现安全可靠的外部访问。

wood5的博客 177

IOS 触摸与手势

触摸 响应者对象 在iOS中不是任何对象都能处理事件,只有继承了UIResponder的对象才能接收并处理事件.我们称之为"响应者对象". UIApplication,UIViewController,UIView都继承自UIResponder,因此它们都是响应者对象,都能够接收并处理事件. UIView????????????不接受触摸时间的三种...

165

2026年AI编程工作流实战:Claude Code与Open Code深度对比

AI编程已从代码生成工具升级为IDE级智能工作流核心能力。其本质是将大语言模型深度嵌入开发环境,通过语义理解、上下文感知与行动闭环重构传统编码范式。Claude Code以企业级知识图谱和双轨Code Review为代表,强调合规性、可审计与深度集成;Open Code则依托Skill可组合性、本地优先模型与ocp协议,实现开源驱动的灵活扩展。二者共同推动IDE从‘编辑器’进化为‘数字搭档’——能理解RFC文档、记住PR评论、自动补全带重试的fetch逻辑,并在Promise链发呆时一键重构为async/a

weixin_33739523的博客 460

iOS 第11章 触摸事件与手势

目标     了解多点触摸术语     理解响应者链     体系结构     多点触摸的基本应用   1、了解多点触摸术语 触摸事件    指手指放到 iOS 设备屏幕上 从屏幕上拖动或抬起。    iOS中触摸事件,基于多点触摸模型    多点触摸序列 NSSet*touches 一个或多个和屏幕接触的手指,识别为多点触摸序列的一部分 从第一个手指碰到屏幕开始,直到最后

杜甲同学的专栏 2649

2024年全国大学生电子设计竞赛H题_自动行驶小车

自动行驶小车(H题)【本科组/高职高专组】

qq_74395263的博客 1万+

【Agent实战】Agent Skills 深度解析:从原理到落地的完整指南

本文深入解析了Agent Skills的概念及其在AI协作中的实际应用。Skill是一种可被AI按需发现和加载的任务执行说明书,它将团队经验、规则和步骤固化为结构化文档,如SKILL.md。文章阐明了Skill与Prompt、MCP、Function Calling的关系,强调Skill专注于"怎么做"而非底层能力。重点介绍了SKILL.md的编写规范,包括元数据命名规则、描述技巧和正文内容优化,旨在帮助开发者高效构建可复用的知识资产,提升Agent的任务执行稳定性与专业性。通过清晰的示例和对比,为AI架构

少说,多做 115

iOS —— 触摸事件传递及响应与手势

iOS 的事件分为三种,触摸事件(Touch Event)、加速器事件(Motion Events)、远程遥控事件(Remote Events)。这些事件对应的类为UIResponder。本文只探究触摸事件。 Tip:在模拟器中,按住option可以两根手指操作。同时按住option+shift可以移动两根手指。 触摸事件的处理 触摸事件可以分为两部分——传递和响应。 传递:系统把该事件传到最适...

weixin_33882443的博客 1062

Arcgis中的模型构建器(ModelBuilder)技术之批量图层转KML

这段时间全省各地都在开展耕地流出图斑整改恢复工作,期间或多或少都需要村委会协助摸排举证,除了举证软件外,奥维、外业精灵等软件想必大家接触得也很多。这就经常需要我们转kmz文件给业主或者摸排人员,那么有没有什么方法在arcgis下快速批量转kmz文件呢,今天就介绍一下如何在模型构建器(ModelBuilder)构建批量图层转KML的模型。

weixin_44671081的博客 1324

IOS基础学习日志(四)手势与触摸

IOS基础学习日志(四)            今天我们主要学习了IOS手势与触摸相关的属性、定义、声明及操作,如下便是我们今天所学内容。 本章要点: 1、事件产生与分发 2、触摸 3、手势 4、手势识别器  触摸事件 Phone OS中的触摸事件基于多点触摸模型。 iPhone OS将一个或多个和屏幕接触的手指识别为多点触摸序列的一部分,该序列从第一个手指碰到屏幕开始,直到最

u012890071的专栏 1003

AMBA-CHI协议详解(七)

本节描述该协议包含的支持系统保序需求的机制。

Crazzy_M的博客 1158

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

iOS开发————触摸与手势

在iOS设备中我们必不可少的操作便是在屏幕上触摸动作和相应的手势动作,那么你的触摸和手势是如何被iOS设备所识别并且做出相应响应的呢,接下来编者将浅谈其中的奥秘。 从事件发生到其处理的对象,传递要经过特殊的一段过程。当用户点击设备屏 幕时,iOS捕捉到一系列的触摸,将其打包到UIEvent对象中并放置到应用程序 活动事件队列中。UIApplication对象从事件队列中取出最前面的事件并将其

Lerryteng的博客 819

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

上一篇: IOS之四种数据持久化方式
下一篇: 类目:nextResponder
Mainning
博客等级 码龄12年 7粉丝 16原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值