除法
Python2和Python3之间的不同
#Python2
>>> 7/10
0
#Python3
>>> 7/10
0.7
>>> int(7/10)
0
随机生成0-1之间的浮点数的矩阵
import numpy as np
>>> np.random.rand(3,2)
array([[0.56908707, 0.03398069],
[0.19991421, 0.11010911],
[0.67583683, 0.01601891]])
随机生成规定范围内的整数
>>> np.random.randint(0,10,(3,2))
array([[7, 0],
[9, 3],
[7, 3]])
二项分布函数
#np.random.binomial(n,p,size=N),函数的返回值表示n中成功的次数
>>> np.random.binomial(5, 0.5, size=(2,3)) # 一次试验抛5次硬币朝上的硬币数,做2*3次试验
array([[2, 2, 3],
[3, 5, 3]])
程序运行时间
import time
time_start=time.time()
time_end=time.time()
print('totally cost',time_end-time_start)
矩阵乘法
使用numpy:二维矩阵得到矩阵乘积,一维矩阵得到两者内积
import numpy as np
# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
# 2-D array: 3 x 2
two_dim_matrix_two = np.array([[1, 2], [3, 4], [5, 6]])
two_multi_res = np.dot(two_dim_matrix_one, two_dim_matrix_two)
print('two_multi_res: %s' %(two_multi_res))
# 1-D array
one_dim_vec_one = np.array([1, 2, 3])
one_dim_vec_two = np.array([4, 5, 6])
one_result_res = np.dot(one_dim_vec_one, one_dim_vec_two)
print('one_result_res: %s' %(one_result_res))
output:
two_multi_res: [[22 28]
[49 64]]
one_result_res: 32
不调包的普通票那个矩阵乘法
#A\B两个矩阵相乘
def matrixMul(A, B):
return [[sum(a * b for a, b in zip(a, b)) for b in zip(*B)] for a in A]
zip()函数
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
图片下采样(numpy数组按固定步长抽样、数组求和)
def downsample_avg(img):
batch1 = img[::2,::2,:] #将图片每2*2像素点抽1,分成4部分
batch2 = img[1::2,::2,:]
batch3 = img[::2,1::2,:]
batch4 = img[1::2,1::2,:]
return ((np.sum([batch1,batch2,batch3,batch4], axis = 0))/4) #求和并取均值,axis = 0表示纵向求和