[英]Why does numpy Dot product of 2d array with 1d array produce 1d array?
[英]numpy dot on 1D and 2D array
我試圖了解以下 python 代碼中發生的情況:
import numpy as np
numberList1 = [1,2,3]
numberList2 = [[4,5,6],[7,8,9]]
result = np.dot(numberList2, numberList1)
# Converting iterator to set
resultSet = set(result)
print(resultSet)
輸出:
{32, 50}
我可以看到,它在每個元素乘以numberList1
在內的每個陣列中的相同位置時,由元件numberList2
-所以{1*4 + 2*5 + 3*6 = 32},{1*7+2*8+3*9 = 50}
。
但是,如果我將數組更改為:
numberList1 = [1,1,1]
numberList2 = [[2,2,2],[3,3,3]]
然后我看到的輸出是
{9, 6}
這是錯誤的方法...
並且,如果我將其更改為:
numberList1 = [1,1,1]
numberList2 = [[2,2,2],[2,2,2]]
然后我看到的輸出就是
{6}
從文檔:
如果 a 是 ND 數組而 b 是一維數組,則它是 a 和 b 的最后一個軸上的和積。
我不是數學家,無法完全理解這告訴我什么; 或者為什么輸出的順序有時會交換。
set
是一種無序的數據類型 - 它將刪除您的重復項。 np.dot
不返回迭代器(如您的代碼中所述)而是一個np.ndarray
,它將按照您期望的順序返回:
import numpy as np
numberList1 = [1, 2, 3]
numberList2 = [[4, 5, 6], [7, 8, 9]]
result = np.dot(numberList2, numberList1)
# [32 50]
# <class 'numpy.ndarray'>
# numberList1 = [1, 1, 1]
# numberList2 = [[2, 2, 2], [3, 3, 3]]
# -> [6 9]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.