Python语言十分钟快速入门

python快速入门,看这一篇就够了! 阅读详情

假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手册(CheatSheet)之间,因此只会包含一些基本概念。很显然,如果你希望真正学好一门语言,你还是需要亲自动手实践的。在此,我会假定你已经有了一定的编程基础,因此我会跳过大部分非Python语言的相关内容。本文将高亮显示重要的关键字,以便你可以很容易看到它们。另外需要注意的是,由于本教程篇幅有限,有很多内容我会直接使用代码来说明加以少许注释。


Python的语言特性


Python是一门具有强类型(即变量类型是强制要求的)、动态性、隐式类型(不需要做变量声明)、大小写敏感(var和VAR代表了不同的变量)以及面向对象(一切皆为对象)等特点的编程语言。


获取帮助


你可以很容易的通过Python解释器获取帮助。如果你想知道一个对象(object)是如何工作的,那么你所需要做的就是调用help(<object>)!另外还有一些有用的方法,dir()会显示该对象的所有方法,还有<object>.__doc__会显示其文档:

>>> help(5)Help on int object:(etc etc)>>> dir(5)['__abs__', '__add__', ...]>>> abs.__doc__
'abs(number) -> number

Return the absolute value of the argument.'


语法


Python中没有强制的语句终止字符,且代码块是通过缩进来指示的。缩进表示一个代码块的开始,逆缩进则表示一个代码块的结束。声明以冒号(:)字符结束,并且开启一个缩进级别。单行注释以井号字符(#)开头,多行注释则以多行字符串的形式出现。赋值(事实上是将对象绑定到名字)通过等号(“=”)实现,双等号(“==”)用于相等判断,”+=”和”-=”用于增加/减少运算(由符号右边的值确定增加/减少的值)。这适用于许多数据类型,包括字符串。你也可以在一行上使用多个变量。例如:

>>> myvar = 3>>> myvar += 2>>> myvar5>>> myvar -= 1>>> myvar4"""This is a multiline comment.
The following lines concatenate the two strings.""">>> mystring = "Hello">>> mystring += " world.">>> print mystring
Hello world.# This swaps the variables in one line(!).# It doesn't violate strong typing because values aren't# actually being assigned, but new objects are bound to# the old names.>>> myvar, mystring = mystring, myvar


数据类型


Python具有列表(list)、元组(tuple)和字典(dictionaries)三种基本的数据结构,而集合(sets)则包含在集合库中(但从Python2.5版本开始正式成为Python内建类型)。列表的特点跟一维数组类似(当然你也可以创建类似多维数组的“列表的列表”),字典则是具有关联关系的数组(通常也叫做哈希表),而元组则是不可变的一维数组(Python中“数组”可以包含任何类型的元素,这样你就可以使用混合元素,例如整数、字符串或是嵌套包含列表、字典或元组)。数组中第一个元素索引值(下标)为0,使用负数索引值能够从后向前访问数组元素,-1表示最后一个元素。数组元素还能指向函数。来看下面的用法:

>>> sample = [1, ["another", "list"], ("a", "tuple")]>>> mylist = ["List item 1", 2, 3.14]>>> mylist[0] = "List item 1 again" # We're changing the item.>>> mylist[-1] = 3.21 # Here, we refer to the last item.>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}>>> mydict["pi"] = 3.15 # This is how you change dictionary values.>>> mytuple = (1, 2, 3)>>> myfunction = len>>> print myfunction(mylist)3


你可以使用:运算符访问数组中的某一段,如果:左边为空则表示从第一个元素开始,同理:右边为空则表示到最后一个元素结束。负数索引则表示从后向前数的位置(-1是最后一个项目),例如:

>>> mylist = ["List item 1", 2, 3.14]>>> print mylist[:]['List item 1', 2, 3.1400000000000001]>>> print mylist[0:2]['List item 1', 2]>>> print mylist[-3:-1]['List item 1', 2]>>> print mylist[1:][2, 3.14]# Adding a third parameter, "step" will have Python step in# N item increments, rather than 1.# E.g., this will return the first item, then go to the third and# return that (so, items 0 and 2 in 0-indexing).>>> print mylist[::2]['List item 1', 3.14]


字符串


Python中的字符串使用单引号(‘)或是双引号(“)来进行标示,并且你还能够在通过某一种标示的字符串中使用另外一种标示符(例如 “He said ‘hello’.”)。而多行字符串可以通过三个连续的单引号(”’)或是双引号(“””)来进行标示。Python可以通过u”This is a unicode string”这样的语法使用Unicode字符串。如果想通过变量来填充字符串,那么可以使用取模运算符(%)和一个元组。使用方式是在目标字符串中从左至右使用%s来指代变量的位置,或者使用字典来代替,示例如下:

>>>print "Name: %s
Number: %s
String: %s" % (myclass.name, 3, 3 * "-")Name: Poromenos
Number: 3String: ---strString = """This is
a multiline
string."""# WARNING: Watch out for the trailing s in "%(key)s".>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}This is a test.


流程控制


Python中可以使用if、for和while来实现流程控制。Python中并没有select,取而代之使用if来实现。使用for来枚举列表中的元素。如果希望生成一个由数字组成的列表,则可以使用range(<number>)函数。以下是这些声明的语法示例:

rangelist = range(10)>>> print rangelist[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continueelse:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothingif rangelist[1] == 2:
    print "The second item (lists are 0-based) is 2"elif rangelist[1] == 3:
    print "The second item (lists are 0-based) is 3"else:
    print "Dunno"while rangelist[1] == 1:
    pass


函数


函数通过“def”关键字进行声明。可选参数以集合的方式出现在函数声明中并紧跟着必选参数,可选参数可以在函数声明中被赋予一个默认值。已命名的参数需要赋值。函数可以返回一个元组(使用元组拆包可以有效返回多个值)。Lambda函数是由一个单独的语句组成的特殊函数,参数通过引用进行传递,但对于不可变类型(例如元组,整数,字符串等)则不能够被改变。这是因为只传递了该变量的内存地址,并且只有丢弃了旧的对象后,变量才能绑定一个对象,所以不可变类型是被替换而不是改变(译者注:虽然Python传递的参数形式本质上是引用传递,但是会产生值传递的效果)。例如:

# 作用等同于 def funcvar(x): return x + 1funcvar = lambda x: x + 1>>> print funcvar(1)2# an_int 和 a_string 是可选参数,它们有默认值# 如果调用 passing_example 时只指定一个参数,那么 an_int 缺省为 2 ,a_string 缺省为 A default string。如果调用 passing_example 时指定了前面两个参数,a_string 仍缺省为 A default string。# a_list 是必备参数,因为它没有指定缺省值。def passing_example(a_list, an_int=2, a_string="A default string"):
    a_list.append("A new item")
    an_int = 4
    return a_list, an_int, a_string>>> my_list = [1, 2, 3]>>> my_int = 10>>> print passing_example(my_list, my_int)([1, 2, 3, 'A new item'], 4, "A default string")>>> my_list[1, 2, 3, 'A new item']>>> my_int10


类


Python支持有限的多继承形式。私有变量和方法可以通过添加至少两个前导下划线和最多尾随一个下划线的形式进行声明(如“__spam”,这只是惯例,而不是Python的强制要求)。当然,我们也可以给类的实例取任意名称。例如:

class MyClass(object):
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable    # This is the class instantiation>>> classinstance = MyClass()>>> classinstance.myfunction(1, 2)3# This variable is shared by all classes.>>> classinstance2 = MyClass()>>> classinstance.common10>>> classinstance2.common10# Note how we use the class name# instead of the instance.>>> MyClass.common = 30>>> classinstance.common30>>> classinstance2.common30# This will not update the variable on the class,# instead it will bind a new object to the old# variable name.>>> classinstance.common = 10>>> classinstance.common10>>> classinstance2.common30>>> MyClass.common = 50# This has not changed, because "common" is# now an instance variable.>>> classinstance.common10>>> classinstance2.common50# This class inherits from MyClass. The example# class above inherits from "object", which makes# it what's called a "new-style class".# Multiple inheritance is declared as:# class OtherClass(MyClass1, MyClass2, MyClassN)class OtherClass(MyClass):
    # The "self" argument is passed automatically
    # and refers to the class instance, so you can set
    # instance variables as above, but from inside the class.
    def __init__(self, arg1):
        self.myvariable = 3
        print arg1>>> classinstance = OtherClass("hello")hello>>> classinstance.myfunction(1, 2)3# This class doesn't have a .test member, but# we can add one to the instance anyway. Note# that this will only be a member of classinstance.>>> classinstance.test = 10>>> classinstance.test10


异常


Python中的异常由 try-except [exceptionname] 块处理,例如:

def some_function():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print "Oops, invalid."
    else:
        # Exception didn't occur, we're good.
        pass
    finally:
        # This is executed after the code block is run
        # and all exceptions have been handled, even
        # if a new exception is raised while handling.
        print "We're done with that.">>> some_function()Oops, invalid.We're done with that.


导入


外部库可以使用 import [libname] 关键字来导入。同时,你还可以用 from [libname] import [funcname] 来导入所需要的函数。例如:

import randomfrom time import clock

randomint = random.randint(1, 100)>>> print randomint64


文件I / O


Python针对文件的处理有很多内建的函数库可以调用。例如,这里演示了如何序列化文件(使用pickle库将数据结构转换为字符串):

import pickle
mylist = ["This", "is", 4, 13327]# Open the file C:binary.dat for writing. The letter r before the# filename string is used to prevent backslash escaping.myfile = open(r"C:binary.dat", "w")pickle.dump(mylist, myfile)myfile.close()myfile = open(r"C:text.txt", "w")myfile.write("This is a sample string")myfile.close()myfile = open(r"C:text.txt")>>> print myfile.read()'This is a sample string'myfile.close()# Open the file for reading.myfile = open(r"C:binary.dat")loadedlist = pickle.load(myfile)myfile.close()>>> print loadedlist['This', 'is', 4, 13327]


其它杂项


  • 数值判断可以链接使用,例如 1<a<3 能够判断变量 a 是否在1和3之间。

  • 可以使用 del 删除变量或删除数组中的元素。

  • 列表推导式(List Comprehension)提供了一个创建和操作列表的有力工具。列表推导式由一个表达式以及紧跟着这个表达式的for语句构成,for语句还可以跟0个或多个if或for语句,来看下面的例子:

>>> lst1 = [1, 2, 3]>>> lst2 = [3, 4, 5]>>> print [x * y for x in lst1 for y in lst2][3, 4, 5, 6, 8, 10, 9, 12, 15]>>> print [x for x in lst1 if 4 > x > 1][2, 3]# Check if an item has a specific property.# "any" returns true if any item in the list is true.>>> any([i % 3 for i in [3, 3, 4, 4, 3]])True# This is because 4 % 3 = 1, and 1 is true, so any()# returns True.# Check how many items have this property.>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)2>>> del lst1[0]>>> print lst1[2, 3]>>> del lst1
  • 全局变量在函数之外声明,并且可以不需要任何特殊的声明即能读取,但如果你想要修改全局变量的值,就必须在函数开始之处用global关键字进行声明,否则Python会将此变量按照新的局部变量处理(请注意,如果不注意很容易被坑)。例如:

    number = 5def myfunc():
        # This will print 5.
        print numberdef anotherfunc():
        # This raises an exception because the variable has not
        # been bound before printing. Python knows that it an
        # object will be bound to it later and creates a new, local
        # object instead of accessing the global one.
        print number
        number = 3def yetanotherfunc():
        global number    # This will correctly change the global.
        number = 3


小结


本教程并未涵盖Python语言的全部内容(甚至连一小部分都称不上)。Python有非常多的库以及很多的功能特点需要学习,所以要想学好Python你必须在此教程之外通过其它方式,例如阅读Dive into Python。我希望这个教程能给你一个很好的入门指导。如果你觉得本文还有什么地方值得改进或添加,或是你希望能够了解Python的哪方面内容,请留言。



640?wx_fmt=png


版权声明:“并发编程网”所推送文章,除非确实无法确认,我们都会注明作者和来源。部分文章推送时未能与原作者取得联系。若涉及版权问题,烦请原作者联系我们,我们会在24小时内删除处理,谢谢!^_^15701189222

640?wx_fmt=jpeg
微信号:并发编程网
长按、关注
640?wx_fmt=png640?wx_fmt=jpeg

Python入门第1课——打印(只读课堂) 阅读详情

相关推荐

Python入门知识总结——超详细版

Python 是一种解释型面向对象的语言Python的语法和动态类型,以及解释性语言的本质,使它成为多数平台上写脚本和快速开发应用的编程语言单引号定义法:双引号定义法:三引号定义法:其中,单引号定义法,可以内含双引号;双引号定义法,可以内含单引号;并且可以使用**转义字符(\)**来将引号解除效用,变成普通字符串。

xiaolinyui的博客 4778

Python入门教程(全网最详细),零基础入门到精通,从看这一篇开始!

一.初聊Python在学习Python之前,你不要担心自己没基础或“脑子笨”,我始终认为,只要你想学并为之努力,就能学好,就能用Python去做很多事情。在这个喧嚣的时代,很多技术或概念会不断兴起,我希望你能沉下心来去学习,不要急于求成,一步一个脚印。当你把某个技术学好、学精后,还是能做一些事情的,甚至能找到喜欢的工作或完成实践项目。程序语言没有最好,只有最适合。作为一名初学者,我非常推荐你学习Python,为啥?

m0_59236602的博客 11万+

CTF命令执行绕过实战:从空格过滤到无回显外带的7种核心姿势

命令执行漏洞是Web安全中的常见高危漏洞,其核心原理在于应用程序未对用户输入进行充分过滤,导致攻击者能够注入并执行系统命令。在真实环境中,安全防护措施(如WAF、输入过滤函数)普遍存在,因此漏洞利用的关键技术在于“绕过”这些过滤机制。理解过滤器的运作逻辑(如黑名单、白名单、转义、长度限制)是成功绕过的前提。通过系统学习**空格绕过**、**命令黑名单绕过**、**编码混淆**等基础技巧,并结合**无回显外带**、**反弹Shell**等高级利用链,安全研究人员能够有效应对复杂防护场景。本文以CTFshow

weixin_29315091的博客 371

10年程序员职业生涯感悟—写给正在迷茫的你

希望能带给大家不一样的参考。或者能提前预防,少走弯路!

pythonandaiot的博客 1万+

【Office激活】学校正版Office已激活成功仍弹出激活窗口

学校正版Office激活问题:已激活成功仍弹出激活窗口

ESCM_的博客 1万+

生物信息学投稿避坑指南:如何根据影响因子和审稿速度选择最适合的期刊

本文为生物信息学研究者提供全面的期刊投稿策略,重点解析影响因子、审稿速度等关键指标,帮助选择最适合的期刊。涵盖算法开发类和应用型研究的投稿路径,分析不同出版社特点及开放获取的利弊,并提供投稿全流程优化建议,助力高效发表研究成果。

weixin_42652674的博客 382

python后端快速入门_Python语言十分钟快速入门

假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手册(CheatSheet)之间,因此只会包含一些基本概念。很显然,如果你希望真正学好一门语言,你还是需要亲自动手实践的。在此,我会假定你已经有了一定的编程基础,因此我会跳过大部分非Python语言的相关内容。本文将高亮显示重...

weixin_29802189的博客 413

STRING数据库的蛋白质相互作用(PPI)网络分析

在转录调控相关的文献中,我们经常能够看到这样的蛋白质相互作用网络(protein protein interaction network,PPI network)。具体而言,这些相关的文献中首先通过RNA-seq、表达谱芯片或者蛋白质组分析等,找到了在不同分组样本间一系列的差异表达基因或蛋白。

weixin_43029125的博客 9463

python语言入门-Python语言十分钟快速入门

【简介】Python(蟒蛇)是一种动态解释型的编程语言。Python可以在Windows、UNIX、MAC等多种操作系统上使用,也可以在Java、.NET开发平台上使用。python logo【特点】1 Python使用C语言开发,但是Python不再有C语言中的指针等复杂的数据类型。2 Python具有很强的面向对象特性,而且简化了面向对象的实现。它消除了保护类型、抽象类、接口等面向对象的元素。...

q6q6q的专栏 363

告别WSL!用AMD ROCm7在Windows上跑ComfyUI,我的幻x2025 AI Max+ 395体验与性能调优心得

本文详细介绍了在搭载AMD Ryzen AI Max+ 395处理器的幻x2025笔记本上,如何通过ROCm7在Windows原生环境下高效运行ComfyUI,并分享了一系列性能调优技巧和实战经验,帮助开发者摆脱WSL束缚,提升AI创作效率。

weixin_29102619的博客 1127

STM32H743的FDCAN使用方法(1):STM32CubeMX初始化代码生成

STM32H743的FDCAN使用方法(1):STM32CubeMX初始化代码生成。

kevin1499的博客 2572

十分钟快速入门Python语言

Python(蟒蛇)是一种动态解释型的编程语言。Python可以在Windows、UNIX、MAC等多种操作系统上使用,也可以在Java、.NET开发平台上使用。 【特点】 1 Python使用C语言开发,但是Python不再有C语言中的指针等复杂的数据类型。 2 Python具有很强的面向对象特性,而且简化了面向对象的实现。它消除了保护类型、抽象类、接口等面向对象的元素。 3 Python代码块...

web开发与Python 360

智能运营模型的建设与运用实践

一项运营活动的全流程,主要包含客群挖掘与筛选、产品与权益选择、触点与活动选择、运营策略调优等关键环节,涉及客群管理、活动管理、权益管理、触达管理、智能调控等系统支撑需求,如今工商银行已开展与其相对应的推荐模型、分析模型等的研发与实践。自2023年9月该模型被知客运营平台吸收并上线以来,已累计有远程银行中心、吉林分行、重庆分行等30余家分行或机构使用,赋能融e借、积存金、结售汇、基金、理财、存款等12种场景,产生营销客户清单达千万人次,有力促进了保守型理财、天天盈、添益快线、寿险等产品的销售。

银行信息系统应用架构详解 861

python语言新手入门教程-Python语言十分钟快速入门

【简介】Python(蟒蛇)是一种动态解释型的编程语言。Python可以在Windows、UNIX、MAC等多种操作系统上使用,也可以在Java、.NET开发平台上使用。python logo【特点】1 Python使用C语言开发,但是Python不再有C语言中的指针等复杂的数据类型。2 Python具有很强的面向对象特性,而且简化了面向对象的实现。它消除了保护类型、抽象类、接口等面向对象的元素。...

weixin_37988176的博客 194

2021年高职组DCN信息安全管理与评估赛题-国赛真题解析答案

2021年高职组DCN信息安全管理与评估赛题-国赛真题解析答案 购买专栏解锁更多资源 DCRS工作任务 DCRS 开启 telnet 登录功能,用户名 dcn01,密码 dcn01,配置使 用 telnet 方式登录终端界面前显示如下授权信息: “WARNING!!! Authorised access only, all of your done will be recorded! Disconnected IMMEDIATELY if you are not an authorised user! O

Jay 1013

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

python语言入门教程-Python语言十分钟快速入门

【简介】Python(蟒蛇)是一种动态解释型的编程语言。Python可以在Windows、UNIX、MAC等多种操作系统上使用,也可以在Java、.NET开发平台上使用。python logo【特点】1 Python使用C语言开发,但是Python不再有C语言中的指针等复杂的数据类型。2 Python具有很强的面向对象特性,而且简化了面向对象的实现。它消除了保护类型、抽象类、接口等面向对象的元素。...

weixin_37988176的博客 112

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

python语言入门u-Python语言十分钟快速入门

【简介】Python(蟒蛇)是一种动态解释型的编程语言。Python可以在Windows、UNIX、MAC等多种操作系统上使用,也可以在Java、.NET开发平台上使用。python logo【特点】1 Python使用C语言开发,但是Python不再有C语言中的指针等复杂的数据类型。2 Python具有很强的面向对象特性,而且简化了面向对象的实现。它消除了保护类型、抽象类、接口等面向对象的元素。...

weixin_37988176的博客 135

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

快速入门:十分钟学会Python

最近开始整理python的资料,博主建立了一个qq群,希望给大家提供一个交流的同平台 78486745 。 初试牛刀 假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手册(CheatSheet)之间,因此只会包含一些基本概念。很显然,如果你希望真正学好一门语言,你还...

weixin_33859231的博客 96

十分钟python入门教程

from: http://hi.baidu.com/wxipi/blog/item/dcbf1f500991975b1038c298.html from: http://yunhaozou.org/perl-shell/314.html from: http://roclinux.cn/?p=2338 看到好多同学在求Python教程,其实完全没必要, Python非常的简单,简单

sunvince的专栏 3766

一分钟教你学会python_十分钟学会Python_快速学习

假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。初试牛刀1假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手册(CheatSheet)之间,因此只会包含一些基本概念。很显然,如果你希望真正学好...

weixin_39847945的博客 141
上一篇: 一个熟练程序员所具备的特质
下一篇: 现在开始创业,到底做啥项目火?
ifeves
博客等级 码龄7年 119粉丝 229原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值