本文整理汇总了Python中numpy.ma.expand_dims方法的典型用法代码示例。如果您正苦于以下问题:Python ma.expand_dims方法的具体用法?Python ma.expand_dims怎么用?Python ma.expand_dims使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy.ma
的用法示例。
在下文中一共展示了ma.expand_dims方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: moment
# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import expand_dims [as 别名]
def moment(a, moment=1, axis=0):
a, axis = _chk_asarray(a, axis)
if moment == 1:
# By definition the first moment about the mean is 0.
shape = list(a.shape)
del shape[axis]
if shape:
# return an actual array of the appropriate shape
return np.zeros(shape, dtype=float)
else:
# the input was 1D, so return a scalar instead of a rank-0 array
return np.float64(0.0)
else:
mn = ma.expand_dims(a.mean(axis=axis), axis)
s = ma.power((a-mn), moment)
return s.mean(axis=axis)
示例2: read
# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import expand_dims [as 别名]
def read(self, indexes=None, **kwargs):
"""
Read reprojected & resampled input data.
Parameters
----------
indexes : integer or list
band number or list of band numbers
Returns
-------
data : array
"""
band_indexes = self._get_band_indexes(indexes)
arr = self.process.get_raw_output(self.tile)
return (
arr[band_indexes[0] - 1]
if len(band_indexes) == 1
else ma.concatenate([ma.expand_dims(arr[i - 1], 0) for i in band_indexes])
)
示例3: concatenate
# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import expand_dims [as 别名]
def concatenate(self,value,axis=0):
""" Concatentate UncertContainer value to self.
Assumes that if dimensions of self and value do not match, to
add a np.newaxis along axis of value
"""
if isinstance(value,UncertContainer):
if value.vals.ndim == self.vals.ndim:
vals = value.vals
dmin = value.dmin
dmax = value.dmax
wt = value.wt
uncert = value.uncert
mask = value.mask
elif (value.vals.ndim + 1) == self.vals.ndim:
vals = ma.expand_dims(value.vals,axis)
dmin = ma.expand_dims(value.dmin,axis)
dmax = ma.expand_dims(value.dmax,axis)
wt = ma.expand_dims(value.wt,axis)
uncert = ma.expand_dims(value.uncert,axis)
mask = np.expand_dims(value.mask,axis)
else:
raise ValueError('Could not propery match dimensionality')
self.vals = ma.concatenate((self.vals,vals),axis=axis)
self.dmin = ma.concatenate((self.dmin,dmin),axis=axis)
self.dmax = ma.concatenate((self.dmax,dmax),axis=axis)
self.wt = ma.concatenate((self.wt,wt),axis=axis)
self.uncert = ma.concatenate((self.uncert,uncert),axis=axis)
self.mask = np.concatenate((self.mask,mask),axis=axis)
else:
raise ValueError('Can only concatenate with an UncertContainer object')
示例4: weighted_average
# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import expand_dims [as 别名]
def weighted_average(self,axis=0,expaxis=None):
""" Calculate weighted average of data along axis
after optionally inserting a new dimension into the
shape array at position expaxis
"""
if expaxis is not None:
vals = ma.expand_dims(self.vals,expaxis)
dmin = ma.expand_dims(self.dmin,expaxis)
dmax = ma.expand_dims(self.dmax,expaxis)
wt = ma.expand_dims(self.wt,expaxis)
else:
vals = self.vals
wt = self.wt
dmin = self.dmin
dmax = self.dmax
# Get average value
avg,norm = ma.average(vals,axis=axis,weights=wt,returned=True)
avg_ex = ma.expand_dims(avg,0)
# Calculate weighted uncertainty
wtmax = ma.max(wt,axis=axis)
neff = norm/wtmax # Effective number of samples based on uncertainties
# Seeking max deviation from the average; if above avg use max, if below use min
term = np.empty_like(vals)
indices = np.where(vals > avg_ex)
i0 = indices[0]
irest = indices[1:]
ii = tuple(x for x in itertools.chain([i0],irest))
jj = tuple(x for x in itertools.chain([np.zeros_like(i0)],irest))
term[ii] = (dmax[ii] - avg_ex[jj])**2
indices = np.where(vals <= avg_ex)
i0 = indices[0]
irest = indices[1:]
ii = tuple(x for x in itertools.chain([i0],irest))
jj = tuple(x for x in itertools.chain([np.zeros_like(i0)],irest))
term[ii] = (avg_ex[jj] - dmin[ii])**2
dsum = ma.sum(term*wt,axis=0) # Sum for weighted average of deviations
dev = 0.5*np.sqrt(dsum/(norm*neff))
if isinstance(avg,(float,np.float)):
avg = avg_ex
tmp_min = avg - dev
ii = np.where(tmp_min < 0)
tmp_min[ii] = TOL*avg[ii]
return UncertContainer(avg,tmp_min,avg+dev)
示例5: moment
# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import expand_dims [as 别名]
def moment(a, moment=1, axis=0):
"""
Calculates the nth moment about the mean for a sample.
Parameters
----------
a : array_like
data
moment : int, optional
order of central moment that is returned
axis : int or None, optional
Axis along which the central moment is computed. Default is 0.
If None, compute over the whole array `a`.
Returns
-------
n-th central moment : ndarray or float
The appropriate moment along the given axis or over all values if axis
is None. The denominator for the moment calculation is the number of
observations, no degrees of freedom correction is done.
Notes
-----
For more details about `moment`, see `stats.moment`.
"""
a, axis = _chk_asarray(a, axis)
if moment == 1:
# By definition the first moment about the mean is 0.
shape = list(a.shape)
del shape[axis]
if shape:
# return an actual array of the appropriate shape
return np.zeros(shape, dtype=float)
else:
# the input was 1D, so return a scalar instead of a rank-0 array
return np.float64(0.0)
else:
# Exponentiation by squares: form exponent sequence
n_list = [moment]
current_n = moment
while current_n > 2:
if current_n % 2:
current_n = (current_n-1)/2
else:
current_n /= 2
n_list.append(current_n)
# Starting point for exponentiation by squares
a_zero_mean = a - ma.expand_dims(a.mean(axis), axis)
if n_list[-1] == 1:
s = a_zero_mean.copy()
else:
s = a_zero_mean**2
# Perform multiplications
for n in n_list[-2::-1]:
s = s**2
if n % 2:
s *= a_zero_mean
return s.mean(axis)
示例6: prepare_array
# 需要导入模块: from numpy import ma [as 别名]
# 或者: from numpy.ma import expand_dims [as 别名]
def prepare_array(data, masked=True, nodata=0, dtype="int16"):
"""
Turn input data into a proper array for further usage.
Output array is always 3-dimensional with the given data type. If the output
is masked, the fill_value corresponds to the given nodata value and the
nodata value will be burned into the data array.
Parameters
----------
data : array or iterable
array (masked or normal) or iterable containing arrays
nodata : integer or float
nodata value (default: 0) used if input is not a masked array and
for output array
masked : bool
return a NumPy Array or a NumPy MaskedArray (default: True)
dtype : string
data type of output array (default: "int16")
Returns
-------
array : array
"""
# input is iterable
if isinstance(data, (list, tuple)):
return _prepare_iterable(data, masked, nodata, dtype)
# special case if a 2D single band is provided
elif isinstance(data, np.ndarray) and data.ndim == 2:
data = ma.expand_dims(data, axis=0)
# input is a masked array
if isinstance(data, ma.MaskedArray):
return _prepare_masked(data, masked, nodata, dtype)
# input is a NumPy array
elif isinstance(data, np.ndarray):
if masked:
return ma.masked_values(data.astype(dtype, copy=False), nodata, copy=False)
else:
return data.astype(dtype, copy=False)
else:
raise ValueError(
"Data must be array, masked array or iterable containing arrays. "
"Current data: %s (%s)" % (data, type(data))
)