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

yipeiwu_com5年前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设计】。

相关文章

Python3 pip3 list 出现 DEPRECATION 警告的解决方法

需要在 ~/.pip/pip.conf 配置文件中加入下面的语句,避免这类警告: 没有目录或没有配置文件需要自己新建 mkdir ~/.pip/ cd ~/.pip touch pip....

python中使用 xlwt 操作excel的常见方法与问题

前言 Python可以操作Excel的模块不止一种,我习惯使用的写入模块是xlwt(一般都是读写模块分开的) python中使用xlwt操作excel非常方,和Java使用调框架apac...

解决python中用matplotlib画多幅图时出现图形部分重叠的问题

1.解决方法:使用函数 tight_layout() 2.具体使用方法 import matplotlib.pyplot as plt fig = plt.figure()...

Python3.x中自定义比较函数

在Python3.x的世界里,cmp函数没有了。那么sorted,min,max等需要比较函数作为参数的函数该如何用呢? 以min函数的定义为例,有两种重载形式: 单参数(一个迭代器):...

Python原始字符串与Unicode字符串操作符用法实例分析

Python原始字符串与Unicode字符串操作符用法实例分析

本文实例讲述了Python原始字符串与Unicode字符串操作符用法。分享给大家供大家参考,具体如下: #coding=utf8 ''''' 在原始字符串里,所有的字符串都是直接按照...