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沒有遞增(++)和遞減(--)運算符。
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的更多信息。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的CS231n Convolutional Neural Networks for Visual Recognition------Python Tutorial的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2月新基金发行量降温,是大跌之后不敢买了
- 下一篇: 【51nod-1289】大鱼吃小鱼