本文整理汇总了Python中numpy.add.reduce函数的典型用法代码示例。如果您正苦于以下问题:Python reduce函数的具体用法?Python reduce怎么用?Python reduce使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了reduce函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_reduceND
def test_reduceND(self):
from numpy import add, arange
a = arange(12).reshape(3, 4)
assert (add.reduce(a, 0) == [12, 15, 18, 21]).all()
assert (add.reduce(a, 1) == [6.0, 22.0, 38.0]).all()
raises(ValueError, add.reduce, a, 2)
示例2: test_reduce_keepdims
def test_reduce_keepdims(self):
from numpy import add, arange
a = arange(12).reshape(3, 4)
b = add.reduce(a, 0, keepdims=True)
assert b.shape == (1, 4)
assert (add.reduce(a, 0, keepdims=True) == [12, 15, 18, 21]).all()
assert (add.reduce(a, 0, None, None, True) == [12, 15, 18, 21]).all()
示例3: make_F_matrix
def make_F_matrix(E_matrix):
"""takes an E matrix and returns an F matrix
input is output of make_E_matrix
for each element in matrix subtract mean of corresponding row and
column and add the mean of all elements in the matrix
"""
num_rows, num_cols = shape(E_matrix)
#make a vector of the means for each row and column
#column_means = (add.reduce(E_matrix) / num_rows)
column_means = (add.reduce(E_matrix) / num_rows)[:,newaxis]
trans_matrix = transpose(E_matrix)
row_sums = add.reduce(trans_matrix)
row_means = row_sums / num_cols
#calculate the mean of the whole matrix
matrix_mean = sum(row_sums) / (num_rows * num_cols)
#adjust each element in the E matrix to make the F matrix
E_matrix -= row_means
E_matrix -= column_means
E_matrix += matrix_mean
#for i, row in enumerate(E_matrix):
# for j, val in enumerate(row):
# E_matrix[i,j] = E_matrix[i,j] - row_means[i] - \
# column_means[j] + matrix_mean
return E_matrix
示例4: _basic_simps
def _basic_simps(y,start,stop,x,dx,axis):
nd = len(y.shape)
if start is None:
start = 0
step = 2
all = (slice(None),)*nd
slice0 = tupleset(all, axis, slice(start, stop, step))
slice1 = tupleset(all, axis, slice(start+1, stop+1, step))
slice2 = tupleset(all, axis, slice(start+2, stop+2, step))
if x is None: # Even spaced Simpson's rule.
result = add.reduce(dx/3.0* (y[slice0]+4*y[slice1]+y[slice2]),
axis)
else:
# Account for possibly different spacings.
# Simpson's rule changes a bit.
h = diff(x,axis=axis)
sl0 = tupleset(all, axis, slice(start, stop, step))
sl1 = tupleset(all, axis, slice(start+1, stop+1, step))
h0 = h[sl0]
h1 = h[sl1]
hsum = h0 + h1
hprod = h0 * h1
h0divh1 = h0 / h1
result = add.reduce(hsum/6.0*(y[slice0]*(2-1.0/h0divh1) + \
y[slice1]*hsum*hsum/hprod + \
y[slice2]*(2-h0divh1)),axis)
return result
示例5: gaussian_convolution
def gaussian_convolution(data, ijk_linewidths):
from numpy import float32, zeros, add, divide, outer, reshape
if data.dtype.type != float32:
data = data.astype(float32)
from math import exp
gaussians = []
for a in range(3):
size = data.shape[a]
gaussian = zeros((size,), float32)
hw = ijk_linewidths[2-a] / 2.0
for i in range(size):
u = min(i,size-i) / hw
p = min(u*u/2, 100) # avoid OverflowError with exp()
gaussian[i] = exp(-p)
area = add.reduce(gaussian)
divide(gaussian, area, gaussian)
gaussians.append(gaussian)
g01 = outer(gaussians[0], gaussians[1])
g012 = outer(g01, gaussians[2])
g012 = reshape(g012, data.shape)
cdata = zeros(data.shape, float32)
from numpy.fft import fftn, ifftn
# TODO: Fourier transform Gaussian analytically to reduce computation time
# about 30% (one of three fft calculations).
ftg = fftn(g012)
ftd = fftn(data)
gd = ifftn(ftg * ftd)
gd = gd.astype(float32)
return gd
示例6: plane
def plane(self, matrix):
from numpy import ravel, minimum, maximum, add, multiply, array, float32
matrix_1d = matrix.ravel()
dmin = minimum.reduce(matrix_1d)
if self.min == None or dmin < self.min:
self.min = dmin
dmax = maximum.reduce(matrix_1d)
if self.max == None or dmax > self.max:
self.max = dmax
self.sum += add.reduce(matrix_1d)
# TODO: Don't copy array to get standard deviation.
# Avoid overflow when squaring integral types
m2 = array(matrix_1d, float32)
multiply(m2, m2, m2)
self.sum2 += add.reduce(m2)
示例7: test_reduce_errors
def test_reduce_errors(self):
from numpy import sin, add, maximum, zeros
raises(ValueError, sin.reduce, [1, 2, 3])
assert add.reduce(1) == 1
assert list(maximum.reduce(zeros((2, 0)), axis=0)) == []
exc = raises(ValueError, maximum.reduce, zeros((2, 0)), axis=None)
assert exc.value[0] == ("zero-size array to reduction operation " "maximum which has no identity")
exc = raises(ValueError, maximum.reduce, zeros((2, 0)), axis=1)
assert exc.value[0] == ("zero-size array to reduction operation " "maximum which has no identity")
a = zeros((2, 2)) + 1
assert (add.reduce(a, axis=1) == [2, 2]).all()
assert (add.reduce(a, axis=(1,)) == [2, 2]).all()
exc = raises(ValueError, add.reduce, a, axis=2)
assert exc.value[0] == "'axis' entry is out of bounds"
示例8: sample_from_histogram
def sample_from_histogram(p, n_samples=1):
"""
returns the indice of bin according to the histogram p
@param p: histogram
@type p: numpy.array
@param n_samples: number of samples to generate
@type n_samples: integer
"""
from numpy import add, less, argsort, take, arange
from numpy.random import random
indices = argsort(p)
indices = take(indices, arange(len(p) - 1, -1, -1))
c = add.accumulate(take(p, indices)) / add.reduce(p)
return indices[add.reduce(less.outer(c, random(n_samples)), 0)]
示例9: getStats
def getStats(self, histo):
m = array(histo[1:])
sum = 0.0
sum2 = 0.0
n = float(add.reduce(m))
for j in range(len(m)):
sum = sum + j * m[j]
sum2 = sum2 + (j ** 2) * float(m[j])
var = (sum2-(sum**2.0)/n)/n
return sum/n,sqrt(var)
示例10: gaussian
def gaussian(sdev, size):
from math import exp
from numpy import empty, single as floatc, add, divide
g = empty((size,), floatc)
for i in range(size):
u = min(i,size-i) / sdev
p = min(u*u/2, 100) # avoid OverflowError with exp()
g[i] = exp(-p)
area = add.reduce(g)
divide(g, area, g)
return g
示例11: _make_f_matrix
def _make_f_matrix(matrix):
"""It takes an E matrix and returns an F matrix
The input is the output of make_E_matrix
For each element in matrix subtract mean of corresponding row and
column and add the mean of all elements in the matrix
"""
num_rows, num_cols = matrix.shape
# make a vector of the means for each row and column
# column_means = (add.reduce(E_matrix) / num_rows)
column_means = (add.reduce(matrix) / num_rows)[:, newaxis]
trans_matrix = transpose(matrix)
row_sums = add.reduce(trans_matrix)
row_means = row_sums / num_cols
# calculate the mean of the whole matrix
matrix_mean = nsum(row_sums) / (num_rows * num_cols)
# adjust each element in the E matrix to make the F matrix
matrix -= row_means
matrix -= column_means
matrix += matrix_mean
return matrix
示例12: RombergMethod
def RombergMethod(y, dx, show=False):
axis=-1
y = asarray(y)
nd = len(y.shape)
Nsamps = y.shape[axis]
Ninterv = Nsamps-1
n = 1
k = 0
while n < Ninterv:
n <<= 1
k += 1
R = {}
all = (slice(None),) * nd
slice0 = tupleset(all, axis, 0)
slicem1 = tupleset(all, axis, -1)
h = Ninterv*asarray(dx)*1.0
R[(1,1)] = (y[slice0] + y[slicem1])/2.0*h
slice_R = all
start = stop = step = Ninterv
for i in range(2,k+1):
start >>= 1
slice_R = tupleset(slice_R, axis, slice(start,stop,step))
step >>= 1
R[(i,1)] = 0.5*(R[(i-1,1)] + h*add.reduce(y[slice_R],axis))
for j in range(2,i+1):
R[(i,j)] = R[(i,j-1)] + \
(R[(i,j-1)]-R[(i-1,j-1)]) / ((1 << (2*(j-1)))-1)
h = h / 2.0
if show:
precis = 5
width = 8
formstr = "%" + str(width) + '.' + str(precis)+'f'
print('\nMétodo de Romberg')
print('----------------------------------')
for i in range(1,k+1):
for j in range(1,i+1):
print(formstr % R[(i,j)], end=' ')
print()
print('----------------------------------')
return R[(k,k)]
示例13: notes_roc
def notes_roc (la, lb, eps):
from numpy import transpose, add, resize
""" creates a matrix of size len(la)*len(lb) then look for hit and miss
in it within eps tolerance windows """
gdn,fpw,fpg,fpa,fdo,fdp = 0,0,0,0,0,0
m = len(la)
n = len(lb)
x = resize(la[:][0],(n,m))
y = transpose(resize(lb[:][0],(m,n)))
teps = (abs(x-y) <= eps[0])
x = resize(la[:][1],(n,m))
y = transpose(resize(lb[:][1],(m,n)))
tpitc = (abs(x-y) <= eps[1])
res = teps * tpitc
res = add.reduce(res,axis=0)
for i in range(len(res)) :
if res[i] > 1:
gdn+=1
fdo+=res[i]-1
elif res [i] == 1:
gdn+=1
fpa = n - gdn - fpa
return gdn,fpw,fpg,fpa,fdo,fdp
示例14: distanceA2AEuclideanSquared
def distanceA2AEuclideanSquared(x, std=[], w=[]):
"""
This function calcule the Euclidean Squared distance between
two or more variables.
"""
if std:
x = nparray(x)
x = stdobs(x) # standardize
x = x.tolist()
if w:
x = nparray(x)
w = w / float(npadd.reduce(w))
x = x * w # weights
x = x.tolist()
numrows = len(x)
distance = [0]*(numrows-1)
for row in xrange(numrows - 1):
npsublist = npsubtract(x[row], x[row + 1])
sublist = npsublist.tolist()
distance[row] = [square_double(sublist)]
return distance
示例15: test_reduce_1d
def test_reduce_1d(self):
import numpy as np
from numpy import array, add, maximum, less, float16, complex64
assert less.reduce([5, 4, 3, 2, 1])
assert add.reduce([1, 2, 3]) == 6
assert maximum.reduce([1]) == 1
assert maximum.reduce([1, 2, 3]) == 3
raises(ValueError, maximum.reduce, [])
assert add.reduce(array([True, False] * 200)) == 200
assert add.reduce(array([True, False] * 200, dtype="int8")) == 200
assert add.reduce(array([True, False] * 200), dtype="int8") == -56
assert type(add.reduce(array([True, False] * 200, dtype="float16"))) is float16
assert type(add.reduce(array([True, False] * 200, dtype="complex64"))) is complex64
for dtype in ["bool", "int"]:
assert np.equal.reduce([1, 2], dtype=dtype) == True
assert np.equal.reduce([1, 2, 0], dtype=dtype) == False