numpy矩阵的类型为numpy.ndarray, 没有指定数据类型,默认是float64类型
列表与numpy矩阵的转换:
x = [675.99524, 166.36523, 691.63257, 193.72832] y = np.asarray(x) print(x, type(x)) print(y, type(y), y.shape)全零矩阵:
## 创建(2,)维的全0向量 d = np.zeros(2) print(d, d.shape) d = np.zeros((2,1)) print(d, d.shape) d = np.zeros((3,4)) print(d, d.shape) # 下面两个构造方法等价 d = np.zeros((10, 3, 3), dtype=np.uint8) d = np.zeros([10, 3, 3], dtype=np.uint8)注意不同矩阵的维度区别。
全1矩阵:
b = np.ones((1,2))常数矩阵:
c = np.full((2,2), 7) # Create a constant array print(c) # Prints "[[ 7. 7.] # [ 7. 7.]]"单位矩阵:
d = np.eye(2) # Create a 2x2 identity matrix print(d) # Prints "[[ 1. 0.] # [ 0. 1.]]"随机矩阵:
# 创建指定维度的随机矩阵 x = np.random.rand(4,3) x = np.random.random([4,3]) x = np.random.random([4,3,2]) y = np.random.randint(0,10,(4,3)) # [0,10)区间, shape为(4,3)的随机矩阵 x1 = np.random.uniform(-1,1) # 指定区间均匀分布随机数没有指定数值类型时,numpy矩阵有默认数值类型:
x = np.array([1, 2, 3]) # dtype('int64') x = np.array([1.0, 2, 3]) dtype('float64')修改数值类型方法:
x = x.astype(float) x = x.astype(bool) x = np.array(x, dtype=float)一个矩阵的切片是对相同矩阵元素数据的不同观察角度,共享相同的数据,修改切片后矩阵会影响原矩阵。
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]) print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]"索引切片会降维,但是列表索引或范围索引不会降维:
overlap_0_7 = np.array([[0.7, 0.5, 0.5, 0.7, 0.5, 0.7, 0.7, 0.7], [0.7, 0.5, 0.5, 0.7, 0.5, 0.7, 0.7, 0.7], [0.7, 0.5, 0.5, 0.7, 0.5, 0.7, 0.7, 0.7]]) overlap_0_5 = np.array([[0.7, 0.5, 0.5, 0.7, 0.5, 0.5, 0.5, 0.5], [0.5, 0.25, 0.25, 0.5, 0.25, 0.5, 0.5, 0.5], [0.5, 0.25, 0.25, 0.5, 0.25, 0.5, 0.5, 0.5]]) min_overlaps = np.stack([overlap_0_7, overlap_0_5], axis=0) # [2, 3, 8] print(min_overlaps, min_overlaps.shape) print(len(min_overlaps)) current_classes = [0] min_overlaps = min_overlaps[:, :, current_classes] # [2, 3, 1] print(min_overlaps, min_overlaps.shape)求解指定维度上最小或最大值,返回值直接就是得到的最小最大值,会进行降维。
x = np.random.randint(0, 10, (3, 8)) print(x, x.shape) y = np.max(x, 1) print(y)结果:
[[3 0 3 9 6 9 9 6] [8 0 3 1 4 7 6 8] [5 7 2 8 4 0 5 8]] (3, 8) [9 8 8]https://stackoverflow.com/questions/39549331/reshape-numpy-n-vector-to-n-1-vector?rq=1