【CS231n】Python Tutorial
【1】Python3的使用
基本数据类型
整型,浮点型(支持算数运算)
布尔型(支持逻辑运算:与and、或or、非not、异或!=)
字符型
print(type(t))
# 可查t变量的类型
容器(containers)
列表list
案例:animals = [‘cat’, ‘dog’, ‘monkey’]
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]"
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]"
字典dictionary
案例:d = {‘cat’: ‘cute’, ‘dog’: ‘furry’}
dictionary comprehension【字典推导式】
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}"
集合set
案例:animals = {‘cat’, ‘dog’}
set comprehension【集合推导式】
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums) # Prints "{0, 1, 2, 3, 4, 5}"
元组tuple
案例:t = (5, 6)
tuples can be used as keys in dictionaries and as elements of sets, while lists cannot.(元组可作为字典的关键词、集合的元素,而列表不能)
函数(functions)
使用【def】关键词开头
类(classes)
类中包含constructor(构造函数)和instance method(实例方法)
案例:
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)
【2】Numpy库的使用
在使用前加上
import numpy as np
数组(arrays)
初始化
以list初始化numpy数组
import numpy as np
a = np.array([1, 2, 3]) # Create a rank 1 array
# a.shape: (3, )
b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
# b.shape: (2, 3)
以内设函数初始化numpy数组
import numpy as np
# define m * n
m = 2
n = 3
constant = 7
a = np.zeros((m, n)) # all zeros
b = np.ones((m, n) # all ones
c = np.full((m,n),constant) # all constant
d = np.eye(m) # identity matrix,对角线全1
"""
1 0
0 1
"""
e = np.random.random((m,n)) # random matrix
常用函数:
np.zeros
np.ones
np.full
np.eye
np.random.random
生成一个和x类似的array,可用:
np.empty_like(x)
切片
numpy数组的切片
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
b = a[:2, 1:3]
"""
b取了a的前2行,第1列和第2列(列标和行标从0开始)
a矩阵是
1 2 3 4
5 6 7 8
9 10 11 12
b矩阵是
2 3
6 7
"""
row_r1 = a[1, :] # Rank 1 view of the second row of a
# int和slice同时使用,阶级变低1阶(比如这里是2-1=1阶)
row_r2 = a[1:2, :] # Rank 2 view of the second row of a
# 只使用slice,阶级和原来的numpy数组对其(比如这里是2阶)
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)"
整型下标构造新array
整数下标integer array index,可以从一个array中取出元素,构造出另外一个array
案例:
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]"
"""
这里以b为每一行的列标,从a中取出了元素,构造了新的array
例如,1来自a中第0行的第0个元素,6来自a中第1行的第2个元素
"""
# 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]])
布尔型下标构造新array
布尔型下标:
1:通过条件,给出array中每个元素的布尔值;
2:通过条件,筛选元素,组成新的array
案例:
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 array的元素是相同类型的。
array数学计算
np.add(x, y)
np.subtract(x, y)
np.multiply(x, y)
np.divide(x, y)
np.sqrt(x)
以上都是elementwise(对应行标列表下的一个元素)操作
np.dot(x, y) 点乘
案例:
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))
np.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]"
np.sum对所有元素求和
axis=0,约束为每列求和
axis=1,约束为每行求和
矩阵转置transpose
x = np.array()
new_x = x.T
广播机制broadcasting
通过广播,对齐2个array
案例:
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]]
reshape_v:
[[1,2,3]]
w:
[4,5]
"""
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)
"""
x.T:
1 4
2 5
3 6
w:
4 5
x.T+W:
5 9
6 10
7 11
final result:
5 6 7
9 10 11
"""
print((x.T + w).T)
"""
reshape_w:
[[4,5]]
x:
[[1,2,3],
[4,5,6]]
x+reshape_w:
x的第一行都加4,第二行都加5
"""
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)
【3】SciPy库的使用
图像处理
from scipy.misc import imread, imsave, imresize
# 读取图像
img = imread('assets/cat.jpg')
print(img.dtype, img.shape) # Prints "uint8 (400, 248, 3)"
# 改变颜色通道值
img_tinted = img * [1, 0.95, 0.9]
# 改变图像尺寸
img_tinted = imresize(img_tinted, (300, 300))
# 保存图像
imsave('assets/cat_tinted.jpg', img_tinted)
两点间的距离
import numpy as np
from scipy.spatial.distance import pdist, squareform
# 3个点的坐标:
# [[0 1]
# [1 0]
# [2 0]]
x = np.array([[0, 1], [1, 0], [2, 0]])
print(x)
# 计算邻接矩阵
# [[ 0. 1.41421356 2.23606798]
# [ 1.41421356 0. 1. ]
# [ 2.23606798 1. 0. ]]
d = squareform(pdist(x, 'euclidean'))
print(d)
【4】Matplotlib库的使用
画图
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()
plt.plot(array, array_name):画出array中的点
plt.xlabel(‘x axis label’):添加x坐标轴的变量名称
plt.title(‘TITLE’):添加标题
plt.legend([‘x’,‘y’]):添加图例
plt.show():显示图像
画子图
调用plt.subplot(height, width, number)
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()
显示图像
调用plt.imshow(image)