初学android——简易计算器的制作

树莓派提升计划 Android应用科学计算器开发之MainActivity类实现 2021SC@SDUSC 如同C的main函数,Android的程序入口就是MainActivity类,在这个科学计算器程序中的MainActivity类用来实现与前端用户交互,按键的监听和数学表达式的输入。 首先是创建窗体的入口函数——onCreate函数,用来初始化Activity实例对象。 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 阅读详情

       之前有好好完成老师留过的C++大作业,使用MFC制作通讯录。所以用AS写一个安卓的计算器并不是很难,但还是想上手操作一下,写一个只有简单加减乘除运算的小计算器,后面可能会考虑加一些其他的稍微复杂的计算功能。下面是步骤。

       1.首先创建一个empty activity,取名为MyStudyCalculator。

       2.打开activity_main.xml文件,创建两个编辑框(EditText)、四个按钮(Button)、一个文本框(TextView),并设置相应的id。其中编辑框作用是让用户填入两个数字,四个按钮分别对应四种不同的运算(需要对按钮分别添加响应事件),文本框用于显示运算结果。我另外添加了两个文本框,一个用于显示标题,一个显示作者,对于该计算器来说没有任何作用。下面给出代码:

   //第一个数字
    <EditText
        android:id="@+id/first"
        android:layout_width="85dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="56dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="168dp"
        android:hint="@string/num1"
        app:layout_constraintEnd_toStartOf="@+id/second"
        app:layout_constraintHorizontal_bias="0.621"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    //第二个数字
    <EditText
        android:id="@+id/second"
        android:layout_width="85dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="64dp"
        android:layout_marginTop="168dp"
        android:hint="@string/num2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    //第二个数字
    <TextView
        android:id="@+id/res"
        android:layout_width="96dp"
        android:layout_height="33dp"
        android:layout_marginBottom="84dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.481"
        app:layout_constraintStart_toStartOf="parent" />

    //加法按钮
    <Button
        android:id="@+id/button1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="260dp"
        android:onClick="SUM"
        android:text="+"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.391"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    //减法按钮
    <Button
        android:id="@+id/button2"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="30dp"
        android:layout_marginEnd="148dp"
        android:layout_marginTop="8dp"
        android:onClick="SUB"
        android:text="-"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.595" />

    //乘法按钮
    <Button
        android:id="@+id/button3"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="152dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:onClick="MUL"
        android:text="*"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.393"
        app:layout_constraintStart_toStartOf="parent" />

    //除法按钮
    <Button
        android:id="@+id/button4"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="148dp"
        android:layout_marginTop="8dp"
        android:onClick="DIV"
        android:text="/"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.678" />

    //标题
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="36dp"
        android:text="丑陋的而且只能算加减乘除的计算机"
        android:textSize="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    //作者
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="11dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="496dp"
        android:text="TimberWolf"
        android:textSize="10dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.99"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

3.打开MainActivity.java写四个按钮对应的方法,代码如下:

//加法
    public void SUM(View view) {
        EditText first = (EditText)findViewById(R.id.first);
        EditText second = (EditText)findViewById(R.id.second);
        TextView  res = (TextView)findViewById(R.id.res);
        double num1 = 0;
        double num2 = 0;
        double ans = 0;
        String numfirst = first.getText().toString();
        String numsecond = second.getText().toString();
        num1 = Double.parseDouble(numfirst);
        num2 = Double.parseDouble(numsecond);
        ans = num1 + num2;
        res.setText(String.valueOf(ans));
    }
    //减法
    public void SUB(View view) {
        EditText first = (EditText)findViewById(R.id.first);
        EditText second = (EditText)findViewById(R.id.second);
        TextView  res = (TextView)findViewById(R.id.res);
        double num1 = 0;
        double num2 = 0;
        double ans = 0;
        String numfirst = first.getText().toString();
        String numsecond = second.getText().toString();
        num1 = Double.parseDouble(numfirst);
        num2 = Double.parseDouble(numsecond);
        ans = num1 - num2;
        res.setText(String.valueOf(ans));
    }
    //乘法
    public void MUL(View view) {
        EditText first = (EditText)findViewById(R.id.first);
        EditText second = (EditText)findViewById(R.id.second);
        TextView  res = (TextView)findViewById(R.id.res);
        double num1 = 0;
        double num2 = 0;
        double ans = 0;
        String numfirst = first.getText().toString();
        String numsecond = second.getText().toString();
        num1 = Double.parseDouble(numfirst);
        num2 = Double.parseDouble(numsecond);
        ans = num1 * num2;
        res.setText(String.valueOf(ans));
    }
    //除法
    public void DIV(View view) {
        EditText first = (EditText)findViewById(R.id.first);
        EditText second = (EditText)findViewById(R.id.second);
        TextView  res = (TextView)findViewById(R.id.res);
        double num1 = 0;
        double num2 = 0;
        double ans = 0;
        String numfirst = first.getText().toString();
        String numsecond = second.getText().toString();
        num1 = Double.parseDouble(numfirst);
        num2 = Double.parseDouble(numsecond);
        ans = num1 / num2;
        res.setText(String.valueOf(ans));
    }

4.看似代码很长,其实都是一样的,很简单就完成了,其中MainActivity.java中的代码我没有给出注释,就是几种类型的转换。欢迎大佬指点,初学者不懂的可以给我留言。下面给出仿真机运行效果。



Android 简单计算器的实现 计算器计算器App看似简单,实现起来却是不那么简单。对于android新手来说,计算器是一个很好的练手的小项目。对于android的一些基础知识和一些算法逻辑是一个很好的锻炼。功能基本计算器的加减乘除运算、历史记录、连续运算。 想法 计算器按键布局方式 添加button点击事件 字符串逻辑处理布局布局采用LinearLayout,采用layout_weight进行均等分是一个不错的方式。此计算 阅读详情

相关推荐

安卓开发之简易计算器教程

真·简易计算器,只支持两个整型数据进行简单的加减乘除四则运算,仅作为熟悉安卓开发的练手项目。 一共包括两个界面,一是主界面,如图1-1所示,是计算器的主体部分,二是选择运算符界面,如图1-2所示。 1-1主界面 1-2选择界面 主界面代码: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ap

qq_40174589的博客 1660

Android Studio入门教程(计算器)

一、建立开发环境 1、AS简介 Android Studio 是Google开发的一款面向Android开发者的IDE,支持Windows、Mac、Linux等操作系统,基于流行的开发语言java集成开发环境IntelliJ搭建而成的,类似Eclipse ADT。该IDE在2003年5月的Google I/O开发者大会首次露面,当时的测试版本还不够完善,直到2014年12月8日发布了稳定的版本。Android Studio 提供了集成的 Android 开发工具用于开发和调试。 1)基于 Gradle 的灵

独影阑珊 1万+

Android Studio制作一个简单的计算器APP

虽然现在我们日常生活中很少用到计算器,但在一些数学题或者物理题目上还是非常有帮助的,所以我就想在Android Studio上做一个计算器程序设计步骤: (1)在布局文件中声明编辑文件框EditText,按钮Button等组件。 (2)在MainActivity中获取组件实例。 (3)通过swtich函数,判断输入的内容,并进行相应操作,通过getText()获取文本内容,setText()显示。程序代码设计: 布局实现:在activi_main.xml中设置。使用线性布局(LinearLayout)与网格

weixin_57398221的博客 1万+

Java实现简单的计算器代码

【代码】Java实现简单的计算器代码。

qq_58416757的博客 1580

Android初识之简易计算器

之前自己的编程完全是在PC上进行的,而且主要是在算法和数据结构上。由于某些需要加之认识到Android的重要性,且大学走到现在基本上没什么课了,空闲时间很多,于是就开始学习Android。本系列博客都将围绕Android应用程序设计展开,由于本人是完全没有Android程序设计基础,所以内容都很基础,希望与大家交流学习并得到指点。      加上昨天,总共看了两天Android书,觉得似乎可以写

晓风残月xj 1516

[安卓初学者实验]简易的计算器

1)     实现一个简易的计算器。界面如图所示。 第一行四个存储键(mc,m+,m-,mr)可以不用实现,其余18个键需要实现。 布局文件<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.c

mai_pupil的博客 1026

Android简易计算器(四)—— 完整逻辑代码

  最近在学安卓的相关知识,第一个demo做了一个简易计算器,功能仿手机上自带的计算器,没有加括号,简单的四则运算,支持长表达式运算。此篇贴出本次简易计算器完整逻辑代码。 代码如下: package com.example.zwkkkk1.caculator1; import android.support.v7.app.AppCompatActivity; import android.o...

zwkkkk1的博客 5374

Android 小程序:自制简易计算器

My first Android app:计算器 ! 在经过了JavaSE基础学习后接触Android开发基础知识。 1周的学习后,我们的培训讲师布置了简易的计算器项目作业(在中期项目中会包含有计算器),这一任务激发了对数字敏感的我强烈兴趣,可是初学者终归是初学者,想一股脑儿得噼里啪啦写出代码实现功能简直是天方夜谭。于是百度了一些计算器逻辑与代码,我以为我看看别人的就能懂,可现实很残酷,我根本

Allen_0911的博客 2273

基于Android平台的简易计算器,基于Andriod的简易计算器

这学期有安卓这门课,这里做了一个简易的计算器,实现了两位数加减乘除的基本功能,比较简单适合用来入门学习。运行效果 预备知识实现这个计算器之前要先了解实现计算器需要的基本组件1.TextViewTextView是一个文本显示组件,提供了基本的显示文本功能,因为大多数UI系统组件都需要展示信息,所有它也是大多数UI系统组件的父类。(1)TextView的常用属性和方法属性名对应方法说明android:...

weixin_42114645的博客 1170

用Android Studio 编写简易计算器

用Android Studio 编写简易计算器界面设计功能的實現其他配置1.頂部標題2.修改測試 这是用Android Studio编写的 简易计算器 。功能主要是实现简单的加减操作,以及比较复杂的四则运算。 话不多说请看设计! 界面设计 在layout下面的calu.xml文件進行設計,推荐使用线性布局。沒有的先自行创建文件。 源码如下 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://

魏千泷 2397

Android案例:简易四则计算器,加减乘除用四个按钮控制。利用Activity点击事件监听

利用Activity点击事件监听的开发技术,实现了一个简单四则计算器,其功能模块包括加减乘除用四个按钮控制等。

java安卓编程计算器_菜鸟学Android编程——简单计算器《一》

菜鸟瞎搞,高手莫进本人菜鸟一枚,最近在学Android编程,网上看了一些视频教程,于是想着平时手机上的计算器应该很简单,自己何不尝试着做一个呢?于是就冒冒失失的开撸了。简单计算器嘛,功能当然很少,加减乘除就可以。第一步:设计布局文件界面如下图:由于刚开始学Android,对布局文件也不是很了解,边查边找,最后凑合着写好了布局文件。注意事项:此布局文件用到了GridLayout布局,是在Androi...

weixin_39552317的博客 750

瑞萨单片机,把CS文件转换为CC

1、打开CC的软件: 点击坐上角的"START" 点击"Create New Project"的"GO": 导入工程: 如下图设置后,点击"Create" 2、进入到CC的开发界面: 可以看到原启动库文件以asm文件的方式直接出现在工程中: 删除新生成的main.c,保留导入的r_main.c(以你自己的代码为准): 注意添加所有的头文件路径: 点击"...

weixin_37611121的博客 1228

【安卓】Android Studio简易计算器(实现加减乘除,整数小数运算,正数负数运算)

随着移动互联网的普及,手机应用程序已经成为人们生活中不可或缺的一部分。计算器是一类被广泛使用的应用程序之一,因此学习如何开发一款简易的计算器应用程序是学习Android Studio开发的一个很好的开始。Android Studio是一款Google开发的用于创建安卓应用的集成开发环境(IDE), 它可以帮助开发者快速设计、开发和测试应用程序。接下来我将为大家介绍如何使用Android Studio创建一个简易的计算器应用程序。

qq_73830179的博客 1万+

C51编程25-应用篇(单片机与电脑端实现wifi通讯)

单片机使用ESP-01S wifi模块与电脑端进行数据通讯。

qq_34343637的博客 1万+

无人机信号干扰系统设计方案

设计定向阻塞干扰器需要结合射频(RF)技术、功率放大技术和定向天线技术,核心目标是向特定方向发射高功率噪声信号,覆盖目标频段,阻断无人机的通信或导航信号。实际设计中需平衡功率、效率、散热和便携性,同时需考虑抗干扰技术的快速演进(如无人机加密通信和AI避障)。在合法框架下,此类设备可有效应对“黑飞”威胁,但技术滥用风险需严格管控。定向阻塞干扰器的硬件设计核心在于。

wanghao312的博客 3060

利用android studio制作简易的计算器

利用android studio制作简易的计算器Android Studio简介正文设计思路上代码colors.xml代码 Android Studio简介 Android Studio 是谷歌推出的一个Android集成开发工具,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提供了集成的 Android 开发工具用于开发和调试。 在IDEA的基础上...

OTS_luo的博客 6101

python爬虫入门教程(非常详细)

爬虫指的是一种自动化程序,能够模拟人类在互联网上的浏览行为,自动从互联网上抓取、预处理并保存所需要的信息。爬虫运行的过程一般是先制定规则(如指定要抓取的网址、要抓取的信息的类型等),紧接着获取该网址的HTML源代码,根据规则对源代码进行解析和抽取,最后进行处理和保存。爬虫在实际应用中广泛使用,如搜索引擎、大数据分析、交易数据采集等领域,都需要用到爬虫技术来实现信息的定向采集和处理。

工宗浩生财指南针 2万+

Android 实现的一个简易的计算器

最近刚刚开始学习安卓布局,尝试着实现了一个简单计算器。可以实现简单的加、减、乘、除,功能简单。随着将来会学的越来越深入,会计划把这个计算器一直优化下去。 MainActivity.java 文件 import android.os.Bundle; import android.view.View; import android.widget.Button; import ...

weixin_44314183的博客 1170

【数据分析】R语言分段结构方程模型手把手教程(Piecewise Structural Equation Model)

分段结构方程模型(Piecewise Structural Equation Model, SEM)是一种用于分析变量之间因果关系的统计方法。它通过将复杂的因果关系分解为多个简单的线性模型来评估变量之间的直接和间接效应。与传统的结构方程模型(SEM)不同,分段结构方程模型不需要假设数据的多变量正态分布,因此在处理非正态数据时更为灵活。

专注生信领域 2650

Allegro174版本如何关闭模块复用后铜皮自动从动态变成静态操作指导

在用Allegro进行PCB设计的时候,模块复用是使用的十分频繁的操作,当Allegro升级到了174 S034版本的时候,当使用模块复用的功能的时候,模块内的铜皮会自动动静转换,大部分情况是不需要的。版本如何关闭模块复用后铜皮自动从动态变成静态操作指导。如何关闭这个功能,具体操作如下。

weixin_54787054的博客 1261

Android Studio制作简单计算器

代码地址 https://github.com/xjhqre/android_calculator 制作步骤 1. 创建按钮图片 1.1. 退格图形 <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="200dp" android:height="200dp" android:viewportWidth="1024" android:viewportHeigh

xjhqre的博客 1万+

Python爬虫实战:深度解析携程/飞猪酒店评论API与大数据采集

本文详细介绍了如何通过Python爬虫技术获取携程和飞猪平台的酒店评论数据。我们涵盖了从API分析、反爬虫对策到数据存储和处理的完整流程。API逆向分析:通过浏览器开发者工具发现和分析API接口反爬虫对策:使用请求头随机化、IP代理、浏览器自动化等技术异步处理:使用asyncio提高爬取效率数据质量:实现数据清洗和质量检查机制系统架构:构建可扩展的分布式爬虫系统未来改进方向:机器学习识别验证码分布式爬虫架构实时数据流处理更智能的反反爬虫策略。

2201_76125261的博客 602

android简易计算器

android简易计算器 说明:完成简易版计算器,能够实现基本的加、减、乘、除运算 图示: 布局文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#3E3E3E

shgzzd的博客 3738

编写python脚本调用ordinals以及BRC20的接口

1、钱包地址生成walletreceive,对应ord命令:ord wallet receive。6、测试手动出块generate,这个只在regtest链节点用得上。所有接口都是post请求,采用postman进行测试。4、测试bitcoin转币sendtoaddress。7、测试其他的wallet方法wallet。2、钱包币种铭刻inscription,对应bitcoin-cli命令。对应bitcoin-cli命令。对应bitcoin-cli命令。fee.json文本模板。还可以加很多根据需要加减。

云深海阔专栏 1048

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

利用android studio LinearLayout线性布局嵌套设计制作简易的计算器详细版【精选收藏】

利用android studio GridLayout网格布局设计制作简易的计算器详细版【精选收藏】Android Studio简介设计思路上代码 Android Studio简介 Android Studio 是谷歌推出的一个Android集成开发工具,基于IntelliJ IDEA. 类似 Eclipse ADT,Android Studio 提供了集成的 Android 开发工具用于开发和调...

OTS_luo的博客 4506

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

上一篇: 初学android studio——如何通过编辑框(EditText)向另一个activity的文本框(TextView)发送信息
下一篇: Java创建数组对象及初始化
Timber666
博客等级 码龄9年 28粉丝 10原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值