首页 > 代码库 > 【CS231n学习笔记】2. python numpy 之numpy
【CS231n学习笔记】2. python numpy 之numpy
Numpy
数组的创建
import numpy as np a = np.full((3, 3), 1) print(a) a = np.random.random((3, 3)) print(a) a = np.eye(3) print(a) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(a) print(a.shape)
输出: [[1 1 1] [1 1 1] [1 1 1]] [[ 0.09670856 0.44868154 0.43326738] [ 0.57400445 0.47124464 0.76310375] [ 0.72557452 0.98591433 0.97147127]] [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]] [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] (4, 4)
数组的访问方法
import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(a) print(a.shape) print(a[1:3]) print(a[1:-1, 1:-1]) print(a[0, 1]) print(a[1:3, 2]) print(a[2, 1:3]) print(a[[0, 1, 3, 3], [2, 3, 2, 2]]) # print a[0,2],a[1,3],a[3,2],a[3,2]
输出: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12] [13 14 15 16]] (4, 4) [[ 5 6 7 8] [ 9 10 11 12]] [[ 6 7] [10 11]] 2 [ 7 11] [10 11] [ 3 8 15 15]
蜜汁用法
import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) print(np.arange(4)) print(np.full([1, 4], 1)) print(a[np.arange(4), 1]) a[np.arange(4), [2, 3, 2, 3]] += 100 print(a)
[0 1 2 3] [[1 1 1 1]] [ 2 6 10 14] [[ 1 2 103 4] [ 5 6 7 108] [ 9 10 111 12] [ 13 14 15 116]]
布尔
import numpy as np a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) b = a > 5 # 还有这种操作??? print(b) print(a[a > 6])
[[False False False False]
[False True True True]
[ True True True True]
[ True True True True]]
[ 7 8 9 10 11 12 13 14 15 16]
数组计算
import numpy as np a = np.array([1, 2]) b = np.array([3, 4]) print(a + b) print(a - b) print(a * b) print(a / b) print(a * 2) print(a + 3) print(a ** 0.5)
[4 6] [-2 -2] [3 8] [ 0.33333333 0.5 ] [2 4] [4 5] [ 1. 1.41421356]
矩阵乘法&转置
import numpy as np a = np.array([1, 2]) b = np.array([3, 4]) print(a.dot(b)) # 相当于自动把b竖起来,相当于两个向量内积 a = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([[1, 2, 3], [4, 5, 6]]) print(b.T) # 转置 print(a.dot(b.T)) # 矩阵乘法
11 [[1 4] [2 5] [3 6]] [[14 32] [32 77]]
求和
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.sum()) # 求和
21
各种函数 http://link.zhihu.com/?target=http%3A//docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html
广播
秩不同的矩阵能一起运算
import numpy as np a = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) b = np.array([1, 1, 0]) print(a + b) v = np.array([1, 2, 3]) w = np.array([4, 5]) v.reshape([3, 1]) print(v.reshape(3, 1) + w) print(w + v.reshape(3, 1))
[[2 3 3] [2 3 3] [2 3 3]] [[5 6] [6 7] [7 8]] [[5 6] [6 7] [7 8]]
【CS231n学习笔记】2. python numpy 之numpy
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。