【python】numpy使用心得

版权声明:本文为博主原创文章,转载请标明出处 https://blog.csdn.net/C2681595858/article/details/90523890

一、乘法

  • numpy.dot(x,y)就是正常的向量或者矩阵乘法
  • x*y:
    分情况讨论
    • 如果x和y是维度相同的行(列)向量或者矩阵,结果是对应位置的数相乘:
import numpy as np
a =np.array([1,2,3])
b = np.array([4,2,6])
print(a*b)
# 结果 array([ 4,  4, 18])

c = np.array([[1],[2],[3]])
d = np.array([[4],[2],[6]])
print(c*d)

# array([[ 4],
#       [ 4],
#       [18]])

>>> e
	       
array([[ 4,  8, 12],
       [ 2,  4,  6],
       [ 6, 12, 18]])
>>> f
	       
array([[2, 3, 4],
       [2, 4, 6],
       [6, 3, 7]])
>>> e*f
	       
array([[  8,  24,  48],
       [  4,  16,  36],
       [ 36,  36, 126]])
  • 如果x和y,一个是行向量,另一个是列向量,那么,将行或列进行复制,形成相同形状的矩阵后,在对应位置的元素相乘:
>>> a
array([1, 2, 3])
>>> d
array([[4],
      [2],
      [6]])
>>> a*d
array([[ 4,  8, 12],
      [ 2,  4,  6],
      [ 6, 12, 18]])
  • 如果x和y是维度不相同的矩阵则无法进行这种运算
>>> h
		   
array([[2, 3],
       [3, 5],
       [4, 6]])
>>> g
		   
array([[2, 3, 5],
       [3, 5, 6]])
>>> g*h
		   
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    g*h
ValueError: operands could not be broadcast together with shapes (2,3) (3,2) 
>>> h*g
		   
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    h*g
ValueError: operands could not be broadcast together with shapes (3,2) (2,3) 

  • 如果x和y一个是矩阵一个是向量,则将向量进行复制,形成与矩阵相同的大小,然后对应位置元素相乘。
>>> h
		   
array([[2, 3],
       [3, 5],
       [4, 6]])
>>> i
		   
array([[3],
       [6],
       [8]])
>>> h*i
		   
array([[ 6,  9],
       [18, 30],
       [32, 48]])
>>> i*h
		   
array([[ 6,  9],
       [18, 30],
       [32, 48]])
>>> h
		   
array([[2, 3],
       [3, 5],
       [4, 6]])
>>> g = np.array([3,4])
		   
>>> h*g
		   
array([[ 6, 12],
       [ 9, 20],
       [12, 24]])
>>> g*h
		   
array([[ 6, 12],
       [ 9, 20],
       [12, 24]])

二、转置

array.transpose()

array.T

首先需要说明的是,如果你的array是行向量。那么前两个转置方法是没有用的。如果是列向量或者矩阵,要转置成为行向量,那么前两个是有用的。示例如下:

>>> b
		   
array([4, 2, 6])
>>> b.T
		   
array([4, 2, 6])
>>> b.transpose()
		   
array([4, 2, 6])

>>> c
		   
array([[1],
       [2],
       [3]])
>>> c.T
		   
array([[1, 2, 3]])
>>> c.transpose()
		   
array([[1, 2, 3]])

>>> h
		   
array([[2, 3],
       [3, 5],
       [4, 6]])
>>> h.T
		   
array([[2, 3, 4],
       [3, 5, 6]])
>>> h.transpose()
		   
array([[2, 3, 4],
       [3, 5, 6]])
  • 不管是矩阵还是向量下面这个方法一定是有用的,但一般只用这个处理行向量的转置:

reshape()

其原型如下:

numpy.reshape(a, newshape, order='C')[source]# a:待reshape的数组
# newshape: 新数组的样式,(x,y), 表示x行,y列,如果y为-1,那么它会根据原数组中数据的数量,以及行x的数量,自动计算y的值。

使用示例:

import numpy as np
a = np.array([1,2,3]);
b = np.reshape(a,(3, -1));
print(b)
#结果:[[1]
# 		[2]
# 		[3]]

求逆

Q = np.array([[-0.6, -0.8],
			  [-0.8, 0.6]])
np.linalg.inv(Q)

猜你喜欢

转载自blog.csdn.net/C2681595858/article/details/90523890