Python中的 numpy.dot()
numpy.dot(vector_a, vector_b, out = None) 返回向量 a 和 b 的点积。它可以处理二维数组,但将它们视为矩阵并将执行矩阵乘法。对于 N 维,它是 a 的最后一个轴和 b 的倒数第二个轴的和积:
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
参数
- vector_a : [array_like] 如果 a 是复数,则其复共轭用于计算点积。
- vector_b : [array_like] 如果 b 是复数,则其复共轭用于计算点积。
- out : [array, optional] 输出参数必须是 C 连续的,并且它的 dtype 必须是为 dot(a,b) 返回的 dtype。
返回:
向量 a 和 b 的点积。如果vector_a 和vector_b 是一维的,则返回标量
代码 1:
Python
# Python Program illustrating
# numpy.dot() method
import numpy as geek
# Scalars
product = geek.dot(5, 4)
print("Dot Product of scalar values : ", product)
# 1D array
vector_a = 2 + 3j
vector_b = 4 + 5j
product = geek.dot(vector_a, vector_b)
print("Dot Product : ", product)
Python
# Python Program illustrating
# numpy.dot() method
import numpy as geek
# 1D array
vector_a = geek.array([[1, 4], [5, 6]])
vector_b = geek.array([[2, 4], [5, 2]])
product = geek.dot(vector_a, vector_b)
print("Dot Product : \n", product)
product = geek.dot(vector_b, vector_a)
print("\nDot Product : \n", product)
"""
Code 2 : as normal matrix multiplication
"""
输出:
Dot Product of scalar values : 20
Dot Product : (-7+22j)
How Code1 works ?
vector_a = 2 + 3j
vector_b = 4 + 5j
now dot product
= 2(4 + 5j) + 3j(4 – 5j)
= 8 + 10j + 12j – 15
= -7 + 22j
代码 2:
Python
# Python Program illustrating
# numpy.dot() method
import numpy as geek
# 1D array
vector_a = geek.array([[1, 4], [5, 6]])
vector_b = geek.array([[2, 4], [5, 2]])
product = geek.dot(vector_a, vector_b)
print("Dot Product : \n", product)
product = geek.dot(vector_b, vector_a)
print("\nDot Product : \n", product)
"""
Code 2 : as normal matrix multiplication
"""
输出:
Dot Product :
[[22 12]
[40 32]]
Dot Product :
[[22 32]
[15 32]]
参考: https://numpy.org/doc/stable/reference/generated/numpy.dot.html