[关闭]
@K1999 2016-09-22T01:40:22.000000Z 字数 16030 阅读 1829

Stanford CS class CS231n Notes(One):Python Numpy Tutorial

深度学习 CS231n


原文地址:http://cs231n.github.io/python-numpy-tutorial/#matplotlib-subplots

Python

Python语言可以用短短几行代码快速实现你的想法,写出易读易懂的代码。

  1. def quicksort(arr):
  2. if len(arr) <= 1:
  3. return arr
  4. pivot = arr[len(arr) / 2]
  5. left = [x for x in arr if x < pivot]
  6. middle = [x for x in arr if x == pivot]
  7. right = [x for x in arr if x > pivot]
  8. return quicksort(left) + middle + quicksort(right)
  9. print quicksort([3,6,8,10,1,2,1])
  10. # Prints "[1, 1, 2, 3, 6, 8, 10]"

Basic data types

  1. x = 3
  2. print type(x) # Prints "<type 'int'>"
  3. print x # Prints "3"
  4. print x + 1 # Addition; prints "4"
  5. print x - 1 # Subtraction; prints "2"
  6. print x * 2 # Multiplication; prints "6"
  7. print x ** 2 # Exponentiation; prints "9"
  8. x += 1
  9. print x # Prints "4"
  10. x *= 2
  11. print x # Prints "8"
  12. y = 2.5
  13. print type(y) # Prints "<type 'float'>"
  14. print y, y + 1, y * 2, y ** 2 # Prints "2.5 3.5 5.0 6.25"

同大多数语言不一样,Python中没有自增(i++)自减(i--)操作。

Python还实现了所有的布尔逻辑,但是没有使用逻辑运算符(&&, ||, etc.)而是使用英文单词:

  1. t = True
  2. f = False
  3. print type(t) # Prints "<type 'bool'>"
  4. print t and f # Logical AND; prints "False"
  5. print t or f # Logical OR; prints "True"
  6. print not t # Logical NOT; prints "False"
  7. print t != f # Logical XOR; prints "True"

Python对字符串的支持也非常好

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

Python还有一系列字符串处理的有用的方法

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

Containers

Python有许多内置的容器类型,如列表(lists)、字典(dictionaries)、集合(sets)和元组(tuples)等。

列表(Lists)

Python中的列表相当于数组,但是列表长度可变,而且列表中可以包含多种不同类型的元素。

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

切片(Slicing):可以一次性的获得列表的部分元素。

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

循环(Loops):我们可以用如下的方式遍历列表。

  1. animals = ['cat', 'dog', 'monkey']
  2. for animal in animals:
  3. print animal
  4. # Prints "cat", "dog", "monkey", each on its own line.

如果想要在循环体内访问每个元素的指针,可以使用内置的enumerate函数。

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

列表还提供了一种快速的将列表数据元素转换的方法。

  1. # 普通方法
  2. nums = [0, 1, 2, 3, 4]
  3. squares = []
  4. for x in nums:
  5. squares.append(x ** 2)
  6. print squares # Prints [0, 1, 4, 9, 16]
  7. # 简化方法
  8. nums = [0, 1, 2, 3, 4]
  9. squares = [x ** 2 for x in nums]
  10. print squares # Prints [0, 1, 4, 9, 16]

该方法中还可以嵌入条件语句:

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

字典(Dictionaries)

字典可以存储键值对(键,值),类似于Java中的Map。

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

循环(Loops):可以用“键”来很容易的遍历字典。

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

用iteritems( )方法可以很方便的访问字典的键和对应的值:

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

和列表相同,可以很方便的构建字典。

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

集合(Sets)

集合是独立的不同个体无序的组合在一起的容器。

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

遍历集合元素:

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

快速建立集合

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

元祖(Tuples)

元组是一个值的有序列表(不可改变)。从很多方面来说,元组和列表都很相似。和列表最重要的不同在于,元组可以在字典中用作键,还可以作为集合的元素,而列表不行。元组中的元素值是不允许修改的

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

Functions

函数用def()定义。

  1. def sign(x):
  2. if x > 0:
  3. return 'positive'
  4. elif x < 0:
  5. return 'negative'
  6. else:
  7. return 'zero'
  8. for x in [-1, 0, 1]:
  9. print sign(x)
  10. # Prints "negative", "zero", "positive"

函数中的参数是可以带默认值的。

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

Classes

Python中定义类的语法是非常简单的。

  1. class Greeter(object):
  2. # Constructor
  3. def __init__(self, name):
  4. self.name = name # Create an instance variable
  5. # Instance method
  6. def greet(self, loud=False):
  7. if loud:
  8. print 'HELLO, %s!' % self.name.upper()
  9. else:
  10. print 'Hello, %s' % self.name
  11. g = Greeter('Fred') # Construct an instance of the Greeter class
  12. g.greet() # Call an instance method; prints "Hello, Fred"
  13. g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"

Numpy

Numpy是利用Python进行科学计算的核心库。它提供了高性能的多维数组对象,以及相关工具。

数组(Arrays)

首先是创建数据和访问数组中的元素:

  1. import numpy as np
  2. a = np.array([1, 2, 3]) # Create a rank 1 array
  3. print type(a) # Prints "<type 'numpy.ndarray'>"
  4. print a.shape # Prints "(3,)"
  5. print a[0], a[1], a[2] # Prints "1 2 3"
  6. a[0] = 5 # Change an element of the array
  7. print a # Prints "[5, 2, 3]"
  8. b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
  9. print b.shape # Prints "(2, 3)"
  10. print b[0, 0], b[0, 1], b[1, 0] # Prints "1 2 4"

Numpy 还有一些其他的创建数组的方法。

  1. import numpy as np
  2. a = np.zeros((2,2)) # 建立一个全0的数组
  3. print a # Prints "[[ 0. 0.]
  4. # [ 0. 0.]]"
  5. b = np.ones((1,4)) # 建立一个1行4列的数组
  6. print b # Prints "[[ 1. 1. 1. 1.]]"
  7. c = np.full((2,2), 7) # Create a constant array
  8. print c # Prints "[[ 7. 7.]
  9. # [ 7. 7.]]"
  10. d = np.eye(2) # Create a 2x2 identity matrix
  11. print d # Prints "[[ 1. 0.]
  12. # [ 0. 1.]]"
  13. e = np.random.random((2,2)) # Create an array filled with random values
  14. print e # Might print "[[ 0.91940167 0.08143941]
  15. # [ 0.68744134 0.87236687]]"

数组索引(Array indexing)

切片(Slicing):和Python列表类似,Numpy中的数组也有切片操作。因为数组是多维的,所以必须为每个维度指定切片。

  1. import numpy as np
  2. # Create the following rank 2 array with shape (3, 4)
  3. # [[ 1 2 3 4]
  4. # [ 5 6 7 8]
  5. # [ 9 10 11 12]]
  6. a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
  7. # b是a的一个切片,取a的前两行和1、2两列
  8. # [[2 3]
  9. # [6 7]]
  10. b = a[:2, 1:3]
  11. # 切片是原数组的一个视图,所以改变切片中的数据也会改变原数组中的数据。
  12. print a[0, 1] # Prints "2"
  13. b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
  14. print a[0, 1] # Prints "77"

还可以使用整型和切片相结合的方式访问数组元素。

  1. import numpy as np
  2. # Create the following rank 2 array with shape (3, 4)
  3. # [[ 1 2 3 4]
  4. # [ 5 6 7 8]
  5. # [ 9 10 11 12]]
  6. a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
  7. # Two ways of accessing the data in the middle row of the array.
  8. # Mixing integer indexing with slices yields an array of lower rank,
  9. # while using only slices yields an array of the same rank as the
  10. # original array:
  11. row_r1 = a[1, :] # Rank 1 view of the second row of a
  12. row_r2 = a[1:2, :] # Rank 2 view of the second row of a
  13. print row_r1, row_r1.shape # Prints "[5 6 7 8] (4,)"
  14. print row_r2, row_r2.shape # Prints "[[5 6 7 8]] (1, 4)"
  15. # We can make the same distinction when accessing columns of an array:
  16. col_r1 = a[:, 1]
  17. col_r2 = a[:, 1:2]
  18. print col_r1, col_r1.shape # Prints "[ 2 6 10] (3,)"
  19. print col_r2, col_r2.shape # Prints "[[ 2]
  20. # [ 6]
  21. # [10]] (3, 1)"

可以通过整形数组索引的方式访问数组。

  1. import numpy as np
  2. a = np.array([[1,2], [3, 4], [5, 6]])
  3. # a是一个二维数组
  4. print a[[0, 1, 2], [0, 1, 0]]
  5. # 相当于访问a[0][0],a[1][2],a[2][0],Prints "[1 4 5]"
  6. # 上面的用整形数组索引的例子类似于下边的访问方法
  7. print np.array([a[0, 0], a[1, 1], a[2, 0]]) # Prints "[1 4 5]"
  8. # 在用整型数组索引的时候,可以一个元素多次访问。
  9. print a[[0, 0], [1, 1]] # Prints "[2 2]"
  10. # 上面的用整形数组索引的例子类似于下边的访问方法
  11. print np.array([a[0, 1], a[0, 1]]) # Prints "[2 2]"

利用整形数组索引访问数组的一个小窍门:可以利用整形数组索引来选择或者修改数组中每一行中的元素。

  1. import numpy as np
  2. # Create a new array from which we will select elements
  3. a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
  4. print a # prints "array([[ 1, 2, 3],
  5. # [ 4, 5, 6],
  6. # [ 7, 8, 9],
  7. # [10, 11, 12]])"
  8. # Create an array of indices
  9. b = np.array([0, 2, 0, 1])
  10. # Select one element from each row of a using the indices in b
  11. print a[np.arange(4), b] # Prints "[ 1 6 7 11]"
  12. # Mutate one element from each row of a using the indices in b
  13. a[np.arange(4), b] += 10
  14. print a # prints "array([[11, 2, 3],
  15. # [ 4, 5, 16],
  16. # [17, 8, 9],
  17. # [10, 21, 12]])

还有一种布尔型数组索引的方式。布尔型数组访问可以让你选择数组中任意元素。

  1. import numpy as np
  2. a = np.array([[1,2], [3, 4], [5, 6]])
  3. bool_idx = (a > 2) # Find the elements of a that are bigger than 2;
  4. # this returns a numpy array of Booleans of the same
  5. # shape as a, where each slot of bool_idx tells
  6. # whether that element of a is > 2.
  7. print bool_idx # Prints "[[False False]
  8. # [ True True]
  9. # [ True True]]"
  10. # We use boolean array indexing to construct a rank 1 array
  11. # consisting of the elements of a corresponding to the True values
  12. # of bool_idx
  13. print a[bool_idx] # Prints "[3 4 5 6]"
  14. # We can do all of the above in a single concise statement:
  15. print a[a > 2] # Prints "[3 4 5 6]"

数据类型(Datatypes)

Numpy数组内的元素数据类型均相同。Numpy提供了许多数据类型用于创建数组。当你创建数组并且没有指明数组类型的时候,Numpy会去尽力猜测这个数组中的数据类型。Numpy中还提供了一个可选参数,当建立数组时可以明确指出数据类型。

  1. import numpy as np
  2. x = np.array([1, 2]) # Let numpy choose the datatype
  3. print x.dtype # Prints "int32"
  4. x = np.array([1.0, 2.0]) # Let numpy choose the datatype
  5. print x.dtype # Prints "float64"
  6. x = np.array([1, 2], dtype=np.int64) # Force a particular datatype
  7. print x.dtype # Prints "int64"

数组运算(Array math)

  1. import numpy as np
  2. x = np.array([[1,2],[3,4]], dtype=np.float64)
  3. y = np.array([[5,6],[7,8]], dtype=np.float64)
  4. # Elementwise sum; both produce the array
  5. # [[ 6.0 8.0]
  6. # [10.0 12.0]]
  7. print x + y
  8. print np.add(x, y)
  9. # Elementwise difference; both produce the array
  10. # [[-4.0 -4.0]
  11. # [-4.0 -4.0]]
  12. print x - y
  13. print np.subtract(x, y)
  14. # Elementwise product; both produce the array
  15. # [[ 5.0 12.0]
  16. # [21.0 32.0]]
  17. print x * y
  18. print np.multiply(x, y)
  19. # Elementwise division; both produce the array
  20. # [[ 0.2 0.33333333]
  21. # [ 0.42857143 0.5 ]]
  22. print x / y
  23. print np.divide(x, y)
  24. # Elementwise square root; produces the array
  25. # [[ 1. 1.41421356]
  26. # [ 1.73205081 2. ]]
  27. print np.sqrt(x)

在Numpy中,'*'是矩阵元素之间逐个相乘,不是矩阵乘法。矩阵相乘用dot()函数。

  1. import numpy as np
  2. x = np.array([[1,2],[3,4]])
  3. y = np.array([[5,6],[7,8]])
  4. v = np.array([9,10])
  5. w = np.array([11, 12])
  6. # Inner product of vectors; both produce 219
  7. print v.dot(w)
  8. print np.dot(v, w)
  9. # Matrix / vector product; both produce the rank 1 array [29 67]
  10. print x.dot(v)
  11. print np.dot(x, v)
  12. # Matrix / matrix product; both produce the rank 2 array
  13. # [[19 22]
  14. # [43 50]]
  15. print x.dot(y)
  16. print np.dot(x, y)

Numpy还提供了很多有用的数组的计算函数,譬如下边的sum()函数。

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

还有一些数组中的函数用于改造或者操作数组中的元素。譬如可以用数组的属性'T'来进行矩阵转置。

  1. import numpy as np
  2. x = np.array([[1,2], [3,4]])
  3. print x # Prints "[[1 2]
  4. # [3 4]]"
  5. print x.T # Prints "[[1 3]
  6. # [2 4]]"
  7. # Note that taking the transpose of a rank 1 array does nothing:
  8. v = np.array([1,2,3])
  9. print v # Prints "[1 2 3]"
  10. print v.T # Prints "[1 2 3]"

广播(Broadcasting)

Broadcasting是Numpy中的一种强有力的机制,他可以让不同大小的矩阵在一起进行计算。
假设我们想要把一个常数向量加到矩阵的每一行,我们可以这样做:

  1. import numpy as np
  2. # We will add the vector v to each row of the matrix x,
  3. # storing the result in the matrix y
  4. x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
  5. v = np.array([1, 0, 1])
  6. y = np.empty_like(x) # Create an empty matrix with the same shape as x
  7. # Add the vector v to each row of the matrix x with an explicit loop
  8. for i in range(4):
  9. y[i, :] = x[i, :] + v
  10. # Now y is the following
  11. # [[ 2 2 4]
  12. # [ 5 5 7]
  13. # [ 8 8 10]
  14. # [11 11 13]]
  15. print y

上面的方法用到了循环,当矩阵规模足够大的时候,此种方法的执行速度就慢了,可以采用下边的方法:

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

下面是用Numpy的广播机制实现这一功能。

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

下边是广播机制的一些应用。

  1. import numpy as np
  2. # Compute outer product of vectors
  3. v = np.array([1,2,3]) # v has shape (3,)
  4. w = np.array([4,5]) # w has shape (2,)
  5. # To compute an outer product, we first reshape v to be a column
  6. # vector of shape (3, 1); we can then broadcast it against w to yield
  7. # an output of shape (3, 2), which is the outer product of v and w:
  8. # [[ 4 5]
  9. # [ 8 10]
  10. # [12 15]]
  11. print np.reshape(v, (3, 1)) * w
  12. # Add a vector to each row of a matrix
  13. x = np.array([[1,2,3], [4,5,6]])
  14. # x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
  15. # giving the following matrix:
  16. # [[2 4 6]
  17. # [5 7 9]]
  18. print x + v
  19. # Add a vector to each column of a matrix
  20. # x has shape (2, 3) and w has shape (2,).
  21. # If we transpose x then it has shape (3, 2) and can be broadcast
  22. # against w to yield a result of shape (3, 2); transposing this result
  23. # yields the final result of shape (2, 3) which is the matrix x with
  24. # the vector w added to each column. Gives the following matrix:
  25. # [[ 5 6 7]
  26. # [ 9 10 11]]
  27. print (x.T + w).T
  28. # Another solution is to reshape w to be a row vector of shape (2, 1);
  29. # we can then broadcast it directly against x to produce the same
  30. # output.
  31. print x + np.reshape(w, (2, 1))
  32. # Multiply a matrix by a constant:
  33. # x has shape (2, 3). Numpy treats scalars as arrays of shape ();
  34. # these can be broadcast together to shape (2, 3), producing the
  35. # following array:
  36. # [[ 2 4 6]
  37. # [ 8 10 12]]
  38. print x * 2

SciPy

Numpy包提供了高性能的多维数组以及计算和操作这些数组的基本工具。SciPy包基于Numpy,提供了大量的操作和计算numpy数组的函数,这些函数对于各种类型的科学和工程计算非常有用。

图像操作(Image operations)

  1. from scipy.misc import imread, imsave, imresize
  2. # Read an JPEG image into a numpy array
  3. img = imread('assets/cat.jpg')
  4. print img.dtype, img.shape # Prints "uint8 (400, 248, 3)"
  5. # We can tint the image by scaling each of the color channels
  6. # by a different scalar constant. The image has shape (400, 248, 3);
  7. # we multiply it by the array [1, 0.95, 0.9] of shape (3,);
  8. # numpy broadcasting means that this leaves the red channel unchanged,
  9. # and multiplies the green and blue channels by 0.95 and 0.9
  10. # respectively.
  11. img_tinted = img * [1, 0.95, 0.9]
  12. # Resize the tinted image to be 300 by 300 pixels.
  13. img_tinted = imresize(img_tinted, (300, 300))
  14. # Write the tinted image back to disk
  15. imsave('assets/cat_tinted.jpg', img_tinted)

这里写图片描述
左边是原始图片,右边是变色和变形的图片。

点之间的距离(Distance between points)

SciPy定义了一些有用的函数,可以用于计算集合中点之间的距离。
函数scipy.spatial.distance.pdist能够计算给定集合中所有点之间的距离。

  1. import numpy as np
  2. from scipy.spatial.distance import pdist, squareform
  3. # Create the following array where each row is a point in 2D space:
  4. # [[0 1]
  5. # [1 0]
  6. # [2 0]]
  7. x = np.array([[0, 1], [1, 0], [2, 0]])
  8. print x
  9. # Compute the Euclidean distance between all rows of x.
  10. # d[i, j] is the Euclidean distance between x[i, :] and x[j, :],
  11. # and d is the following array:
  12. # [[ 0. 1.41421356 2.23606798]
  13. # [ 1.41421356 0. 1. ]
  14. # [ 2.23606798 1. 0. ]]
  15. d = squareform(pdist(x, 'euclidean'))
  16. print d

Matplotlib

Matplotlib是Python中的一个作图包。

作图(Plotting)

plot是matplotlib包中的一个重要的函数,可以用plot函数画出二维图形。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on a sine curve
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y = np.sin(x)
  6. # Plot the points using matplotlib
  7. plt.plot(x, y)
  8. plt.show() # You must call plt.show() to make graphics appear.

执行上面的代码,得出下边的图形:
这里写图片描述
再加上一点少量的工作,就可以一次画出多条线,并且加上标题等。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on sine and cosine curves
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y_sin = np.sin(x)
  6. y_cos = np.cos(x)
  7. # Plot the points using matplotlib
  8. plt.plot(x, y_sin)
  9. plt.plot(x, y_cos)
  10. plt.xlabel('x axis label')
  11. plt.ylabel('y axis label')
  12. plt.title('Sine and Cosine')
  13. plt.legend(['Sine', 'Cosine'])
  14. plt.show()

这里写图片描述

Subplots

可以使用subplot函数将多幅图画组合在一张图里:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Compute the x and y coordinates for points on sine and cosine curves
  4. x = np.arange(0, 3 * np.pi, 0.1)
  5. y_sin = np.sin(x)
  6. y_cos = np.cos(x)
  7. # Set up a subplot grid that has height 2 and width 1,
  8. # and set the first such subplot as active.
  9. plt.subplot(2, 1, 1)
  10. # Make the first plot
  11. plt.plot(x, y_sin)
  12. plt.title('Sine')
  13. # Set the second subplot as active, and make the second plot.
  14. plt.subplot(2, 1, 2)
  15. plt.plot(x, y_cos)
  16. plt.title('Cosine')
  17. # Show the figure.
  18. plt.show()

这里写图片描述

图像(Images)

可以用imshow()函数显示图片。

  1. import numpy as np
  2. from scipy.misc import imread, imresize
  3. import matplotlib.pyplot as plt
  4. img = imread('assets/cat.jpg')
  5. img_tinted = img * [1, 0.95, 0.9]
  6. # Show the original image
  7. plt.subplot(1, 2, 1)
  8. plt.imshow(img)
  9. # Show the tinted image
  10. plt.subplot(1, 2, 2)
  11. # A slight gotcha with imshow is that it might give strange results
  12. # if presented with data that is not uint8. To work around this, we
  13. # explicitly cast the image to uint8 before displaying it.
  14. plt.imshow(np.uint8(img_tinted))
  15. plt.show()

这里写图片描述

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注