天辰安卓版APP下载numpy的轴(axis)与维度(shape)问题

对numpy维度有时不是太清楚,经常搞错,天辰安卓版APP下载写几个例子看一遍就懂了

import numpy as np
a = np.arange(6).reshape([3,2])
print(a)
[[0 1]
 [2 3]
 [4 5]]

print(a.shape)
(3, 2)
(n,)数组与(n,1)数组的互转

reshape进行维度的转换

a = np.array([1,2,3])
print(a.shape)
(3,)

b = a.reshape(-1,1)
print(b.shape)
(3, 1)

把shape中为1的维度去掉

a = np.array([[1],[2],[3]])
print(a.shape)
(3, 1)

b = np.squeeze(a)
print(b.shape)
(3,)

添加新维度

a = np.array([1,2,3])
b = a[np.newaxis,:]
print(b)
[[1 2 3]]
print(b.shape)
(1, 3)

c = a[:,np.newaxis]
print(c)
[[1]
 [2]
 [3]]
print(c.shape)
(3, 1)
矩阵乘法

(n,)数组求内积

a = np.array([1,2,3])
print(a.dot(a))
14

(n,1)数组求内积天辰安卓版APP下载

a = np.array([[1],[2],[3]])
print(a.dot(a))

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-be6ff70f8c84> in <module>()
      1 a = np.array([[1],[2],[3]])
----> 2 print(a.dot(a))

ValueError: shapes (3,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0)
numpy的转置
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
       [2, 3]])
>>> np.transpose(x)
array([[0, 2],
       [1, 3]])

>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)
numpy数组展平
a = np.arange(24).reshape(2,3,4)
print(a.shape)
(2, 3, 4)
print(a.flatten().shape)
(24,)
print(a.flatten())
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
np.sum的axis
a = np.array([[1,2,3],[4,5,6]])

# 对所有数字求和
print(np.sum(a))
21

# 对列求和
print(np.sum(a,axis=0))
[5 7 9]

# 对行求和
print(np.sum(a,axis=1))
[ 6 15]

# 对最后一个维度求和
print(np.sum(a,axis=-1))
[ 6 15]
np.sum的keepdims
a = np.array([[1,2,3],[4,5,6]])
print(np.sum(a,axis=1))
[ 6 15]
print(np.sum(a,axis=1,keepdims=True))
[[ 6]
 [15]]
>>> x=np.array([[1001, 1002], [3, 4]])
>>> x -= np.max(x)
>>> x
array([[  -1,    0],
       [-999, -998]])


>>> x=np.array([[1001, 1002], [3, 4]])
>>> x -= np.max(x, axis=1)
>>> x
array([[  -1,  998],
       [-999,    0]])


>>> import numpy as np
>>> x=np.array([[1001, 1002], [3, 4]])
>>> x -= np.max(x, axis=1, keepdims=True)
>>> x
array([[-1,  0],
       [-1,  0]])

上一篇:获取Tensor的维度(tf.shape(x)、x.shape和x.get_shape()的
下一篇:天辰安卓版APP下载晨间日记多几个维度去思考,继

网友回应

欢迎扫描关注我们的微信公众平台!

欢迎扫描关注我们的微信公众平台!