文章目录
生成数据类
numpy.random
numpy.random.randn 生成服从标准正态分布的样本
numpy.random.rand 生成位于[0,1)之间的随机样本
输入参数: n , (m,n)
返回一个List
import numpy as np
arr1 = np.random.randn(2,4)
print(arr1)
arr2 = np.random.rand(2,4)
print(arr2)
##---------------------
[[-1.03021018 0.5197033 0.52117459 -0.70102661]
[ 0.98268569 1.21940697 -1.095241 -0.38161758]]
******************************************************************
[[ 0.19947349 0.05282713 0.56704222 0.45479972]
[ 0.28827103 0.1643551 0.30486786 0.56386943]]
numpy.zeros(shape, dtype=float, order='C)
返回来一个给定形状和类型的用0填充的数组
shape: 5 、 (3,4)
dtype:c浮点负数,i整数,f浮点数
order: 可选参数,c表示与C语言类似行优先,F代表列优先
np.zeros((5,), dtype=np.int)
array([0, 0, 0, 0, 0])
s = (2,2)
np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
数据合并 vstack / hstack
import numpy as np
a = np.array([1, 2, 3]) # 1*3
b = np.array([4, 5, 6]) # 1*3
print(np.vstack((a, b))) # vertical stack 上下合并 2*3
print(np.hstack((a, b))) # horizontal stack 左右合并 1*6
运算类
np.dot(A, B) 矩阵乘法
矩阵乘法运算
输入:A/B同为一维矩阵(List), 计算AB內积,返回一个数
A/B 为多维矩阵时,同线性代数中矩阵乘法运算, 返回一个矩阵
## 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))
# 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))
##------------------------------------
one_result_res: 32
two_multi_res: [[22 28]
[49 64]]
np.multiply(A,B)
相同位置的对应元素相乘
输入两个形状相同的numpy.array
输出为相同形状的numpy.array
另一种方法直接用* 符号
# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
another_two_dim_matrix_one = np.array([[7, 8, 9], [4, 7, 1]])
# 对应元素相乘 element-wise product
element_wise = two_dim_matrix_one * another_two_dim_matrix_one
print('element wise product: %s' %(element_wise))
element_wise_2 = np.multiply(two_dim_matrix_one, another_two_dim_matrix_one)
print('element wise product: %s' % (element_wise_2))
##----------------------
element wise product: [[ 7 16 27]
[16 35 6]]
element wise product: [[ 7 16 27]
[16 35 6]]