CS231n Convolutional Neural Networks for Visual Recognition------Python Tutorial

源链接为:http://cs231n.github.io/python-numpy-tutorial/。

这篇指导书是由Justin Johnson编写的。

在这门课程中我们将使用Python语言完成所有变成任务!Python本身就是一种很棒的通用编程语言,但是在一些流行的库帮助下(numpy,scipy,matplotlib)它已经成为科学计算的强大环境。
我们希望你们中的许多人都有一些Python和numpy的使用经验; 对你们其他人来说,这个section将作为Python用于科学计算和使用的快速速成课程。
你们中的一些人可能已经掌握了Matlab的知识,在这种情况下我们也推荐使用numpy。

你也可以阅读由Volodymyr Kuleshov和Isaac Caswell(CS 228)编写的Notebook版笔记。

本教程使用的Python版本为Python3.


目录

Basic data types

Containers

Lists

Dictionaries

Sets

Tuples:

Functions

Classes


原文共分为4部分,分别介绍了Python、Numpy、Scipy和Matplotlib的使用。本次翻译为第一部分:Python的使用指导!

Python是一种高级动态类型的多范式编程语言。 经常说Python代码几乎像伪代码,因为它允许你在很少的代码行中表达非常强大的想法。 作为一个例子,这里是经典的快速排序算法的实现。

def quicksort(arr):if len(arr) <= 1:return arrpivot = arr[len(arr) // 2]left = [x for x in arr if x < pivot]middle = [x for x in arr if x == pivot]right = [x for x in arr if x > pivot]return quicksort(left) + middle + quicksort(right)print(quicksort([3,6,8,10,1,2,1]))[1, 1, 2, 3, 6, 8, 10]

Basic data types

和其它语言一样,Python也有许多基本数据类型,包括整数,浮点数,布尔类型,和字符类型。这些数据类型的行为和其它语言十分相似。
Numbers:整数和浮点数的运算和其它一样。
注意:和其它语言不同的是,Python没有递增(++)和递减(--)运算符。

%matplotlib inline
x = 3
print(type(x)) # Prints "<class 'int'>"
print(x)       # Prints "3"
print(x + 1)   # Addition; prints "4"
print(x - 1)   # Subtraction; prints "2"
print(x * 2)   # Multiplication; prints "6"
print(x ** 2)  # Exponentiation; prints "9"
x += 1
print(x)  # Prints "4"
x *= 2
print(x)  # Prints "8"
y = 2.5
print(type(y)) # Prints "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"

Python还有许多内置的复杂数字类型,你可以在这里找到所有的细节。

Booleans:Python实现了布尔逻辑的所有常用运算符,但使用的是英语单词而不是符号(&&,||等):

t = True
f = False
print(type(t)) # Prints "<class 'bool'>"
print(t and f) # Logical AND; prints "False"
print(t or f)  # Logical OR; prints "True"
print(not t)   # Logical NOT; prints "False"
print(t != f)  # Logical XOR; prints "True"

Strings:Python对字符串有很大的支持

hello = 'hello'    # String literals can use single quotes
world = "world"    # or double quotes; it does not matter.
print(hello)       # Prints "hello"
print(len(hello))  # String length; prints "5"
hw = hello + ' ' + world  # String concatenation
print(hw)  # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)  # prints "hello world 12"

字符串对象有很多实用的方法:例如

s = "hello"
print(s.capitalize())  # Capitalize a string; prints "Hello"
print(s.upper())       # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7))      # Right-justify a string, padding with spaces; prints "  hello"
print(s.center(7))     # Center a string, padding with spaces; prints " hello "
print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;# prints "he(ell)(ell)o"
print('  world '.strip())  # Strip leading and trailing whitespace; prints "world"

Containers

Python包含几种内置容器类型:列表,字典,集合和元组。

Lists

列表是Python中的数组,但是可以调整大小并且可以包含不同类型的元素:

xs = [3, 1, 2]    # Create a list
print(xs, xs[2])  # Prints "[3, 1, 2] 2"
print(xs[-1])     # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo'     # Lists can contain elements of different types
print(xs)         # Prints "[3, 1, 'foo']"
xs.append('bar')  # Add a new element to the end of the list
print(xs)         # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop()      # Remove and return the last element of the list
print(x, xs)      # Prints "bar [3, 1, 'foo']"

像往常一样,您可以在文档中找到有关列表的所有详细信息。

切片:除了一次访问一个列表元素外,Python还提供了访问子列表的简明语法; 这被称为切片:

nums = list(range(5))     # range is a built-in function that creates a list of integers
print(nums)               # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4])          # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:])           # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2])           # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:])            # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1])          # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9]        # Assign a new sublist to a slice
print(nums)               # Prints "[0, 1, 8, 9, 4]"

循环:您可以循环遍历列表的元素,如下所示:

animals = ['cat', 'dog', 'monkey']
for animal in animals:print(animal)
# Prints "cat", "dog", "monkey", each on its own line.

如果要访问循环体内每个元素的索引,请使用内置枚举函数:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):print('#%d: %s' % (idx + 1, animal))
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line

列表解析:编程时,我们经常要将一种数据转换为另一种。 举个简单的例子,考虑以下计算平方数的代码:

nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:squares.append(x ** 2)
print(squares)   # Prints [0, 1, 4, 9, 16]

你可以使用列表解析来减少代码量:

nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)   # Prints [0, 1, 4, 9, 16]

列表解析也可以包含一些特定条件:

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)  # Prints "[0, 4, 16]"

Dictionaries

字典存储(键,值)对,类似于Java中的Map或Javascript中的对象。 你可以像这样使用它:

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
print(d['cat'])       # Get an entry from a dictionary; prints "cute"
print('cat' in d)     # Check if a dictionary has a given key; prints "True"
d['fish'] = 'wet'     # Set an entry in a dictionary
print(d['fish'])      # Prints "wet"
# print(d['monkey'])  # KeyError: 'monkey' not a key of d
print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"
del d['fish']         # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"

你可以在文档里找到所有你需要知道的。

循环:在字典里通过键来迭代很容易。

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d:legs = d[animal]print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"

如果要访问键及其对应的值,请使用items方法:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():print('A %s has %d legs' % (animal, legs))
# Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"

字典解析:这些与列表解析类似,但允许您轻松构建字典。 例如:

nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)  # Prints "{0: 0, 2: 4, 4: 16}"

Sets

集合是不同元素的无序集合。 举个简单的例子:

animals = {'cat', 'dog'}
print('cat' in animals)   # Check if an element is in a set; prints "True"
print('fish' in animals)  # prints "False"
animals.add('fish')       # Add an element to a set
print('fish' in animals)  # Prints "True"
print(len(animals))       # Number of elements in a set; prints "3"
animals.add('cat')        # Adding an element that is already in the set does nothing
print(len(animals))       # Prints "3"
animals.remove('cat')     # Remove an element from a set
print(len(animals))       # Prints "2"

同样的,任何关于集合你想知道的事都可以在这里找到。

循环:对集合进行迭代与迭代列表具有相同的语法; 但是由于集合是无序的,因此您无法对访问集合元素的顺序进行假设:

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):print('#%d: %s' % (idx + 1, animal))
# Prints "#1: fish", "#2: dog", "#3: cat"

集合解析:和列表和字典一样,我们可以使用集合解析来构造集合。

from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)  # Prints "{0, 1, 2, 3, 4, 5}"

Tuples:

元组是(不可变的)有序值列表。 元组在很多方面类似于列表; 其中一个最重要的区别是元组可以用作字典中的键和集合的元素,而列表则不能。 这是一个简单的例子:

d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)        # Create a tuple
print(type(t))    # Prints "<class 'tuple'>"
print(d[t])       # Prints "5"
print(d[(1, 2)])  # Prints "1"

这篇文档有更多关于元组的信息。

Functions

Python的函数是使用def来定义的,如下:

def sign(x):if x > 0:return 'positive'elif x < 0:return 'negative'else:return 'zero'for x in [-1, 0, 1]:print(sign(x))
# Prints "negative", "zero", "positive"

我们经常定义函数来获取可选的关键字参数:

def hello(name, loud=False):if loud:print('HELLO, %s!' % name.upper())else:print('Hello, %s' % name)hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True)  # Prints "HELLO, FRED!"

这里有关于Python函数的更多信息。

Classes

在Python中定义类的语法很简单:

class Greeter(object):# Constructordef __init__(self, name):self.name = name  # Create an instance variable# Instance methoddef greet(self, loud=False):if loud:print('HELLO, %s!' % self.name.upper())else:print('Hello, %s' % self.name)g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

这里有关于Pythonclasses的更多信息。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/440012.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【HDU - 3081】Marriage Match II(网络流最大流,二分+网络流)

题干&#xff1a; Presumably, you all have known the question of stable marriage match. A girl will choose a boy; it is similar as the game of playing house we used to play when we are kids. What a happy time as so many friends playing together. And it is …

IP、TCP、UDP、HTTP头部信息

IP头部信息 ip报文段格式 版本&#xff1a; 占4位&#xff0c;表明IP协议实现的版本号&#xff0c;当前一般为IPv4&#xff0c;即0100。报头长度 &#xff1a; 占4位&#xff0c;因为头部长度不固定&#xff08;Option可选部分不固定&#xff09;&#xff0c;所以需要标识…

ROS技术点滴 —— MoveIt!中的运动学插件

MoveIt!是ROS中一个重要的集成化开发平台&#xff0c;由一系列移动操作的功能包组成&#xff0c;提供运动规划、操作控制、3D感知、运动学等功能模块&#xff0c;是ROS社区中使用度排名前三的功能包&#xff0c;目前已经支持众多机器人硬件平台。 MoveIt!中的众多功能都使用插件…

1)机器学习基石笔记Lecture1:The Learning Problem

网上关于机器学习的课程有很多&#xff0c;其中最著名的是吴恩达老师的课程&#xff0c;最近又发现了NTU林轩田老师的《机器学习基石》课程&#xff0c;这门课也很好。课程总共分为4部分&#xff0c;总共分为16节课&#xff0c;今天来记录第一节课。 When Can Machines Learn?…

MMS协议

MMS格式解析 简介&#xff1a; MMS是微软的私有流媒体协议。 它的最初目的是通过网络传输多媒体广播、视频、音轨、现场直播和一系列的实时或实况材料。 MMS建立在UDP或TCP传输&#xff0f;网络层上&#xff0c;是属于应用层的。使用TCP的MMS上URL是MMS://或者MMST://&#x…

【HDU - 6118】度度熊的交易计划(最小费用可行流,网络流费用流变形 )

题干&#xff1a; 度度熊参与了喵哈哈村的商业大会&#xff0c;但是这次商业大会遇到了一个难题&#xff1a; 喵哈哈村以及周围的村庄可以看做是一共由n个片区&#xff0c;m条公路组成的地区。 由于生产能力的区别&#xff0c;第i个片区能够花费a[i]元生产1个商品&#xff0…

老王说ros的tf库

ros的tf库 为了这个题目&#xff0c;我是拿出了挤沟的精神挤时间&#xff0c;是下了功夫的&#xff0c;线性代数、矩阵论复习了&#xff0c;惯性导航里的dcm、四元数也了解了&#xff0c;刚体力学也翻了&#xff0c;wiki里的欧拉角也读了&#xff0c;tf的tutorial、paper、sou…

Apollo进阶课程 ③ | 开源模块讲解(中)

目录 1&#xff09;ISO-26262概述 2&#xff09;ISO-26262认证流程 3&#xff09;ISO-26262优点与缺陷 原文链接&#xff1a;Apollo进阶课程 ③ | 开源模块讲解&#xff08;中&#xff09; Apollo自动驾驶进阶课程是由百度Apollo联合北京大学共同开设的课程&#xff0c;邀请…

python 问题集

打开文件是报&#xff1a;UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xe9 in position 0: unexpected end of data UnicodeDecodeError:“utf-8”编解码器无法解码位置0中的字节0xe9:unex 在open中加入encodingunicode_escape 如&#xff1a; with open(file_n…

【HDU - 6447】YJJ's Salesman(降维dp,树状数组优化dp)

题干&#xff1a; YJJ is a salesman who has traveled through western country. YJJ is always on journey. Either is he at the destination, or on the way to destination. One day, he is going to travel from city A to southeastern city B. Let us assume that A …

由浅到深理解ROS(5.1)- roslaunch 学习

oslaunch 用处&#xff1a;将多个rosnode 结合起来&#xff0c;一起运行。这样就不需要一个个的运行。 roslaunch格式 &#xff08;add_two.launch&#xff09; <launch> <arg name"a" default"1" /> <arg name"b&q…

CS231n Convolutional Neural Networks for Visual Recognition------Numpy Tutorial

源链接为&#xff1a;http://cs231n.github.io/python-numpy-tutorial/。 这篇指导书是由Justin Johnson编写的。 在这门课程中我们将使用Python语言完成所有变成任务&#xff01;Python本身就是一种很棒的通用编程语言&#xff0c;但是在一些流行的库帮助下&#xff08;numpy&…

【CodeForces - 1047C】Enlarge GCD(数学,枚举,预处理打表,思维)

题干&#xff1a; F先生有n个正整数&#xff0c;a1&#xff0c;a2&#xff0c;...&#xff0c;an 他认为这些整数的最大公约数太小了,所以他想通过删除一些整数来扩大它 您的任务是计算需要删除的最小整数数,以便剩余整数的最大公约数大于所有整数的公约数. Input 3 1 2 4…

TS解析文档

TS格式解析 简介&#xff1a; ts文件为传输流文件&#xff0c;视频编码主要格式h264/mpeg4&#xff0c;音频为acc/MP3。 ts的包是一个一个188字节的包组成&#xff0c;这188字节里面由一个0x47开头的包作为同步。 也就是说&#xff0c;如果你找到了0x47&#xff0c;如果与它相…

ROS入门之——浅谈launch

0.何为launch&#xff1f; launch&#xff0c;中文含义是启动&#xff0c;launch文件顾名思义就是启动文件&#xff0c;要说这launch文件啊&#xff0c;那还得从roslaunch说起。 相传&#xff0c;在程序猿们还没有使用roslaunch之前&#xff0c;需要手动rosrun逐个启动node&am…

2)机器学习基石笔记Lecture2:Learning to Answer Yes/No

目录 0.上节回顾 1. Perceptron Hypothesis Set 2. Perceptron Learning Algorithm(PLA)&#xff08;重点&#xff09; 3. Guarantee of PLA&#xff08;难点&#xff09; 4. Non-Separable Data 0.上节回顾 第一节课主要讲述了机器学习的定义及机器学习的过程&#xff0…

【CodeForces - 616C】The Labyrinth(bfs,并查集,STLset)

题干&#xff1a; 求每个*能够到达的格子数量&#xff0c;只有.可以走&#xff08;四个方向扩展&#xff09;&#xff0c;结果mod 10&#xff0c;替换 * 后输出。 Input The first line contains two integers n, m (1 ≤ n, m ≤ 1000) — the number of rows and co…

scapy和dpkt使用

scapy官方文档 Scapy 下载 # (临时换pip源) pip install scapy (-i https://pypi.tuna.tsinghua.edu.cn/simple/)导入 from scapy.all import *读取pcap文件&#xff0c;进行相关操作 # 读取文件 # 整个文件&#xff1a;packets&#xff1a;scapy.plist.PacketList对象 &…

Google Colab——谷歌免费GPU使用教程

Google Colab简介 Google Colaboratory是谷歌开放的一款研究工具&#xff0c;主要用于机器学习的开发和研究。这款工具现在可以免费使用。Google Colab最大的好处是给广大的AI开发者提供了免费的GPU使用&#xff01;GPU型号是Tesla K80&#xff01;你可以在上面轻松地跑例如&am…

javaBean和Servlet的区别

可以像使用一般的类一样使用JavaBean,Bean只是一种特殊的类。特殊在可以通过<jsp:useBean />调用JavaBean。而其他类,可以和一般java中一样使用。 Bean的参数中还可以指定范围, <jsp:useBean scope"application" />该Bean在服务器的JVM中将只有一个…