指数运算np.exp()
np.exp(x)会创建一个新的对象,
np.exp(x,x)会将结果赋给x不会创建新的对象
exp = np.array([3.0, 5.0])
# 会将指数运算e^3.0, e^5.0 的结果赋给exp,
exp = np.array([3.0, 5.0])
print 'exp', id(exp)
exp1 = np.exp(exp)
print 'exp1', id(exp1),exp1
np.exp(exp, exp)
print 'exp', id(exp), exp
倒数运算np.reciprocal(),用法同np.exp
矩阵升一维
np.expand_dims(rows, axis=0)等价与rows[np.newaxis,:],
np.newaxis也可以用None替代
rows = np.array([[0, 3, 5],[10, 13, 15]], dtype=np.intp)
print rows.shape
(2, 3)
axis0 = np.expand_dims(rows, axis=0)
print axis0
print axis0.shape
[[[ 0 3 5]
[10 13 15]]]
(1, 2, 3)
row = rows[np.newaxis,:]
print row,row.shape
print rows.shape
[[[ 0 3 5]
[10 13 15]]]
(1, 2, 3)
axis1 = np.expand_dims(rows, axis=1)
print axis1,axis1.shape
row = rows[:,np.newaxis,]
print row,row.shape
[[[ 0 3 5]]
[[10 13 15]]] (2, 1, 3)
[[[ 0 3 5]]
[[10 13 15]]] (2, 1, 3)
axis1 = np.expand_dims(rows, axis=2)
print axis1,axis1.shape
row = rows[:,:,np.newaxis,]
print row,row.shape
[[[ 0]
[ 3]
[ 5]]
[[10]
[13]
[15]]] (2, 3, 1)
[[[ 0]
[ 3]
[ 5]]
[[10]
[13]
[15]]] (2, 3, 1)
rows = np.array([1,2,3,4,5,6,7,8])
row = rows[:,np.newaxis]
print row
[[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]]
random
详见链接
矩阵转置
arr1 = np.array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
# 这是原来的矩阵。如果对其进行转置,执行
print arr1.shape
输出
(2, 2, 4)
shape(2,2,4),三维原有顺序(0,1,2)
(1,0,2)表示前两维转置,后一维维数不变,转换后矩阵shape(2,2,4),虽然形状没有变化,但是内容变了
A[x,y,z]---->B[y,x,z],就是A矩阵位置[x,y,z]元素转换到B矩阵中位置为[y,x,z],如:
A[0,0,0]--->B[0,0,0]
A[0,0,1]--->B[0,0,1]
...
A[0,0,3]--->B[0,0,3]
以上这些元素的位置不会变化
A[0,1,0]--->B[1,0,0]
A[0,1,1]--->B[1,0,1]
...
A[0,1,3]--->B[1,0,3]
以上这些元素的位置会变化
arr2 = arr1.transpose((1,0,2))
print arr2
[[[ 0 1 2 3]
[ 8 9 10 11]]
[[ 4 5 6 7]
[12 13 14 15]]]
第一维不变,后两维交换位置
(0,1,2)---->(0,2,1)
shape(2,2,4)---->shape(2,4,2)
这时候矩阵形状发生了变化
arr3 = arr1.transpose((0,2,1))
print arr3
[[[ 0 4]
[ 1 5]
[ 2 6]
[ 3 7]]
[[ 8 12]
[ 9 13]
[10 14]
[11 15]]]
arr4 = arr1.transpose((2,1,0))
print arr4
[[[ 0 8]
[ 4 12]]
[[ 1 9]
[ 5 13]]
[[ 2 10]
[ 6 14]]
[[ 3 11]
[ 7 15]]]
这个要是在实际应用中,使用什么方式转出自己想要的样子还需要多观察。
矩阵合并
z = np.array([1,2,3,4,5,6])
rand = np.random.rand(6,2)
print type(rand)
print z.shape
z = z[:, np.newaxis]
print np.hstack((rand, z))
矩阵正规化(单位模长为1)
from sklearn import preprocessing
X = [[ 1., -1., 2.],
[ 2., 0., 0.],
[ 0., 1., -1.]]
X = np.array(X)
X_normalized = preprocessing.normalize(X, norm='l2')
print X_normalized
print np.linalg.norm(X_normalized[0])
[[ 0.40824829 -0.40824829 0.81649658]
[ 1. 0. 0. ]
[ 0. 0.70710678 -0.70710678]]
1.0
矩阵行求和
变量.sum(axis=1)