【问题标题】:numpy dot on 1D and 2D array一维和二维数组上的 numpy 点
【发布时间】:2019-09-03 09:26:52
【问题描述】:

我试图了解以下 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 是 N 维数组且 b 是一维数组,则它是 a 和 b 的最后一个轴上的和积。

我还不够数学家,无法完全理解这告诉我什么;或者为什么有时输出的顺序会互换。

【问题讨论】:

  • a set 是一种无序数据类型。你的意思是创建一个元组吗?还是将其保留为np.arraydot 的结果不是迭代器...)而不是将其放入不同的数据类型?
  • 当然!谢谢
  • 那么文档中的“a 和 b 的最后一个轴”是什么意思?
  • 谢谢!如果您想要功劳,请随时添加答案;否则我就做。

标签: python arrays numpy dot-product


【解决方案1】:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多