np.dot()函数的用法详解

yipeiwu_com6年前Python基础

基本简介

dot函数为numpy库下的一个函数,主要用于矩阵的乘法运算,其中包括:向量内积、多维矩阵乘法和矩阵与向量的乘法。

1. 向量内积

向量其实是一维的矩阵,两个向量进行内积运算时,需要保证两个向量包含的元素个数是相同的。

例1:

import numpy as np

x = np.array([1, 2, 3, 4, 5, 6, 7])
y = np.array([2, 3, 4, 5, 6, 7, 8])
result = np.dot(x, y)
print(result)

输出结果:

168

计算过程就是将向量中对应元素相乘,再相加所得。即普通的向量乘法运算。

2. 矩阵乘法运算

两个矩阵(x, y)如果可以进行乘法运算,需要满足以下条件:
x为 m×n 阶矩阵,y为 n×p 阶矩阵,
则相乘的结果 result 为 m×p 阶矩阵。

例2:

import numpy as np

x = np.array([[1, 2, 3],
   [3, 4, 4]])
y = np.array([[0, 1, 1, 1],
   [1, 2, 0, 1],
   [0, 0, 2, 1]])
result = np.dot(x, y)

print(result)
print("x阶数:" + str(x.shape))
print("y阶数:" + str(y.shape))
print("result阶数:" + str(result.shape))

结果为:

[[ 2  5  7  6]
 [ 4 11 11 11]]
x阶数:(2, 3)
y阶数:(3, 4)
result阶数:(2, 4)

dot(x, y)不等于dot(y, x),矩阵乘法不满足交换律

例3:

import numpy as np

x = np.array([[1, 2],
   [3, 4]])
y = np.array([[2, 2],
   [1, 2]])
result1 = np.dot(x, y)
result2 = np.dot(y, x)

print("result1 = " + str(result1))
print("result2 = " + str(result2))

结果为:

result1 = [[ 4  6]
           [10 14]]
result2 = [[ 8 12]
           [ 7 10]]

如果不满足运算前提,都不可以运算。例2的dot(y,x)不满足运算条件,因此运算会报错。

例4:

import numpy as np

x = np.array([[1, 2, 3],
   [3, 4, 4]])
y = np.array([[0, 1, 1, 1],
   [1, 2, 0, 1],
   [0, 0, 2, 1]])
result = np.dot(y, x)

print(result)

结果为:

Traceback (most recent call last):
  File "numpy1.py", line 96, in <module>
    result = np.dot(y,x)
  File "<__array_function__ internals>", line 6, in dot
ValueError: shapes (3,4) and (2,3) not aligned: 4 (dim 1) != 2 (dim 0)

3. 矩阵与向量乘法

矩阵x为m×n阶,向量y为n阶向量,则矩阵x和向量y可以进行乘法运算,结果为m阶向量。进行运算时,会首先将后面一项进行自动转置操作,之后再进行乘法运算。

例5:

import numpy as np

x = np.array([[1, 2, 3],
   [3, 4, 4]])
y = np.array([1, 2, 3])
result = np.dot(x, y)

print(result)
print("x阶数:" + str(x.shape))
print("y阶数:" + str(y.shape))
print("result阶数:" + str(result.shape))

结果为:

[14 23]
x阶数:(2, 3)
y阶数:(3,)
result阶数:(2,)

例6:仍然不满足交换律

import numpy as np

x = np.array([[1, 2, 3],
   [3, 4, 4],
   [0, 1, 1]])
y = np.array([1, 2, 3])
result1 = np.dot(x, y) # 1×1 + 2×2 + 3×3 = 14(result1的第一个元素)
result2 = np.dot(y, x) # 1×1 + 2×3 + 3×0 = 7 (result2的第一个元素)

print("result1 = " + str(result1))
print("result2 = " + str(result2))

结果为:

result1 = [14 23  5]
result2 = [ 7 13 14]

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

相关文章

使用Rasterio读取栅格数据的实例讲解

Rasterio简介 有没有觉得用GDAL的Python绑定书写的代码很不Pythonic,强迫症的你可能有些忍受不了。不过,没关系,MapBox旗下的开源库Rasterio帮我们解决了...

Pandas 缺失数据处理的实现

数据丢失(缺失)在现实生活中总是一个问题。 机器学习和数据挖掘等领域由于数据缺失导致的数据质量差,在模型预测的准确性上面临着严重的问题。 在这些领域,缺失值处理是使模型更加准确和有效的重...

python 分离文件名和路径以及分离文件名和后缀的方法

分离路径和文件名: os.path.split() 区分文件的名字和后缀: os.path.splitext() import os file_path = "D:/test/t...

python pandas 组内排序、单组排序、标号的实例

python pandas 组内排序、单组排序、标号的实例

摘要:本文主要是讲解一下,如何进行排序。分为两种情况,不分组进行排序和组内进行排序。什么意思呢?具体来说,我举个栗子。 ****注意**** 如果只是单纯想对某一列进行排序,而不进行打序...

Python实现的一个自动售饮料程序代码分享

写这个程序的时候,我已学习Python将近有一百个小时,在CSDN上看到有人求助使用Python如何写一个自动售饮料的程序,我一想,试试写一个实用的售货程序。当然,只是实现基本功能,欢迎...