CS231n課程筆記翻譯:Python Numpy教程

譯者注:本文智能單元首發,翻譯自斯坦福CS231n課程筆記Python Numpy Tutorial,由課程教師Andrej Karpathy授權進行翻譯。本篇教程由杜客翻譯完成,Flood SungSunisDown鞏子嘉和一位不願透露ID的知友對本翻譯亦有貢獻。


原文如下

這篇教程由Justin Johnson創作。


我們將使用Python編程語言來完成本課程的所有作業。Python是一門偉大的通用編程語言,在一些常用庫(numpy, scipy, matplotlib)的幫助下,它又會變成一個強大的科學計算環境。

我們期望你們中大多數人對於Python語言和Numpy庫比較熟悉,而對於沒有Python經驗的同學,這篇教程可以幫助你們快速瞭解Python編程環境和如何使用Python作爲科學計算工具。

一部分同學對於Matlab有一定經驗。對於這部分同學,我們推薦閱讀 numpy for Matlab users頁面。

你們還可以查看本教程的IPython notebook版。該教程是由Volodymyr KuleshovIsaac Caswell爲課程CS 228創建的。

內容列表:

  • Python
    • 基本數據類型
    • 容器
      • 列表
      • 字典
      • 集合
      • 元組
    • 函數
  • Numpy
    • 數組
    • 訪問數組
    • 數據類型
    • 數組計算
    • 廣播
  • SciPy
    • 圖像操作
    • MATLAB文件
    • 點之間的距離
  • Matplotlib
    • 繪製圖形
    • 繪製多個圖形
    • 圖像

Python

Python是一種高級的,動態類型的多範型編程語言。很多時候,大家會說Python看起來簡直和僞代碼一樣,這是因爲你能夠通過很少行數的代碼表達出很有力的思想。舉個例子,下面是用Python實現的經典的quicksort算法例子:

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.4。這有點讓人迷惑,3.0向語言中引入了很多不向後兼容的變化,2.7下的代碼有時候在3.4下是行不通的。在這個課程中,我們使用的是2.7版本。

如何查看版本呢?使用python --version命令。

基本數據類型

和大多數編程語言一樣,Python擁有一系列的基本數據類型,比如整型、浮點型、布爾型和字符串等。這些類型的使用方式和在其他語言中的使用方式是類似的。

數字:整型和浮點型的使用與其他語言類似。

x = 3
print type(x) # Prints "<type '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 "<type 'float'>"
print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25"

需要注意的是,Python中沒有 x++ 和 x-- 的操作符。

Python也有內置的長整型和複雜數字類型,具體細節可以查看文檔

布爾型:Python實現了所有的布爾邏輯,但用的是英語,而不是我們習慣的操作符(比如&&和||等)。


t = True
f = False
print type(t) # Prints "<type '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"

字符串對象有一系列有用的方法,比如:

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

譯者注:有知友建議container翻譯爲複合數據類型,供讀者參考。

Python有以下幾種容器類型:列表(lists)、字典(dictionaries)、集合(sets)和元組(tuples)。


列表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 
x = xs.pop()     # Remove and return the last element of the list
print x, xs      # Prints "bar [3, 1, 'foo']"

列表的細節,同樣可以查閱文檔


切片Slicing:爲了一次性地獲取列表中的元素,Python提供了一種簡潔的語法,這就是切片。

nums = 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, 8, 4]"

在Numpy數組的內容中,我們會再次看到切片語法。


循環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]

使用列表推導,你就可以讓代碼簡化很多:

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差不多。你可以這樣使用它:

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"

想要知道字典的其他特性,請查閱文檔


循環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 spider has 8 legs", "A cat has 4 legs"

如果你想要訪問鍵和對應的值,那就使用iteritems方法:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.iteritems():
    print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 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"

和前面一樣,要知道更詳細的,查看文檔


循環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:和字典推導一樣,可以很方便地構建集合:


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

元組Tuples

元組是一個值的有序列表(不可改變)。從很多方面來說,元組和列表都很相似。和列表最重要的不同在於,元組可以在字典中用作鍵,還可以作爲集合的元素,而列表不行。例子如下:
d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
print d
t = (5, 6)       # Create a tuple
print type(t)    # Prints "<type '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!"

函數還有很多內容,可以查看文檔


類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!"

更多類的信息請查閱文檔


Numpy

Numpy是Python中用於科學計算的核心庫。它提供了高性能的多維數組對象,以及相關工具。

數組Arrays

一個numpy數組是一個由不同數值組成的網格。網格中的數據都是同一種數據類型,可以通過非負整型數的元組來訪問。維度的數量被稱爲數組的階,數組的大小是一個由整型數構成的元組,可以描述數組不同維度上的大小。

我們可以從列表創建數組,然後利用方括號訪問其中的元素:

import numpy as np

a = np.array([1, 2, 3])  # Create a rank 1 array
print type(a)            # Prints "<type '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                           # 顯示一下矩陣b
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]]"

其他數組相關方法,請查看文檔

訪問數組

Numpy提供了多種訪問數組的方法。

切片:和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[0, 0] = 77    # b[0, 0] is the same piece of data as a[0, 1]
print a[0, 1]   # Prints "77"

你可以同時使用整型和切片語法來訪問數組。但是,這樣做會產生一個比原數組低階的新數組。需要注意的是,這裏和MATLAB中的情況是不同的:

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

# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:
row_r1 = a[1, :]    # Rank 1 view of the second row of a  
row_r2 = a[1:2, :]  # Rank 2 view of the second row of a
print row_r1, row_r1.shape  # Prints "[5 6 7 8] (4,)"
print row_r2, row_r2.shape  # Prints "[[5 6 7 8]] (1, 4)"

# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print col_r1, col_r1.shape  # Prints "[ 2  6 10] (3,)"
print col_r2, col_r2.shape  # Prints "[[ 2]
                            #          [ 6]
                            #          [10]] (3, 1)"

整型數組訪問:當我們使用切片語法訪問數組時,得到的總是原數組的一個子集。整型數組訪問允許我們利用其它數組的數據構建一個新的數組:

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

# An example of integer array indexing.
# The returned array will have shape (3,) and 
print a[[0, 1, 2], [0, 1, 0]]  # Prints "[1 4 5]"

# The above example of integer array indexing is equivalent to this:
print np.array([a[0, 0], a[1, 1], a[2, 0]])  # Prints "[1 4 5]"

# When using integer array indexing, you can reuse the same
# element from the source array:
print a[[0, 0], [1, 1]]  # Prints "[2 2]"

# Equivalent to the previous integer array indexing example
print np.array([a[0, 1], a[0, 1]])  # Prints "[2 2]"

整型數組訪問語法還有個有用的技巧,可以用來選擇或者更改矩陣中每行中的一個元素:

import numpy as np

# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])

print a  # prints "array([[ 1,  2,  3],
         #                [ 4,  5,  6],
         #                [ 7,  8,  9],
         #                [10, 11, 12]])"

# Create an array of indices
b = np.array([0, 2, 0, 1])

# Select one element from each row of a using the indices in b
print a[np.arange(4), b]  # Prints "[ 1  6  7 11]"

# Mutate one element from each row of a using the indices in b
a[np.arange(4), b] += 10

print a  # prints "array([[11,  2,  3],
         #                [ 4,  5, 16],
         #                [17,  8,  9],
         #                [10, 21, 12]])

布爾型數組訪問:布爾型數組訪問可以讓你選擇數組中任意元素。通常,這種訪問方式用於選取數組中滿足某些條件的元素,舉例如下:

import numpy as np

a = np.array([[1,2], [3, 4], [5, 6]])

bool_idx = (a > 2)  # Find the elements of a that are bigger than 2;
                    # this returns a numpy array of Booleans of the same
                    # shape as a, where each slot of bool_idx tells
                    # whether that element of a is > 2.

print bool_idx      # Prints "[[False False]
                    #          [ True  True]
                    #          [ True  True]]"

# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print a[bool_idx]  # Prints "[3 4 5 6]"

# We can do all of the above in a single concise statement:
print a[a > 2]     # Prints "[3 4 5 6]"

爲了教程的簡介,有很多數組訪問的細節我們沒有詳細說明,可以查看文檔


數據類型

每個Numpy數組都是數據類型相同的元素組成的網格。Numpy提供了很多的數據類型用於創建數組。當你創建數組的時候,Numpy會嘗試猜測數組的數據類型,你也可以通過參數直接指定數據類型,例子如下:

import numpy as np

x = np.array([1, 2])  # Let numpy choose the datatype
print x.dtype         # Prints "int64"

x = np.array([1.0, 2.0])  # Let numpy choose the datatype
print x.dtype             # Prints "float64"

x = np.array([1, 2], dtype=np.int64)  # Force a particular datatype
print x.dtype                         # Prints "int64"

更多細節查看文檔

數組計算

基本數學計算函數會對數組中元素逐個進行計算,既可以利用操作符重載,也可以使用函數方式:

import numpy as np

x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)

# Elementwise sum; both produce the array
# [[ 6.0  8.0]
#  [10.0 12.0]]
print x + y
print np.add(x, y)

# Elementwise difference; both produce the array
# [[-4.0 -4.0]
#  [-4.0 -4.0]]
print x - y
print np.subtract(x, y)

# Elementwise product; both produce the array
# [[ 5.0 12.0]
#  [21.0 32.0]]
print x * y
print np.multiply(x, y)

# Elementwise division; both produce the array
# [[ 0.2         0.33333333]
#  [ 0.42857143  0.5       ]]
print x / y
print np.divide(x, y)

# Elementwise square root; produces the array
# [[ 1.          1.41421356]
#  [ 1.73205081  2.        ]]
print np.sqrt(x)

和MATLAB不同,*是元素逐個相乘,而不是矩陣乘法。在Numpy中使用dot來進行矩陣乘法:

import numpy as np

x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])

v = np.array([9,10])
w = np.array([11, 12])

# Inner product of vectors; both produce 219
print v.dot(w)
print np.dot(v, w)

# Matrix / vector product; both produce the rank 1 array [29 67]
print x.dot(v)
print np.dot(x, v)

# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
#  [43 50]]
print x.dot(y)
print np.dot(x, y)

Numpy提供了很多計算數組的函數,其中最常用的一個是sum

import numpy as np

x = np.array([[1,2],[3,4]])

print np.sum(x)  # Compute sum of all elements; prints "10"
print np.sum(x, axis=0)  # Compute sum of each column; prints "[4 6]"
print np.sum(x, axis=1)  # Compute sum of each row; prints "[3 7]"

想要了解更多函數,可以查看文檔

除了計算,我們還常常改變數組或者操作其中的元素。其中將矩陣轉置是常用的一個,在Numpy中,使用T來轉置矩陣:

import numpy as np

x = np.array([[1,2], [3,4]])
print x    # Prints "[[1 2]
           #          [3 4]]"
print x.T  # Prints "[[1 3]
           #          [2 4]]"

# Note that taking the transpose of a rank 1 array does nothing:
v = np.array([1,2,3])
print v    # Prints "[1 2 3]"
print v.T  # Prints "[1 2 3]"

Numpy還提供了更多操作數組的方法,請查看文檔

廣播Broadcasting

廣播是一種強有力的機制,它讓Numpy可以讓不同大小的矩陣在一起進行數學計算。我們常常會有一個小的矩陣和一個大的矩陣,然後我們會需要用小的矩陣對大的矩陣做一些計算。

舉個例子,如果我們想要把一個向量加到矩陣的每一行,我們可以這樣做:

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x)   # Create an empty matrix with the same shape as x

# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
    y[i, :] = x[i, :] + v

# Now y is the following
# [[ 2  2  4]
#  [ 5  5  7]
#  [ 8  8 10]
#  [11 11 13]]
print y

這樣是行得通的,但是當x矩陣非常大,利用循環來計算就會變得很慢很慢。我們可以換一種思路:

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
print vv                 # Prints "[[1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]
                         #          [1 0 1]]"
y = x + vv  # Add x and vv elementwise
print y  # Prints "[[ 2  2  4
         #          [ 5  5  7]
         #          [ 8  8 10]
         #          [11 11 13]]"

Numpy廣播機制可以讓我們不用創建vv,就能直接運算,看看下面例子:

import numpy as np

# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v  # Add v to each row of x using broadcasting
print y  # Prints "[[ 2  2  4]
         #          [ 5  5  7]
         #          [ 8  8 10]
         #          [11 11 13]]"

對兩個數組使用廣播機制要遵守下列規則:

  1. 如果數組的秩不同,使用1來將秩較小的數組進行擴展,直到兩個數組的尺寸的長度都一樣。
  2. 如果兩個數組在某個維度上的長度是一樣的,或者其中一個數組在該維度上長度爲1,那麼我們就說這兩個數組在該維度上是相容的。
  3. 如果兩個數組在所有維度上都是相容的,他們就能使用廣播。
  4. 如果兩個輸入數組的尺寸不同,那麼注意其中較大的那個尺寸。因爲廣播之後,兩個數組的尺寸將和那個較大的尺寸一樣。
  5. 在任何一個維度上,如果一個數組的長度爲1,另一個數組長度大於1,那麼在該維度上,就好像是對第一個數組進行了複製。

如果上述解釋看不明白,可以讀一讀文檔和這個解釋譯者注:強烈推薦閱讀文檔中的例子。

支持廣播機制的函數是全局函數。哪些是全局函數可以在文檔中查找。

下面是一些廣播機制的使用:

import numpy as np

# Compute outer product of vectors
v = np.array([1,2,3])  # v has shape (3,)
w = np.array([4,5])    # w has shape (2,)
# To compute an outer product, we first reshape v to be a column
# vector of shape (3, 1); we can then broadcast it against w to yield
# an output of shape (3, 2), which is the outer product of v and w:
# [[ 4  5]
#  [ 8 10]
#  [12 15]]
print np.reshape(v, (3, 1)) * w

# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])
# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
# giving the following matrix:
# [[2 4 6]
#  [5 7 9]]
print x + v

# Add a vector to each column of a matrix
# x has shape (2, 3) and w has shape (2,).
# If we transpose x then it has shape (3, 2) and can be broadcast
# against w to yield a result of shape (3, 2); transposing this result
# yields the final result of shape (2, 3) which is the matrix x with
# the vector w added to each column. Gives the following matrix:
# [[ 5  6  7]
#  [ 9 10 11]]
print (x.T + w).T

# Another solution is to reshape w to be a row vector of shape (2, 1);
# we can then broadcast it directly against x to produce the same
# output.
print x + np.reshape(w, (2, 1))

# Multiply a matrix by a constant:
# x has shape (2, 3). Numpy treats scalars as arrays of shape ();
# these can be broadcast together to shape (2, 3), producing the
# following array:
# [[ 2  4  6]
#  [ 8 10 12]]
print x * 2

廣播機制能夠讓你的代碼更簡潔更迅速,能夠用的時候請儘量使用!

Numpy文檔

這篇教程涉及了你需要了解的numpy中的一些重要內容,但是numpy遠不止如此。可以查閱numpy文獻來學習更多。

SciPy

Numpy提供了高性能的多維數組,以及計算和操作數組的基本工具。SciPy基於Numpy,提供了大量的計算和操作數組的函數,這些函數對於不同類型的科學和工程計算非常有用。

熟悉SciPy的最好方法就是閱讀文檔。我們會強調對於本課程有用的部分。

圖像操作

SciPy提供了一些操作圖像的基本函數。比如,它提供了將圖像從硬盤讀入到數組的函數,也提供了將數組中數據寫入的硬盤成爲圖像的函數。下面是一個簡單的例子:

from scipy.misc import imread, imsave, imresize

# Read an JPEG image into a numpy array
img = imread('assets/cat.jpg')
print img.dtype, img.shape  # Prints "uint8 (400, 248, 3)"

# We can tint the image by scaling each of the color channels
# by a different scalar constant. The image has shape (400, 248, 3);
# we multiply it by the array [1, 0.95, 0.9] of shape (3,);
# numpy broadcasting means that this leaves the red channel unchanged,
# and multiplies the green and blue channels by 0.95 and 0.9
# respectively.
img_tinted = img * [1, 0.95, 0.9]

# Resize the tinted image to be 300 by 300 pixels.
img_tinted = imresize(img_tinted, (300, 300))

# Write the tinted image back to disk
imsave('assets/cat_tinted.jpg', img_tinted)

譯者注:如果運行這段代碼出現類似ImportError: cannot import name imread的報錯,那麼請利用pip進行Pillow的下載,可以解決問題。命令:pip install Pillow。

—————————————————————————————————————————

左邊是原始圖片,右邊是變色和變形的圖片。

—————————————————————————————————————————

MATLAB文件

函數scipy.io.loadmatscipy.io.savemat能夠讓你讀和寫MATLAB文件。具體請查看文檔

點之間的距離

SciPy定義了一些有用的函數,可以計算集合中點之間的距離。

函數scipy.spatial.distance.pdist能夠計算集合中所有兩點之間的距離:

import numpy as np
from scipy.spatial.distance import pdist, squareform

# Create the following array where each row is a point in 2D space:
# [[0 1]
#  [1 0]
#  [2 0]]
x = np.array([[0, 1], [1, 0], [2, 0]])
print x

# Compute the Euclidean distance between all rows of x.
# d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
# and d is the following array:
# [[ 0.          1.41421356  2.23606798]
#  [ 1.41421356  0.          1.        ]
#  [ 2.23606798  1.          0.        ]]
d = squareform(pdist(x, 'euclidean'))
print d

具體細節請閱讀文檔

函數scipy.spatial.distance.cdist可以計算不同集合中點的距離,具體請查看文檔

Matplotlib

Matplotlib是一個作圖庫。這裏簡要介紹matplotlib.pyplot模塊,功能和MATLAB的作圖功能類似。

繪圖

matplotlib庫中最重要的函數是Plot。該函數允許你做出2D圖形,如下:

import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
plt.plot(x, y)
plt.show()  # You must call plt.show() to make graphics appear.

運行上面代碼會產生下面的作圖:

—————————————————————————————————————————

—————————————————————————————————————————

只需要少量工作,就可以一次畫不同的線,加上標籤,座標軸標誌等。

import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()

—————————————————————————————————————————

—————————————————————————————————————————

可以在文檔中閱讀更多關於plot的內容。

繪製多個圖像

可以使用subplot函數來在一幅圖中畫不同的東西:

import numpy as np
import matplotlib.pyplot as plt

# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)

# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')

# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')

# Show the figure.
plt.show()

—————————————————————————————————————————

—————————————————————————————————————————

關於subplot的更多細節,可以閱讀文檔

圖像

你可以使用imshow函數來顯示圖像,如下所示:

import numpy as np
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt

img = imread('assets/cat.jpg')
img_tinted = img * [1, 0.95, 0.9]

# Show the original image
plt.subplot(1, 2, 1)
plt.imshow(img)

# Show the tinted image
plt.subplot(1, 2, 2)

# A slight gotcha with imshow is that it might give strange results
# if presented with data that is not uint8. To work around this, we
# explicitly cast the image to uint8 before displaying it.
plt.imshow(np.uint8(img_tinted))
plt.show()

—————————————————————————————————————————

—————————————————————————————————————————

本教程翻譯完畢。

譯者反饋

1.個人水平有限,翻譯中存在的任何問題請大家在評論中或私信我指正,我會認真修改或給出回饋;

2.第一次撰寫知乎專欄,沒有發現文章內的錨點功能。如有,請大家指點;

3.對於Container的翻譯,採取“容器”。亦有知友指出可用“複合數據類型”,未決,請大家點評;

4.對於廣播機制中數組的rank,現在翻譯爲“秩”。亦有知友指出可用“尺寸”,未決,請大家點評;

5.有知友指出文章過長。希望以後能將一篇教程拆分一下,方便大家碎片化閱讀。經我統計,目前希望拆分的知友較多,那麼下篇翻譯將拆分爲上下篇。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章