Numpy 和 Ndarray 的外积 [英] Outer product with Numpy and Ndarray

查看:57
本文介绍了Numpy 和 Ndarray 的外积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个代码中,我使用 numpy 进行矩阵计算.

In one of my codes, I use numpy for matrices calculations.

有一次,我必须在两个向量之间做外积才能得到一个矩阵.这就是我被困的地方.起初,我尝试了 numpy.dot 或其他矩阵产品,但是当参数都是 1D 时,它只做标量产品,这不是我想要的.然后我发现 numpy.outer 完全符合我的要求:一列 * 一行.

At one point, I have to do the outer product between 2 vectors to get a matrix. That's where I'm stuck. At first, I tried numpy.dot, or other matrix product, but when the arguments are both 1D, it only does the scalar product, which not what I want. Then I found that numpy.outer does exactly what I want : a column * a line.

问题是,我的向量不是数组.由于它们是 numpy.dot 操作的结果,因此它们是 ndarray 对象.但是 ndarrays 没有外部方法.我已经尝试了在 Internet 上找到的所有方法将我的 ndarrays 转换为简单数组.但是没有任何效果,我仍然一次又一次地出现ndarray和相同的属性错误.

The thing is, my vectors are not arrays. Since they result from a numpy.dot operation, they are ndarray objects. But ndarrays do not have an outer method. I have tried everything I found on the Internet to convert my ndarrays to simple arrays. But nothing works, I still have a ndarray and the same attribute error again and again.

现在我不知道该尝试什么,所以我想在我做一些暗示克隆数组中的值的令人讨厌的事情之前检查您是否知道另一种方法来执行此外积.

Now I don't know what to try, so I wanted to check if you knew another way to do this outer product, before I do some nasty things implying cloning the values in a array.

非常感谢您的帮助.

推荐答案

outer 不是任何类的方法,它只是在 numpy 模块.

outer is not a method of any class, it is just a plain old function found in the numpy module.

这是一个如何使用它的例子:

Here is an example of how to use it:

import numpy
x = numpy.array([1, 2, 3])
y = numpy.array([4, 5, 6])
# x.__class__ and y.__class__ are both 'numpy.ndarray'

outer_product = numpy.outer(x, y)
# outer_product has the value:
# array([[ 4,  5,  6],
#        [ 8, 10, 12],
#        [12, 15, 18]])

这篇关于Numpy 和 Ndarray 的外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆