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

相关文章

将pandas.dataframe的数据写入到文件中的方法

将pandas.dataframe的数据写入到文件中的方法

导入实验常用的python包。如图2所示。 【import pandas as pd】pandas用来做数据处理。【import numpy as np】numpy用来做高维度矩阵运算....

详解python中eval函数的作用

eval() 函数用来执行一个字符串表达式,并返回表达式的值。 eval函数功能:将字符串str当成有效的表达式来求值并返回计算结果。eval函数可以实现list、dict、tuple与...

详解python字节码

Python对不可变序列进行重复拼接操作效率会很低,因为每次都会生成一个新的对象,解释器需要把原来对象中的元素先复制到新的对象里,然后再追加新的元素。 但是CPython对字符串操作进行...

python使用 request 发送表单数据操作示例

python使用 request 发送表单数据操作示例

本文实例讲述了python使用 request 发送表单数据操作。分享给大家供大家参考,具体如下: # !/usr/bin/env python # -*- coding: utf-...

Python中列表(list)操作方法汇总

本文实例汇总了Python中关于列表的常用操作方法,供大家参考借鉴。具体方法如下: 一、Python创建列表: sample_list = ['a',1,('a','b')]...