First Example
import numpy as np
a = np.random.randn(5)
print(a)
print(a.shape)
result:
[ 1.18961988 0.05722465 1.83658954 -0.6092621 -1.32062653]
(5,)
The array of a have five gaussian random number variables and the shape of array a is (5,). This is called One-dimensional array in python instead of row vector or column vector
if i print transpose of a. you will find a is the same as a.T in the end.
print(a.T)
print(a.T.shape)
result:
[ 1.18961988 0.05722465 1.83658954 -0.6092621 -1.32062653]
(5,)
if you use np.dot(a, a.T), what will you get? let's see.
np.dot(a, a.T)
result:
2.5442768021740205
as you can see, they are all one-dimensional array which shape like (n,) and the result of np.dot() is a number instead of a array
有时候我们确实会遇到shape为(n,)如:(5,)这样子的一维数组,这时候千万不要使用数组转置等操作。
但是我们可以将shape为(n,)的一维数组转换成shape 为 (n,1)的数组,通过以下的代码:
a.shape = (50,)
b.shape = (50,1)
a[:,np.newaxis].shape = (50,1)
np.ravel(b[:,0]) //返回的就是shape = (50,)的数组
由于我们刚刚用的是:
a = np.random.randn(5)
所以a.shape = (5,)
如果用:
a = np.random.randn(5,1)
a.shape = (5,1)
所以在初始化np数组时需要注意。
行向量和列向量:
我们一般把第一个参数当作行,第二个参数当成列。例如:
shape = (5,1) 我们会说这是一个5行1列的向量。
数值为1的位置叫做X向量。例如上面。为列向量
shape = (1,5) 为行向量。在平时使用中,尽量不要使用一维数组。