分享

numpy中的几种矩阵乘法

 LibraryPKU 2020-05-23

Python中的几种矩阵乘法

1. 同线性代数中矩阵乘法的定义: np.dot()

np.dot(A, B):对于二维矩阵,计算真正意义上的矩阵乘积,同线性代数中矩阵乘法的定义。对于一维矩阵,计算两者的内积。见如下Python代码:

  1. import numpy as np
  2. # 2-D array: 2 x 3
  3. two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
  4. # 2-D array: 3 x 2
  5. two_dim_matrix_two = np.array([[1, 2], [3, 4], [5, 6]])
  6. two_multi_res = np.dot(two_dim_matrix_one, two_dim_matrix_two)
  7. print('two_multi_res: %s' %(two_multi_res))
  8. # 1-D array
  9. one_dim_vec_one = np.array([1, 2, 3])
  10. one_dim_vec_two = np.array([4, 5, 6])
  11. one_result_res = np.dot(one_dim_vec_one, one_dim_vec_two)
  12. print('one_result_res: %s' %(one_result_res))

结果如下:

  1. two_multi_res: [[22 28]
  2. [49 64]]
  3. one_result_res: 32

2. 对应元素相乘 element-wise product: np.multiply(), 或 *

在Python中,实现对应元素相乘,有2种方式,一个是np.multiply(),另外一个是*。见如下Python代码:

  1. import numpy as np
  2. # 2-D array: 2 x 3
  3. two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
  4. another_two_dim_matrix_one = np.array([[7, 8, 9], [4, 7, 1]])
  5. # 对应元素相乘 element-wise product
  6. element_wise = two_dim_matrix_one * another_two_dim_matrix_one
  7. print('element wise product: %s' %(element_wise))
  8. # 对应元素相乘 element-wise product
  9. element_wise_2 = np.multiply(two_dim_matrix_one, another_two_dim_matrix_one)
  10. print('element wise product: %s' % (element_wise_2))

结果如下:

  1. element wise product: [[ 7 16 27]
  2. [16 35 6]]
  3. element wise product: [[ 7 16 27]
  4. [16 35 6]]

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多