1. 程式人生 > >[深度學習][CS231n] Python Numpy教程

[深度學習][CS231n] Python Numpy教程

十一七天樂,翻譯自 http://cs231n.github.io/python-numpy-tutorial/
屬於CS231n Convolutional Neural Networks for Visual Recognition課程中關於Python和numpy的科普教程

本教程由Justin Johnson 提供。

本課程中所有作業將使用Python來完成。Python本身就是一種很棒的通用程式語言,現在在一些流行的庫(numpy,scipy,matplotlib)的幫助下,它為科學計算提供強大的環境。

我們希望課程中的大部分人都有一些Python和numpy的經驗;對於其他人來說,本教程將作為Python用於科學計算的速成課程。

另外,一些人由Matlab基礎,我們也提供了numpy for Matlab users供學習者使用。

可以在IPython notebook version of this tutorial here找到Volodymyr KuleshovIsaac Caswell為本科成提供的IPython指令碼。

目錄:

Python

Python是一種高階動態型別的多正規化程式語言。Python程式碼通常被稱為虛擬碼,因為它允許您在非常少的程式碼行中表達非常複雜的演算法,同時具有很強的可讀性。作為示例,這裡是Python中經典快速排序演算法的實現:

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = 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]))
# Prints "[1, 1, 2, 3, 6, 8, 10]"

Python版本

目前有兩種不同的受支援版本的Python,2.7和3.5。但是,Python 3.0後引入了許多向後相容的語言更改,因此為2.7編寫的程式碼可能無法在3.5下執行,反之亦然。對於這個類,所有程式碼都將使用Python 3.5以上版本。

可以通過python --version檢查Python版本。

基本資料型別

與大多數語言一樣,Python有許多基本型別,包括整數,浮點數,布林值和字串。這些資料型別的行為方式與其他程式語言相似。

數字: 整數和浮點數的工作方式與其他語言相同:

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沒有一元增量(x++)和減量(x--)。

Python還有複雜數字的內建型別; 您可以在文件.中找到所有詳細資訊 。

布林: Python中實現所有通常的布林邏輯,但是使用英文詞語(and,or等)而非符號(&&,||等):

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"

字串: 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"

String物件有很多有用的方法; 例如:

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"

您可以在文件中找到所有字串方法的列表。

容器

Python包含幾種內建容器型別: lists, dictionaries, sets, and tuples。

Lists

List是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']"

您可以在文件中找到有關List的所有詳細資訊。

Slicing: 除了一次訪問一個列表元素外,Python還提供了訪問子列表的簡明語法; 這被稱為 slicing:

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]"

我們將在numpy arrays的部分中再次看到slicing。

Loops: 您可以迴圈遍歷列表的元素,如下所示:

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

如果要訪問迴圈體內每個元素的索引,請使用內建enumerate函式:

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

List comprehensions:
程式設計時,我們經常想要將一種資料轉換為另一種資料。舉個簡單的例子,考慮以下計算平方數的程式碼:

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

您可以使用list comprehension使此程式碼更簡單:

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

list comprehension還可以包含條件:

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或Javascript中的Map物件。你可以像這樣使用它:

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"

您可以在文件中找到有關dictionaries的所有資訊。

Loops: 很容易迭代字典中的鍵:

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"

如果要訪問Key及其對應的值,請使用以下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"

Dictionary comprehensions:
這些與列表理解類似,但允許您輕鬆構建字典。例如:

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"

像往常一樣,您可以在文件中找到有關Sets的所有資訊。

Loops: 對集合進行迭代與迭代列表具有相同的語法; 但是由於集合是無序的,因此您無法對訪問集合元素的順序進行假設:

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

Set comprehensions:
像列表和詞典一樣,我們可以使用Set comprehensions輕鬆構建集合:

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

Tuples

Tuple是(不可變的)有序值列表。
Tuple在很多方面類似於列表; 其中一個最重要的區別是Tuple可以用作字典中的鍵和集合的元素,而列表則不能。這是一個簡單的例子:

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):

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def 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!"

您可以在文件中閱讀有關Python類的更多資訊。

Numpy

Numpy 是Python中科學計算的核心庫。它提供了一個高效能的多維陣列物件,以及用於處理這些陣列的工具。如果您已經熟悉MATLAB,那麼您可能會發現本教程對Numpy入門非常有用。

Arrays

numpy arrays是一個值網格,所有型別都相同,並由非負整數元組索引。維數是array的排名; arrays的形狀是一個給出了arrays中的每個維度大小的整數Tuple。

我們可以從巢狀的Python列表初始化numpy array,並使用方括號訪問元素:

import numpy as np

a = np.array([1, 2, 3])   # Create a rank 1 array
print(type(a))            # Prints "<class 'numpy.ndarray'>"
print(a.shape)            # Prints "(3,)"
print(a[0], a[1], a[2])   # Prints "1 2 3"
a[0] = 5                  # Change an element of the array
print(a)                  # Prints "[5, 2, 3]"

b = np.array([[1,2,3],[4,5,6]])    # Create a rank 2 array
print(b.shape)                     # Prints "(2, 3)"
print(b[0, 0], b[0, 1], b[1, 0])   # Prints "1 2 4"

Numpy還提供了許多建立陣列的函式:

import numpy as np

a = np.zeros((2,2))   # Create an array of all zeros
print(a)              # Prints "[[ 0.  0.]
                      #          [ 0.  0.]]"

b = np.ones((1,2))    # Create an array of all ones
print(b)              # Prints "[[ 1.  1.]]"

c = np.full((2,2), 7)  # Create a constant array
print(c)               # Prints "[[ 7.  7.]
                       #          [ 7.  7.]]"

d = np.eye(2)         # Create a 2x2 identity matrix
print(d)              # Prints "[[ 1.  0.]
                      #          [ 0.  1.]]"

e = np.random.random((2,2))  # Create an array filled with random values
print(e)                     # Might print "[[ 0.91940167  0.08143941]
                             #               [ 0.68744134  0.87236687]]"

您可以在文件中閱讀有關其他陣列建立方法 的資訊。

Array indexing

Numpy提供了幾種索引陣列的方法。

Slicing: 與Python列表類似,可以切割numpy陣列。由於陣列可能是多維的,因此必須為陣列的每個維指定一個切片:

import numpy as np

# Create the following rank 2 array with shape (3, 4)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
#  [6 7]]
b = a[:2, 1:3]

# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
print(a[0, 1])   # Prints "2"
b