Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

python - Outer product with Numpy and Ndarray

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

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.

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.

Thank you very much for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...