## np.dot()函数用法

Numpy中dot()函数主要功能有两个：向量点积和矩阵乘法

### 一、向量点积

``````import numpy as np
x=np.array([0,1,2,3,4])#等价于:x=np.arange(0,5)
y=x[::-1]
print x
print y
print np.dot(x,y)

``````

``````[0 1 2 3 4]
[4 3 2 1 0]
10``````

``````import numpy as np
x=np.arange(0,5)
y=np.random.randint(0,10,5)
print x
print y
print np.dot(x,y)``````

``````[0 1 2 3 4]
[5 1 0 9 2]
36``````

### 二、矩阵乘法

1.np.dot(x, y), 当x为二维矩阵，y为一维向量，这时y会转换一维矩阵进行计算

``````import numpy as np
x=np.arange(0,5)
y=np.random.randint(0,10,size=(5,1))
print x
print y
print "x.shape:"+str(x.shape)
print "y.shape"+str(y.shape)
print np.dot(x,y)
``````

``````[0 1 2 3 4]
[[3]
[7]
[2]
[8]
[1]]
x.shape:(5,)
y.shape(5, 1)
[39]``````

2.np.dot(x, y)中，x、y都是二维矩阵，进行矩阵积计算

``````import numpy as np
x=np.arange(0,6).reshape(2,3)
y=np.random.randint(0,10,size=(3,2))
print x
print y
print "x.shape:"+str(x.shape)
print "y.shape"+str(y.shape)
print np.dot(x,y)``````

``````[[0 1 2]
[3 4 5]]
[[7 5]
[0 7]
[6 2]]
x.shape:(2, 3)
y.shape(3, 2)
[[12 11]
[51 53]]``````

0条评论