1.数组转置和轴对换:数组不仅有transpose方法,还有一个特殊的T属性:
arr = np.arange(15).reshape(3,5)
arr
输出:
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
arr.T
输出:
array([[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]])
2.进行矩阵计算时,经常需要用到该操作,比如利用 np.dot计算矩阵内积XTX:
arr = np.random.randn(6,3)
arr
输出:
array([[-0.83790345, -1.13304154, -0.42567014], [ 0.75742538, 1.24634357, -1.00116761], [ 0.54168995, -0.83717253, -1.11580943], [-0.13315165, 0.0331654 , 0.70605975], [-2.57536154, -0.68951735, 1.16959181], [-1.26193272, -1.24703158, 0.3183666 ]])
np.dot(arr.T,arr)
输出:
array([[ 9.81189403, 4.78491411, -4.51395404], [ 4.78491411, 5.56963513, -1.01142215], [-4.51395404, -1.01142215, 4.39638499]])
3.对于高维数组, transpose需要得到一个由轴编号组成的元组才能对这些轴进行转至(比较难理解):
arr = np.arange(16).reshape((2,2,4))
arr
输出:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
arr.transpose((1,0,2))
输出:
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[ 4, 5, 6, 7],
[12, 13, 14, 15]]])
提示:transpose(1,0,2)把原来的shape由(2,2,4)变成了(2,2,4),就是第一个轴和第二个轴上面的元素互换。
比如原来位置(0,1,0)上的元素为4,现在把它放到了(1,0,0)这个位置,就是下面那个位置由8变成了4,标出了红色。
4.ndarray还有一个 swapaxes方法,它接受一对轴变换:
arr
输出:
array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [12, 13, 14, 15]]])
arr.swapaxes(1,2)
输出:
array([[[ 0, 4], [ 1, 5], [ 2, 6], [ 3, 7]], [[ 8, 12], [ 9, 13], [10, 14], [11, 15]]])
5.通用函数sqrt、exp、maximum:
arr = np.arange(10)
arr
输出:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.sqrt(arr)
输出:
array([ 0. , 1. , 1.41421356, 1.73205081, 2. , 2.23606798, 2.44948974, 2.64575131, 2.82842712, 3. ])
np.exp(arr)
输出:
array([ 1.00000000e+00, 2.71828183e+00, 7.38905610e+00, 2.00855369e+01, 5.45981500e+01, 1.48413159e+02, 4.03428793e+02, 1.09663316e+03, 2.98095799e+03, 8.10308393e+03])
x = np.random.randn(8)
x
输出:
array([-0.24726724, 0.69709717, 0.9658356 , 1.89019088, -0.28912795, -0.09235779, 0.37690775, 0.9102138 ])
y = np.random.randn(8)
y
输出:
array([-0.05048326, -0.02207697, -0.59940773, -1.32029941, 0.30894105, -0.05807405, -1.5019804 , 0.12918562])
np.maximum(x,y) #元素级最大值
输出:
array([-0.05048326, 0.69709717, 0.9658356 , 1.89019088, 0.30894105, -0.05807405, 0.37690775, 0.9102138 ])
arr = np.random.randn(7)*5
arr
输出:
array([ -1.53462646, 6.15168006, 4.32588912, -0.05408803, -2.98953481, -10.83013834, 1.13673478])
np.modf(arr)
输出:
(array([-0.53462646, 0.15168006, 0.32588912, -0.05408803, -0.98953481, -0.83013834, 0.13673478]), array([ -1., 6., 4., -0., -2., -10., 1.]))