[Numpy-discussion] add axis to results of reduction (mean, min, ...)
josef.pktd@gmai...
josef.pktd@gmai...
Thu Aug 6 12:18:52 CDT 2009
On Thu, Aug 6, 2009 at 1:07 PM, Keith Goodman<kwgoodman@gmail.com> wrote:
> On Thu, Aug 6, 2009 at 9:58 AM, Charles R
> Harris<charlesr.harris@gmail.com> wrote:
>>
>>
>> On Thu, Aug 6, 2009 at 9:55 AM, <josef.pktd@gmail.com> wrote:
>>>
>>> What's the best way of getting back the correct shape to be able to
>>> broadcast, mean, min,.. to the original array, that works for
>>> arbitrary dimension and axis?
>>>
>>> I thought I have seen some helper functions, but I don't find them
>>> anymore?
>>
>> Adding a keyword to retain the number of dimensions has been mooted. It
>> shouldn't be too difficult to implement and would allow things like:
>>
>>>>> scaled = a/a.max(1, reduce=0)
>>
>> I could do that for 1.4 if folks are interested.
>
> I'd use that. It's better than what I usually do:
>
> scaled = a / a.max(1).reshape(-1,1)
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
added feature to numpy reduce function would be nice.
but helper function is still useful for our own reduce operations
something like this function with an awful name
Josef
import numpy as np
def addreducedaxis(x,axis=None):
'''adds axis so that results of reduce operation broadcast to original
array
Parameter
---------
x : array n-dim
array that is the result of reduce operation, e.g. mean, min
axis : int
axis that was removed in the reduce operation
Return
------
y : array (n+1)dim
array with additional axis
'''
if axis != 0 and not axis is None:
ind = [slice(None)] * (x.ndim+1)
ind[axis] = np.newaxis
return x[ind]
else:
return x
a = np.array([[1,2,3,3,0],[2,2,3,2,1]])
a3 = np.dstack((a,a))
print np.all((a3-a3.mean(1)[:,None,:]) == (a3 - addreducedaxis(a3.mean(1),1)))
print np.all((a3-a3.mean(-2)[:,None,:]) == (a3 -
addreducedaxis(a3.mean(-2),-2)))
print np.all((a3-a3.mean()) == (a3 - addreducedaxis(a3.mean())))
print np.all((a3.ravel()-a3.mean(None)) == (a3.ravel() -
addreducedaxis(a3.mean(None),None)))
print np.all((a3-a3.mean(None)) == (a3 - addreducedaxis(a3.mean(None),None)))
#example usage
from numpy.testing import assert_almost_equal
for axis in [None,0,1,2]:
m = a3.mean(axis)
v = ((a3 - addreducedaxis(m,axis))**2).mean(axis)
assert_almost_equal(v, np.var(a3,axis),15)
#normalize array along one axis
a3n = (a3 - addreducedaxis(np.mean(a3,1),1))/np.sqrt(addreducedaxis(np.var(a3,1),1))
print a3n.mean(1)
print a3n.var(1)
More information about the NumPy-Discussion
mailing list