小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Python中基礎(chǔ)使用及Numpy、Scipy、Matplotlib 使用教程

 Bookroom for JetYang 2021-02-16

本文主要根據(jù) 斯坦福CS231n課程的Python 教程進(jìn)行整理,原文地址為http://cs231n./python-numpy-tutorial/,官方Python指南網(wǎng)址https://www./doc/

Python是本身是一個(gè)通用的編程語(yǔ)言,但其具有一些庫(kù)(numpy,scipy,matplotlib)用于科學(xué)運(yùn)算,原文的Python的版本是3.5。

本文先進(jìn)行Python的基本介紹(數(shù)據(jù)、容器、函數(shù)、類)然后再介紹Numpy庫(kù)、SciPy庫(kù)以及MatPlotlib庫(kù)的常用方法。

Python基本數(shù)據(jù)類型

  1. 整型 int ,浮點(diǎn)型 float (注:Python沒(méi)有i++這種語(yǔ)句,乘方用x**i)
  2. 布爾型 booleans (注:Python 使用 and 、or、not替代C語(yǔ)言的&&、||、??;t!=f表示t和f的異或)
  3. 字符串型 strings (注:Python中字符串可以用單引號(hào)或雙引號(hào)表示,一些常用的函數(shù)如大小寫、去除空格、字符串替換、空格位置調(diào)整等,去掉空格s.strip()字符串替換s.replace('l','ell')具體使用什么函數(shù)可以現(xiàn)查)

Python容器

  • 列表 list,與數(shù)組相同但是可變大?。ㄗⅲ合聵?biāo)從0開始算,與maltab從1開始算不同)
  1. xs = [3, 1, 2] # Create a list
  2. print(xs, xs[2]) # Prints "[3, 1, 2] 2" 注意小標(biāo)從0開始
  3. print(xs[-1]) # 負(fù)數(shù)下標(biāo)從后往前數(shù); prints "2"
  4. xs[2] = 'foo' # 列表的元素可以類型不同
  5. print(xs) # Prints "[3, 1, 'foo']"
  6. xs.append('bar') # 增加元素
  7. print(xs) # Prints "[3, 1, 'foo', 'bar']"
  8. x = xs.pop() # 刪除最后一個(gè)元素
  9. print(x, xs) # Prints "bar [3, 1, 'foo']"

切片:list使用中的一個(gè)重要方法(注:切片的下標(biāo)左邊界包含,右邊界不包含,與matlab兩邊界都包含不同)

  1. nums = list(range(5)) # 利用list()函數(shù)生成列表
  2. print(nums) # Prints "[0, 1, 2, 3, 4]"
  3. print(nums[2:4]) # 切片下標(biāo)2到(4-1); prints "[2, 3]"
  4. print(nums[2:]) # 切片下標(biāo)2到最后; prints "[2, 3, 4]"
  5. print(nums[:2]) # 切片開始到下標(biāo)(2-1); prints "[0, 1]"
  6. print(nums[:]) # 切片全部; prints "[0, 1, 2, 3, 4]"
  7. print(nums[:-1]) # 切片開始到(-1-1); prints "[0, 1, 2, 3]"
  8. nums[2:4] = [8, 9] # 將下標(biāo)2,3的值替換成8,9
  9. print(nums) # Prints "[0, 1, 8, 9, 4]"

 列表元素循環(huán)(與matlab相同)

  1. animals = ['cat', 'dog', 'monkey']
  2. for animal in animals:
  3. print(animal)
  4. # 三行分別打印 cat dog monkey

也可以利用內(nèi)建函數(shù)enumerate(Lists)取得下標(biāo)(從0開始)和元素

  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

列表解析:一種生成新的列表的方式,舉兩個(gè)例子

  1. nums = [0, 1, 2, 3, 4]
  2. squares = [x ** 2 for x in nums]
  3. 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,存儲(chǔ)鍵值對(duì)(key,value)
  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"

字典循環(huán)

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

也可以利用內(nèi)建函數(shù)d.items()取得鍵和值

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

字典解析,利用表達(dá)式生成字典

  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(注:集合中元素?zé)o序且不重復(fù))
  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"

集合循環(huán),與數(shù)組循環(huán)語(yǔ)法相同,但是注意其無(wú)序性。

  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"

集合解析:利用解析表達(dá)式生成集合

  1. from math import sqrt
  2. nums = {int(sqrt(x)) for x in range(30)}
  3. print(nums) # Prints "{0, 1, 2, 3, 4, 5}"
  • 元組 tuple,與數(shù)組類似,但其實(shí)不可變的列表,因此可以作為字典dictionary中的鍵key或集合set的元素(注:列表由于可變無(wú)法成為dictionary的key和set的元素)
  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 "<class 'tuple'>"
  4. print(d[t]) # Prints "5"
  5. print(d[(1, 2)]) # Prints "1"

Python函數(shù)

利用關(guān)鍵字def,返回使用return

  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"

參數(shù)可以使可選的的例子

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

Python類

定義類的Python語(yǔ)法的格式如下

  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') # 構(gòu)造Greeter類的實(shí)例
  12. g.greet() # 調(diào)用類函數(shù);prints "Hello, Fred"
  13. g.greet(loud=True) # 調(diào)用類函數(shù); prints "HELLO, FRED!"

Numpy

numpy庫(kù)用于python科學(xué)計(jì)算,與matlab有相似之處,其核心是對(duì)數(shù)組arrays的操作。

數(shù)組arrays

數(shù)組array是numpy提供的容器,能夠通過(guò)列表list生成,利用方括號(hào)取元素(注:下標(biāo)從0開始)

  1. import numpy as np
  2. a = np.array([1, 2, 3]) # Create a rank 1 array
  3. print(type(a)) # Prints "<class '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"

與matlab類似,numpy提供了一些生成特殊數(shù)組的函數(shù)

  1. import numpy as np
  2. a = np.zeros((2,2)) # Create an array of all zeros
  3. print(a) # Prints "[[ 0. 0.]
  4. # [ 0. 0.]]"
  5. b = np.ones((1,2)) # Create an array of all ones
  6. print(b) # Prints "[[ 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]]"

數(shù)組切片,利用方括號(hào)內(nèi)的逗號(hào)和冒號(hào)對(duì)每個(gè)維度進(jìn)行索引,基本與matlab相同(注:左包括右不包括)

  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. # Use slicing to pull out the subarray consisting of the first 2 rows
  8. # and columns 1 and 2; b is the following array of shape (2, 2):
  9. # [[2 3]
  10. # [6 7]]
  11. b = a[:2, 1:3]
  12. # A slice of an array is a view into the same data, so modifying it
  13. # will modify the original array.
  14. print(a[0, 1]) # Prints "2"
  15. b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
  16. print(a[0, 1]) # Prints "77"

與matlab不同的是,切片時(shí)使用單個(gè)數(shù)字索引和使用冒號(hào)的索引的結(jié)果維度是不同的,例如

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

這里有一個(gè)較為奇怪的整數(shù)索引的方式,但這種表達(dá)方便創(chuàng)建數(shù)組。

  1. import numpy as np
  2. a = np.array([[1,2], [3, 4], [5, 6]])
  3. # An example of integer array indexing.
  4. # The returned array will have shape (3,) and
  5. print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
  6. # The above example of integer array indexing is equivalent to this:
  7. print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
  8. # When using integer array indexing, you can reuse the same
  9. # element from the source array:
  10. print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
  11. # Equivalent to the previous integer array indexing example
  12. print(np.array([a[0, 1], a[0, 1]])) # Prints "[2 2]"
  1. # Create a new array from which we will select elements
  2. a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
  3. print(a) # prints "array([[ 1, 2, 3],
  4. # [ 4, 5, 6],
  5. # [ 7, 8, 9],
  6. # [10, 11, 12]])"
  7. # Create an array of indices
  8. b = np.array([0, 2, 0, 1])
  9. # Select one element from each row of a using the indices in b
  10. print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]"
  11. # Mutate one element from each row of a using the indices in b
  12. a[np.arange(4), b] += 10
  13. print(a) # prints "array([[11, 2, 3],
  14. # [ 4, 5, 16],
  15. # [17, 8, 9],
  16. # [10, 21, 12]])

利用布爾表達(dá)式進(jìn)行索引

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

關(guān)于數(shù)組的索引就只介紹一小部分,當(dāng)有需要時(shí)請(qǐng)查看官方文檔深入學(xué)習(xí)。https://docs./doc/numpy/reference/arrays.indexing.html

數(shù)組的元素類型可以根據(jù)需求進(jìn)行定義

  1. import numpy as np
  2. x = np.array([1, 2]) # Let numpy choose the datatype
  3. print(x.dtype) # Prints "int64"
  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的數(shù)學(xué)運(yùn)算,(注意與matlab不同,乘除法是每一個(gè)位置的元素乘除法,不是矩陣運(yùn)算)

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

矩陣乘法采用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))

一些有用的矩陣運(yùn)算方法,例如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]"

當(dāng)需要使用某些函數(shù)時(shí),進(jìn)行搜索https://docs./doc/numpy/reference/routines.math.html

矩陣轉(zhuǎn)置

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

廣播機(jī)制:numpy中一個(gè)重要而有用的機(jī)制,可以將小的矩陣進(jìn)行擴(kuò)展后與大矩陣進(jìn)行運(yùn)算,省for循環(huán),提高運(yùn)算速度。

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

還能更加簡(jiǎn)潔

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

我們整理一些廣播broadcasting的規(guī)則:

1、兩個(gè)數(shù)組的維數(shù)不相同,低維度的擴(kuò)展維度

2、兩個(gè)數(shù)組在某個(gè)維度上size相同或小的size是1

3、廣播相當(dāng)于沿著size為1的地方進(jìn)行復(fù)制

下面用例子來(lái)展示一下廣播

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

更多關(guān)于Numpy的內(nèi)容,請(qǐng)看官方文件http://docs./doc/numpy/reference/

SciPy

SciPy庫(kù)基于Numpy庫(kù),提供了許多操作數(shù)組array的函數(shù),官方文件http://docs./doc/scipy/reference/index.html

圖片操作

  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)

讀寫matlab文件

scipy.io.loadmat 與scipy.io.savemat,用到請(qǐng)看http://docs./doc/scipy/reference/io.html

’計(jì)算點(diǎn)間距離

  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.pyplot的作圖模塊,與matlab中的使用類似

  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.

多條曲線、圖標(biāo)題、圖例、坐標(biāo)等

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

與matlab相同,利用subplot分區(qū)域作圖

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

顯示圖像

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

 

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多