python - numpy.dot - 确保矩阵兼容性?

标签 python arrays numpy matrix

我有一个二维数组 X .

X[i]是一个具有 3 个值的一维数组。 其形状为:(3L,)

然后我有一个 3D 数组 g ,即 2x3x2。 如果我打印出 g[j] 的形状,它是:(3L,2L)g[j][i] 的形状是 (2L,)

现在我正在运行这样的循环:

for j in range(len(g)):
            for i in range(no_samples):
            e = math.exp(1. + np.dot(X[i], g[j][i]) - np.dot(X[i],g[i_class][i]))

但我收到以下错误:

  e = math.exp(1. + np.dot(X[i], g[j][i]) - np.dot(X[i],g[i_class][i]))
ValueError: matrices are not aligned

我想我明白这个问题,但不知道如何解决它。我尝试转置g[j][i]但这没有什么区别。我尝试 reshape X[i]强制其为 (3L,1L) 。我想如果X[i]是 3x1 和 g[j][i]是 1x2,那么矩阵是兼容的,我应该能够使用 np.dot 。但我想我一定错过了一些东西。

正确的做法是什么?

最佳答案

问题在于两个数组都只是一维且大小不等。此问题有两种解决方案:

让我们从这里开始:

>>> x
array([3, 4, 5])
>>> x.shape
(3,)             #Same shape as your array, but note that it is only 1D
>>> g
array([2, 3])

方式 1 - reshape :

>>> np.dot(x.reshape(3,1), g.reshape(1,2))
array([[ 6,  9],
       [ 8, 12],
       [10, 15]])

方式2-np.outer:

>>> np.outer(x,g)
array([[ 6,  9],
       [ 8, 12],
       [10, 15]])

当访问 numpy 数组而不是 g[i_class][i] 时,请使用 g[i_class,i]。此外,一维数组的转置不会改变数组。

最后,如果您按如下所示运行脚本,您将收到额外的错误。 math.exp 不将 numpy 数组作为输入。要避免这种情况,您需要使用 np.exp 或将元素求和以返回单个标量。

关于python - numpy.dot - 确保矩阵兼容性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23461312/

相关文章:

python - 如何在 python 中创建自己的数据类型以便覆盖算术运算符?

shell - 在 Python 的 IDLE 中扩展 shell 的宽度

python - 在 python 中,如何使用 __str__ 逐行返回列表中的元素

python - 将字符串中的字节发送到 Redis,以便将其用作 Celery 任务的参数

使用多维数组的 JavaScript 多级排序

c++ - 如果我删除指向节点的指针数组,节点本身会被删除吗?

python numpy roll带填充

python - 使用 OpenCV 计算蚕卵

python - 正则表达式删除字符串中重复的字符模式

ios - 转换到 UIImage 的 PFFile 数组在 for 循环之外为空