重走Java路-数据结构与算法-数组-手写ArrayList

C++官方自带可持久化平衡树rope的3000行源码 C++官方rope3000行源码 // SGI's rope class -*- C++ -*- // Copyright (C) 2001-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms o 阅读详情

重走Java路-数据结构与算法-数组-手写简单的ArrayList

上一回分享回顾完了Java的数组,因为数据结构与算法的知识相对独立,所以我决定接着数组回顾一下Java的数据结构。而ArrayList作为Java中最简单又最常用的集合类,正好适合拿来第一个开刀,不知道大家有没有去读过ArrayList的的源码,或者去简单实现一个ArrayList呢?今天我们就一起看看ArrayList的源码,同时手写一个简单的ArrayList。

learn ArrayList

ArrayList源码分析

  1. 打开ArrayList的源码我们能看到ArrayList实现了List接口,扩展至AbstractList,其本质是一个可变长度的数组。
  2. Java8中ArrayList包含注释一起一共1468行代码,算是一个比较复杂的类,所以这当中一定有值得我们研究的东西。
  3. 根据面向对象的基本原则与特性,对象都有自己的属性(成员变量)和行为(方法),所以我们先来看一看ArrayList的属性即成员变量。
private static final long serialVersionUID = 8683452581122892189
    
/**
 * Default initial capacity.
 * 默认的初始容量
 */
private static final int DEFAULT_CAPACITY = 1
    
/**
 * Shared empty array instance used for empty instances.
 * 用于空实例的共享空数组实例。
 */
private static final Object[] EMPTY_ELEMENTDATA = {}

/**
 * Shared empty array instance used for default sized empty instances. We
 * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
 * first element is added.
 * 用于默认大小的空实例的共享空数组实例。我们将其与EMPTY_ELEMENTDATA区分开来,
 * 以便知道何时扩容添加第一个元素。
 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 * will be expanded to DEFAULT_CAPACITY when the first element is added.
 * 存储ArrayList元素的数组。
 * ArrayList的容量是这个数组的长度。
 * 当添加第一个元素时,将扩展DEFAULT_CAPACITY个长度
 */
transient Object[] elementData; // non-private to simplify nested class acce
    
/**
 * The size of the ArrayList (the number of elements it contains).
 * 这是值是数据组中元素的格式
 * @serial
 */
private int size;
  1. 通过上述源代码,我们很容易发现ArrayList就是一个可变长度的数组,我们对ArrayList的操作实际上就是对elementData数组的操作,ArrayList中的元素实际上是存储在elementData数组当中的,size是用来记录数组中元素个数的。既然知道了ArrayList是一个可变长度的数组,接着就到了我们研究的重点看看ArrayList是如何实现自动扩容的?
  2. 继续依据面向对象的特性,对象都有自己的属性(成员变量)和行为(方法),我们来看看ArrayList的行为,既然研究的重点是扩容我们就先看看add()方法。
/**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return <tt>true</tt> (as specified by {@link Collection#add})
 * 往列表尾部添加元素
 */
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
  1. 看到add(E e)方法的doc注释,视乎没太大的意义,只是告诉我们这个方法时往集合尾部添加元素的 //add 添加
  2. 接着我们看ensureCapacityInternal()方法。//ensure Capacity Internal 确保内部容量
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
  1. what这个方法居然没有注释,这ArrayList源码作者的编程习惯也太不规范了吧,看来这水平跟我也差不多。哈哈其实这样想你就错了,大神的代码就是大神的代码。人家这个变量名称minCapacity(最小容量)实在是用的太好了.我们结合之前add()方法的代码,在调用这个方法时传入的是size+1,也就是说我们的数组容量最小得有size+1,这的变量名实在是太妙了。
  2. 接着我们看calculateCapacity()方法。 //calculate Capacity 计算容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}
  1. 什么玩意啊!居然又没注释,这什么鬼源码,这编码习惯简直是稀烂还不如我了(ps:其实依据编码规约,对于private方法是不需要注释的,因为private方法仅内部使用,作者肯定知道他是干嘛的,而对于public等对外提供的方法则需要严格书写doc注释,要不然其他人怎么使用你的方法)。继续分析代码calculateCapacity方法需要两个参数elementData(存储元素的数组)和minCapacity(最小容量),代码第一行逻辑为if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA),这个时候我们需要去看一看ArrayList的构造函数。
/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
  1. 通过上述代码我们看到,ArrayList的无参构造就是将DEFAULTCAPACITY_EMPTY_ELEMENTDATA复制给elementData。所以再回到calculateCapacity方法的代码,此时elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA逻辑成立且elementData={}、minCapacity=1。接着我们继续看代码return Math.max(DEFAULT_CAPACITY, minCapacity),因为DEFAULT_CAPACITY=10大于minCapacity=1,所以此时Math.max返回DEFAULT_CAPACITY。
  2. 回到ensureCapacityInternal方法我们一起看ensureExplicitCapacity()方法。//ensure Explicit Capacity 确保正确的容量。
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
  1. what`s wrong怎么又没有注释呢,嗨!垃圾这编码水平,还好意思写jdk(ps:再次强调private方法是可以不写注释的,而且这是符合编码规范的)。算了还是继续看代码吧,此时参数minCapacity=DEFAULT_CAPACITY=10,第一行代码modCount++,modCount编码位于AbstractList中源码如下。
/**
 * The number of times this list has been <i>structurally modified</i>.
 * Structural modifications are those that change the size of the
 * list, or otherwise perturb it in such a fashion that iterations in
 * progress may yield incorrect results.
 *
 * <p>This field is used by the iterator and list iterator implementation
 * returned by the {@code iterator} and {@code listIterator} methods.
 * If the value of this field changes unexpectedly, the iterator (or list
 * iterator) will throw a {@code ConcurrentModificationException} in
 * response to the {@code next}, {@code remove}, {@code previous},
 * {@code set} or {@code add} operations.  This provides
 * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
 * the face of concurrent modification during iteration.
 *
 * <p><b>Use of this field by subclasses is optional.</b> If a subclass
 * wishes to provide fail-fast iterators (and list iterators), then it
 * merely has to increment this field in its {@code add(int, E)} and
 * {@code remove(int)} methods (and any other methods that it overrides
 * that result in structural modifications to the list).  A single call to
 * {@code add(int, E)} or {@code remove(int)} must add no more than
 * one to this field, or the iterators (and list iterators) will throw
 * bogus {@code ConcurrentModificationExceptions}.  If an implementation
 * does not wish to provide fail-fast iterators, this field may be
 * ignored.
 */
protected transient int modCount = 0;
  1. 这个注释多我喜欢,可是这吧啦吧啦说一堆到底是个啥呢,英语水平有限我的理解就是modCount是用于记录ArrayList的扩容次数
  2. 好了再去看ensureExplicitCapacity方法吧,modCount++之后就进入了代码块
// overflow-conscious code
if (minCapacity - elementData.length > 0)
    grow(minCapacity);
  1. 哈哈这个方法有意思,还有方法内注释,这个是真跟我有点像(其实这样是不太规范的,规整的代码,仅仅只需要靠变量名以及方法名,就能让人通俗易懂的读懂代码,过多的方法内注释是不规范不可取的,当然这里只有一行)。因为此时minCapacity=10、elementData.length=0,所有minCapacity - elementData.length > 0成立,进入grow(minCapacity)方法(ps:这个方法名也起得好啊,扩容,所以其实大神上面那个单行注释压根不用要)。
  2. 我们来一起看看grow()方法,唉!不容易啊,终于进入正题了。//grow 扩展
/**
 * Increases the capacity to ensure that it can hold at least the
 * number of elements specified by the minimum capacity argument.
 *
 * @param minCapacity the desired minimum capacity
 */
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}
  1. 咦!不错、不错。这个私有的方法也有注释,这个注释的意思呢,大概就是:扩展容量以确保至少能容纳minCapacity个元素。接下来我们一起来分析代码:

    1. int oldCapacity = elementData.length 此时因为elementData为一个空数组,所以oldCapacity=0。
    2. int newCapacity = oldCapacity + (oldCapacity >> 1) 因为oldCapacity=0,所以此时newCapacity=0。
    3. if (newCapacity - minCapacity < 0) newCapacity = minCapacity 因为此时newCapacity=0、minCapacity=10,所以最终得到newCapacity=10
    4. if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity) 因为newCapacity <MAX_ARRAY_SIZE,所以直接进入elementData = Arrays.copyOf(elementData, newCapacity)。这里呢就不对Arrays.copyOf(),因为他最终会调用System类的arraycopy()方法,该方法为一个native方法,说明这个方法是用其他语言写的本地方法,我们如果想查看源码就必须通过openjdk8查看相关源码了。
    • 补充说明

    ​ int newCapacity = oldCapacity + (oldCapacity >> 1),这里涉及到一个位移运算,算是比较经典吧,所以补充说明一下。第一次扩容时因为oldCapacity=0,所以oldCapacity向右移动一位还是0。如果是第二次扩容oldCapacity为10,则oldCapacity >> 1=5,扩容后newCapacity=15。所以每次扩容的维度,其实是原来容量的1/2。

    ​ 计算过程如下二进制10(01010,前面高位省略),向右移动一位得到00101二进制的5,如果大家对二进制还是不太熟悉,可以阅读我之前的博文重走Java路-基本数据类型上面有更详细的对二进制的介绍。

  2. 上面已经大致分析完了ArrayList的扩容机制,所有现在就有了我们面试中经常见到的问题:为什么ArrayList查询快添加插入元素却慢呢?分析完源代码之后我相信我们大家都能很快的回答出这个问题,因为ArrayList是基于数组进行元素存储的,从数组中获取元素对CPU而言只是一个取指令、存指令的操作,他的时间复杂度为O(1),而对于插入操作会引起数组的复制操作所以相对较慢。

简单实现MyArrayList

MyArrayList只是一个非常简单的ArrayList,也只实现了size(),add()等几个常用的方法,旨在弄清楚ArrayList的数据结构,扩容机制的知识,源码地址。

package com.itxiaoyuaiit.learn.list;

/**
 * @ClassName MyArrayList
 * @Description 这是一个自定义的简单的ArrayList,仅实现了add、get、indexOf等方法。其目的是为了弄懂ArrayList的自动扩容获取元素,添加元素等实现机制
 * @Author wuyuqing
 * @Date 2020/7/9 21:18
 * @Version 1.0
 */
public class MyArrayList<E> implements MyList {
    /**
     * 记录集合长度(集合中元素的个数)
     */
    private int size;

    /**
     * object类型的数组用于存储集合中的元素,初始容量为16
     */
    private Object[] elements = new Object[16];


    @Override
    public int size() {
        return this.size;
    }

    @Override
    public boolean add(Object o) {
        // 判断集合长度是否等于数组长度
        if (elements.length > size) {
            elements[size] = o;
        } else {
            //进行数组扩容,扩容为原来的两倍
            Object[] temporary = new Object[elements.length * 2];
            //将原来数组中的元素拷贝到临时数组中
            for (int i = 0; i < elements.length; i++) {
                temporary[i] = elements[i];
            }
            //将新的元素添加到临时数组,并把临时数组赋值给elements
            temporary[size] = o;
            elements = temporary;
        }
        size += 1;
        return true;
    }

    @Override
    public boolean remove(int index) {
        boolean result = true;
        // 首先判断index的合法性
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException();
        }else if(index == size -1){//如果移除的是最后一位,则直接将该索引位置元素置null,size减1
            elements[index] = null;
            size -= 1;
        }else {
            // 移除指定索引下的元素,实际上是把index后面的元素前移一位
            for (int i = index; i < elements.length - 1; i++) {
                elements[i] = elements[i + 1];
            }
            size -= 1;
        }
        return result;
    }

    @Override
    public Object get(int index) {
        //首先判断索引的合法性,不合法返回null
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException();
        }else {
            return elements[index];
        }
    }

    @Override
    public Object set(int index, Object element) {
        //首先判断索引的合法性,不合法返回null
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException();
        }else {
            Object oldElement = elements[index];
            elements[index] = element;
            return oldElement;
        }
    }

    @Override
    public int indexOf(Object o) {
        for (int i = 0; i < size; i++) {
            if(elements[i].equals(o)){
                return i;
            }
        }
        return -1;
    }
}

Amazon面试限流器设计:从白板题到生产级Rate Limiter 限流器是分布式系统保障稳定性的核心中间件,其本质是资源配额管理与实时决策的结合体。原理上需兼顾时序精度、数据一致性与低延迟响应,技术价值体现在毫秒级拒绝超载请求、防止雪崩并支撑高并发业务。典型应用场景包括支付网关、API网关和微服务熔断,尤其在大促流量洪峰下成为SLA守门员。本文以Amazon真实面试题为切入点,深入解析滑动窗口实现、本地内存优化、MurmurHash3防冲突及ThreadLocal安全清理等关键工程细节,覆盖边界处理、可读性优先与真实用例驱动等核心实践原则。 阅读详情

相关推荐

torch.nn.LSTM介绍

是 PyTorch 提供的一个高级封装,用于构建长短时记忆网络(LSTM)。相比手动实现,更高效且支持批量处理、双向 LSTM、多层 LSTM 等功能,适合大多数实际应用。

qq_27390023的博客 1010

// Types used in iterator implementation -*- C++ -*-

//**/*/#endif/***///@{/***///@{//@}/***//***/#else#endif。

HJR_hjr_1234567的博客 777

知识图谱与人工智能本体论:构建机器认知的语义基石

本文探讨了知识图谱与人工智能本体论如何作为机器认知的语义基石,让AI从‘知道数据’迈向‘理解知识’。文章详细拆解了本体论的核心构件与构建方法,并阐述了从本体到知识图谱的实践路径,包括知识获取、融合、存储及推理应用,最终分析了其在智能搜索与专家系统等场景中带来的根本性重塑。

nginx7reverse的博客 915

STL algorithm源代码:stl_algo.h

&lt;span style="font-size:18px;"&gt;// Algorithm implementation -*- C++ -*- // Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, // 2010, 2011 // Free Software Foundation, Inc. ...

weixin_34014277的博客 401

ADS新手必看:ICCAP数据导入与导出CSV的完整流程(附常见问题解决)

本文为ADS新手详细讲解了如何将ICCAP测试数据导入ADS进行仿真分析,并导出为通用CSV格式的完整流程。内容涵盖文件格式解析、导入设置、数据验证、处理技巧及常见问题排查,重点解决了数据文件导入过程中的兼容性与单位映射等核心难点,帮助射频工程师高效连接测量与仿真环节。

peace的博客 564

用LightRAG+Ollama搭建本地知识库:从文档上传到智能问答的完整流程

本文详细介绍了如何利用LightRAG与Ollama构建企业级本地知识库,涵盖从文档预处理到智能问答的完整流程。通过实战案例展示,该方案能高效处理海量文档,实现语义搜索与知识图谱关联分析,显著提升信息检索效率。特别适合金融、医疗等领域的技术团队快速搭建智能知识管理系统。

weixin_42535461的博客 222

如何写 可移植C++代码(C++ Portability Guide--From Mozilla Develop Site)

注:这个仅是我的学习笔记,完整的英文文章在这个(http://www.mozilla.org/hacking/portable-cpp.html)。致谢:感谢这个文档的作者,为我学习提供了很好的资料^_^。正文/* Work In Progress  */What follows is a set of rules, guidelines, and tips that we h

grrhard的专栏 1037

嵌入式硬件实战:RC、LC与RL滤波电路的设计与选型指南

本文深入探讨了嵌入式系统中RC、LC与RL滤波电路的设计与选型策略。通过生活化比喻和实战案例,详细解析了三种滤波电路的工作原理、应用场景及工程注意事项,帮助工程师根据电流大小、频率特征和成本预算选择最优方案,提升嵌入式硬件设计的稳定性和抗干扰能力。

kiwi8的博客 291

[重走长征路]集合

集合 1、内存层面需要针对多个数据进行存储,此时可以考虑的容器有 :数组、集合类 2、数组存储多个数据方面的特点 数组一旦初始化,其长度就是固定的 数组中多个元素是依次紧密排列的 有序的可重复的 (优点)数组一旦初始化完成,其元素类型就是确定的,不是此类型的元素,就不能添加到数组中(集合本身不会检查元素类型,检查元素是否一致是泛型的工作) 元素中类型可以是基本数据类型 也可以是引用数据类型 (相较于集合 集合只能存放引用数据类型,基本数据类型的数据会进行自动装箱存库)

weixin_45317494的博客 465

【初阶】手把手教你轻松上手Denodo | 连接数据库并创建基本视图 (二)

在本教程的第二部分,我们将涵盖:连接到数据库,与创建基本视图。

Denodo的博客 1125

【DaVinci Developer工具实战】03 -导入xml文件

本文档描述了 DaVinci Developer 导入数据的的具体功能 ,它适用于导入AUTOSAR SWC 模板【AUTOSAR XML 文件】 文件。

1994

C++模板遇到iterator时候遇到的问题和解决方法

今天开发的时候,发现用模板的时候,再加上iterator,会报错,如下: std::map&lt;T, S&gt;::iterator find_iter = mp.find(key); 编译会报错: error: expected `;' before "find_iter"   查了这篇文章: https://stackoverflow.com/questions/11275444/c-tem...

weixin_34281537的博客 457

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

使用map遇到的两个问题及解决办法

  现定义一个map数据结构如下:map<tuple4, CTcpManage> m_mapTcp;   键值类型为结构体tuple4,存放TCP四元组,定义如下:      struct tuple4   {     u_int32_t sourceIP;     u_int32_t destIP;     unsigned short sport;     ...

weixin_30817749的博客 1234

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

C++ Tips

<bits/stdc++.h> 这个头文件是c++的一个算是比较特殊的头文件,不是所有oj都支持,在pc上一般好像可以用。这个头文件包含很多头文件,当你忘记某个函数在哪个头文件的时候写上这一个头文件就大概率可以运行了。 这个是源码,就是不知道C++的运行机制一下include这么多头文件会不会占内存。。。 // C++ includes used for precompili...

qq_31267769的博客 610

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

一个很强大的头文件

在牛客网看代码,有个头文件叫做#include&lt;bits/stdc++.h&gt; 今天必须一探究竟为什么这个头文件能这么强大。// C++ includes used for precompiling -*- C++ -*- // Copyright (C) 2003-2015 Free Software Foundation, Inc. // // This file is part ...

weixin_35650592的博客 315

ArrayList源码解析

前言 集合中的collection接口下的常用类的关系 ArrayList中的成员变量 /** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {};/** * Shared empty array instance used for default sized empty instances. We * di...

a219219219219的博客 315

ArrayList源码分析

ArrayList是日常开发中使用非常频繁的容器,今天看一下它的源码。ArrayList的源码其实很简单,它就是一个动态数组,我们先从new开始看起: /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } 上述是ArrayList

hyWang94 276

Java小白学点东西(10)

1.ArrayList 大家可以借助官方API查询可以看到: Collection下面有一个子接口叫List List接口下面有一个实现类叫ArrayList ArrayList底层是数组 ArrayList也是容器,可以放数据 源码分析 /** * Default initial capacity. 默认的变量,变量值是10 默认的初始化的容量 */ private static final int DEFAULT_CAPACITY = 10;...

来一杯Java咖啡 187

(一)ArrayList无参构造的初始容器大小

文章目录8版本的jdk初始容量:使用无参构造的初始大小到底是多少? 8版本的jdk初始容量:使用无参构造的初始大小到底是多少? 1.无参初始化并不是在无参构造方法的位置执行的,而是在第一次执行add方法的时候执行了容器大小的设置 /** * Shared empty array instance used for default sized empty instances. We * dist...

dancer 944

关于ArrayList初始容量的问题

关于ArrayList初始容量的问题 先上结论: ​ 1、使用无参构造器创建ArrayList对象时,默认容量是0 ​ 2、当往ArrayList中添加了一个元素后,默认容量自动扩充成10 ​ 3、当容量到达上限时会使用位运算自动扩容,新的容量为先前容量的1.5倍,这点和之前总结的无误 ​ 4、使用带参构造器创建ArrayList对象容量是所传参数 求证过程: 昨天刚在csdn发布了自己整理之前写的关于Collection方面的笔记,结果今天老师就在课堂上提问ArrayList的初始化容量是多少,自信回答,

AlwaysZS的博客 1208

JDK源码分析——Iterator接口、Collection接口、ArrayList类

##集合框架 从类图结构可以了解 java.util包下的2个大类: 1、Collecton:可以理解为主要存放的是单个对象 2、Map:可以理解为主要存储key-value类型的对象 ##Iterator接口分析 package java.lang; import java.util.Iterator; import java.util.Objects; import java.util.S...

小马不奔腾的博客 315

Java核心复习 —— ArrayList源码阅读

一、ArrayList 介绍 ArrayList是List接口可变数组的实现。 特点 非线程安全 查找和修改效率高 二、ArrayList 使用方法 remove元素 @Test public void testRemove(){ List<String> strings = new ArrayList<>(); strings.add("a"...

a5678110的博客 140

java ArrayList 底层源码深度解析

package BaseClassJavaSource; import sun.misc.SharedSecrets; import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; /** * Resizable-array implementation of the <tt>List

pengshuhui123的博客 361

集合——ArrayList实现原理分析

public class ArrayList&lt;E&gt; extends AbstractList&lt;E&gt; implements List&lt;E&gt;, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 868345...

专注分享原创技术干货。大厂资深架构师,多年技术架构与技术管理经验,多年面试官经验。一对一技术指导培训,带你从小白到入门到架构设计到技术管理。关注我,免费领取学习资料。一对一免费面试指导,快速拿offer。 380
上一篇: 重走Java路-Java常用数据结构-数组
下一篇: 怎样才是技术文档的正确书写方式
CrazyJavaWu
博客等级 码龄10年 16粉丝 20原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值