Real inner-product in python
Robert Kern
kern at taliesen.caltech.edu
Wed Jan 22 19:38:02 EST 2003
In article <mailman.1043229043.27058.python-list at python.org>,
Nadav Horesh <NadavH at VisionSense.com> writes:
> Whats about:
>
> >>> c = N.reshape(N.arange(12), (3,2,2))
> >>> b = N.arange(3)
> >>> N.dot(b,c)
> Traceback (most recent call last):
> File "<pyshell#18>", line 1, in ?
> N.dot(b,c)
> File "/usr/local/lib/python2.3/site-packages/Numeric/Numeric.py", line
> 335, in dot
> return multiarray.matrixproduct(a, b)
> ValueError: matrices are not aligned
[snip]
> As I see inner product between two tensors --- A of rank $n$ and B of
> rank $m$ it should be like
> (in TeX style):
> $$
> C = A \cdot B
> $$
> requires:
>
> 1. The last dimension of A must be equal to the first dimension of B,
> and ...
> 2.
> $$
> C_{p_1, ... p_{m-1},q_2, ... q_n} = \sum_{i=1}^{q_1} A_{p_1, ...
> p_{m-1},i} B_{i, q_2, ... q_{n}}
> $$
>
> Thus, I don't see the *dot* function as a proper inner product.
You are correct. Here is dot's docstring:
"""dot(a,b) returns matrix-multiplication between a and b. The product-sum
is over the last dimension of a and the second-to-last dimension of b.
"""
Here is my implementation of a tensor-style inner product:
def _myDot(a, b):
"""Returns the inner product.
a_i...k * b_k...m = c_i...m in summation notation with the ...'s
representing arbitrary, omitted indices
The sum is over the last axis of the first argument and the first axis
of the last axis.
_myDot(a, b) --> NumPy array
"""
a = Numeric.asarray(a)
b = Numeric.asarray(b)
tempAxes = tuple(range(1, len(b.shape)) + [0])
newB = Numeric.transpose(b, tempAxes)
# innerproduct sums over the *last* axes of *both* arguments
return Numeric.innerproduct(a, newB)
> Nadav
--
Robert Kern
Ruddock House President
kern at caltech.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list