NumPy.dot()与Python中’*’操作的区别

NumPy.dot()与Python中’*’操作的区别

在Python中,如果我们有两个numpy数组,通常被称为一个向量。’*’运算符和numpy.dot()对它们的作用是不同的。特别是当你处理数据科学或竞争性编程问题时,知道这一点很重要。

*操作

*操作在数组元素上进行元素间的乘法。a[i][j]处的元素与b[i][j]相乘,这发生在数组的所有元素上。
示例:

Let the two 2D array are v1 and v2:-
v1 = [[1, 2], [3, 4]]
v2 = [[1, 2], [3, 4]]

Output:
[[1, 4]
[9, 16]]
From below picture it would be clear.

NumPy.dot()与Python中'*'操作的区别

numpy.dot()

它进行正常的矩阵乘法。如果第一个数组的列数等于第二个数组的行数,那么只有numpy.dot()函数会被检查,否则会显示错误。
示例:

Let the two 2D array are v1 and v2:-
v1=[[1, 2], [3, 4]]
v2=[[1, 2], [3, 4]]
Than numpy.dot(v1, v2)  gives output of :-
[[ 7 10]
 [15 22]]

示例 1:

import numpy as np
 
 
# vector v1 of dimension (2, 2)
v1 = np.array([[1, 2], [1, 2]])
 
# vector v2 of dimension (2, 2)
v2 = np.array([[1, 2], [1, 2]])
 
print("vector multiplication")
print(np.dot(v1, v2))
 
print("\nElementwise multiplication of two vector")
print(v1 * v2)
**Output :**
vector multiplication
[[3 6]
 [3 6]]

Elementwise multiplication of two vector
[[1 4]
 [1 4]]

示例 2:

import numpy as np
 
 
v1 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
 
v2 = np.array([[[1, 2, 3], [1, 2, 3], [1, 2, 3]]])
 
print("vector multiplication")
print(np.dot(v1, v2))
 
print("\nElementwise multiplication of two vector")
print(v1 * v2)

输出 :

vector multiplication
[[ 6 12 18]
 [ 6 12 18]
 [ 6 12 18]]

Elementwise multiplication of two vector
[[1 4 9]
 [1 4 9]
 [1 4 9]]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Numpy教程