Python中的几种矩阵乘法(小结)

yipeiwu_com6年前Python基础

一.  np.dot()

1.同线性代数中矩阵乘法的定义。np.dot(A, B)表示:

  • 对二维矩阵,计算真正意义上的矩阵乘积。
  • 对于一维矩阵,计算两者的内积。

2.代码

 【code】

import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
# 2-D array: 3 x 2
two_dim_matrix_two = np.array([[1, 2], [3, 4], [5, 6]])

two_multi_res = np.dot(two_dim_matrix_one, two_dim_matrix_two)
print('two_multi_res: %s' %(two_multi_res))

# 1-D array
one_dim_vec_one = np.array([1, 2, 3])
one_dim_vec_two = np.array([4, 5, 6])
one_result_res = np.dot(one_dim_vec_one, one_dim_vec_two)
print('one_result_res: %s' %(one_result_res))

 【result】

two_multi_res: [[22 28]
                [49 64]]
one_result_res: 32

二. np.multiply()或 *

1.在Python中,实现对应元素相乘(element-wise product),有2种方式,

  • 一个是np.multiply()
  • 另外一个是 *

2.代码

【code】

import numpy as np

# 2-D array: 2 x 3
two_dim_matrix_one = np.array([[1, 2, 3], [4, 5, 6]])
another_two_dim_matrix_one = np.array([[7, 8, 9], [4, 7, 1]])

# 对应元素相乘 element-wise product
element_wise = two_dim_matrix_one * another_two_dim_matrix_one
print('element wise product: %s' %(element_wise))

# 对应元素相乘 element-wise product
element_wise_2 = np.multiply(two_dim_matrix_one, another_two_dim_matrix_one)
print('element wise product: %s' % (element_wise_2))

【result】

element wise product: [[ 7 16 27]
                       [16 35  6]]
element wise product: [[ 7 16 27]
                       [16 35  6]]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python找出文件中使用率最高的汉字实例详解

本文实例讲述了Python找出文件中使用率最高的汉字的方法。分享给大家供大家参考。具体分析如下: 这是我初学Python时写的,为了简便,我并没在排序完后再去掉非中文字符,稍微会影响性能...

python执行CMD指令,并获取返回的方法

如下所示: result = os.popen('ps aux') res = result.read() for line in res.splitlines():...

介绍Python中的文档测试模块

如果你经常阅读Python的官方文档,可以看到很多文档都有示例代码。比如re模块就带了很多示例代码: >>> import re >>> m =...

Django 开发环境配置过程详解

Django 开发环境配置过程详解

开发环境 开发环境为: Win 10(64位) Python 3.7.0 Django 2.1 安装Python python的安装为比较简单,首先找到Python官...

让 python 命令行也可以自动补全

许多人都知道 iPython 有很好的自动补全能力,但是就未必知道 python 也同样可以 Tab 键补全, 您可以在启动 python 后,执行下 复制代码 代码如下: import...