本文整理汇总了Python中numpy.place方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.place方法的具体用法?Python numpy.place怎么用?Python numpy.place使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.place方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: one_shot_method
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def one_shot_method(prediction, x, curr_sample, curr_target, p_t):
grad_est = np.zeros((BATCH_SIZE, IMAGE_ROWS, IMAGE_COLS, NUM_CHANNELS))
DELTA = np.random.randint(2, size=(BATCH_SIZE, IMAGE_ROWS, IMAGE_COLS, NUM_CHANNELS))
np.place(DELTA, DELTA==0, -1)
y_plus = np.clip(curr_sample + args.delta * DELTA, CLIP_MIN, CLIP_MAX)
y_minus = np.clip(curr_sample - args.delta * DELTA, CLIP_MIN, CLIP_MAX)
if args.CW_loss == 0:
pred_plus = K.get_session().run([prediction], feed_dict={x: y_plus, K.learning_phase(): 0})[0]
pred_plus_t = pred_plus[np.arange(BATCH_SIZE), list(curr_target)]
pred_minus = K.get_session().run([prediction], feed_dict={x: y_minus, K.learning_phase(): 0})[0]
pred_minus_t = pred_minus[np.arange(BATCH_SIZE), list(curr_target)]
num_est = (pred_plus_t - pred_minus_t)
grad_est = num_est[:, None, None, None]/(args.delta * DELTA)
# Getting gradient of the loss
if args.CW_loss == 0:
loss_grad = -1.0 * grad_est/p_t[:, None, None, None]
return loss_grad
示例2: denormalize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def denormalize(self, data):
data_array, dict_flag = self.mode_checker(data)
for name in data_array.keys(): # normalize data for each named inputs
magic_mask = [data_array[name] == MAGIC_NUMBER]
if self._custom_denorm_func is not None:
data_array[name] = self._custom_denorm_func(data_array[name])
data_array[name] *= self.std_labels[name]
data_array[name] += self.mean_labels[name]
np.place(data_array[name], magic_mask, MAGIC_NUMBER)
if not dict_flag:
data_array = data_array["Temp"]
self.mean_labels = self.mean_labels['Temp']
self.std_labels = self.std_labels['Temp']
return data_array
示例3: kurtosis
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def kurtosis(a, axis=0, fisher=True, bias=True):
a, axis = _chk_asarray(a, axis)
m2 = moment(a,2,axis)
m4 = moment(a,4,axis)
olderr = np.seterr(all='ignore')
try:
vals = ma.where(m2 == 0, 0, m4 / m2**2.0)
finally:
np.seterr(**olderr)
if not bias:
n = a.count(axis)
can_correct = (n > 3) & (m2 is not ma.masked and m2 > 0)
if can_correct.any():
n = np.extract(can_correct, n)
m2 = np.extract(can_correct, m2)
m4 = np.extract(can_correct, m4)
nval = 1.0/(n-2)/(n-3)*((n*n-1.0)*m4/m2**2.0-3*(n-1)**2.0)
np.place(vals, can_correct, nval+3.0)
if fisher:
return vals - 3
else:
return vals
示例4: _get_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def _get_data(self):
if any(not os.path.exists(path) or not check_sha1(path, sha1) for path, sha1 in
((os.path.join(self._root, name), sha1) for _, name, sha1 in self._train_data + self._test_data)):
for url, _, sha1 in self._train_data + self._test_data:
download(url=url, path=self._root, sha1_hash=sha1)
if self._mode == "train":
data_files = self._train_data[0]
else:
data_files = self._test_data[0]
import scipy.io as sio
loaded_mat = sio.loadmat(os.path.join(self._root, data_files[1]))
data = loaded_mat["X"]
data = np.transpose(data, (3, 0, 1, 2))
self._data = mx.nd.array(data, dtype=data.dtype)
self._label = loaded_mat["y"].astype(np.int32).squeeze()
np.place(self._label, self._label == 10, 0)
示例5: _flatten_fdir
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def _flatten_fdir(self, fdir, flat_idx, dirmap, copy=False):
# WARNING: This modifies fdir in place if copy is set to False!
if copy:
fdir = fdir.copy()
shape = fdir.shape
go_to = (
0 - shape[1],
1 - shape[1],
1 + 0,
1 + shape[1],
0 + shape[1],
-1 + shape[1],
-1 + 0,
-1 - shape[1]
)
gotomap = dict(zip(dirmap, go_to))
for k, v in gotomap.items():
fdir[fdir == k] = v
fdir.flat[flat_idx] += flat_idx
示例6: set_nodata
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def set_nodata(self, data_name, new_nodata, old_nodata=None):
"""
Change nodata value of a dataset.
Parameters
----------
data_name : string
Attribute name of dataset to change.
new_nodata : int or float
New nodata value to use.
old_nodata : int or float (optional)
If none provided, defaults to
self.<data_name>.<nodata>
"""
if old_nodata is None:
old_nodata = getattr(self, data_name).nodata
data = getattr(self, data_name)
if np.isnan(old_nodata):
np.place(data, np.isnan(data), new_nodata)
else:
np.place(data, data == old_nodata, new_nodata)
data.nodata = new_nodata
示例7: _cdf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def _cdf(self, x, c):
output = np.zeros(x.shape, dtype=x.dtype)
val = (1.0+c)/(1.0-c)
c1 = x < np.pi
c2 = 1-c1
xp = np.extract(c1, x)
xn = np.extract(c2, x)
if np.any(xn):
valn = np.extract(c2, np.ones_like(x)*val)
xn = 2*np.pi - xn
yn = np.tan(xn/2.0)
on = 1.0-1.0/np.pi*np.arctan(valn*yn)
np.place(output, c2, on)
if np.any(xp):
valp = np.extract(c1, np.ones_like(x)*val)
yp = np.tan(xp/2.0)
op = 1.0/np.pi*np.arctan(valp*yp)
np.place(output, c1, op)
return output
示例8: place
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def place(arr, mask, vals):
"""
Change elements of an array based on conditional and input values.
Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
`place` uses the first N elements of `vals`, where N is the number of
True values in `mask`, while `copyto` uses the elements where `mask`
is True.
Note that `extract` does the exact opposite of `place`.
Parameters
----------
arr : ndarray
Array to put data into.
mask : array_like
Boolean mask array. Must have the same size as `a`.
vals : 1-D sequence
Values to put into `a`. Only the first N elements are used, where
N is the number of True values in `mask`. If `vals` is smaller
than N, it will be repeated, and if elements of `a` are to be masked,
this sequence must be non-empty.
See Also
--------
copyto, put, take, extract
Examples
--------
>>> arr = np.arange(6).reshape(2, 3)
>>> np.place(arr, arr>2, [44, 55])
>>> arr
array([[ 0, 1, 2],
[44, 55, 44]])
"""
if not isinstance(arr, np.ndarray):
raise TypeError("argument 1 must be numpy.ndarray, "
"not {name}".format(name=type(arr).__name__))
return _insert(arr, mask, vals)
示例9: _update_dim_sizes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def _update_dim_sizes(dim_sizes, arg, core_dims):
"""
Incrementally check and update core dimension sizes for a single argument.
Arguments
---------
dim_sizes : Dict[str, int]
Sizes of existing core dimensions. Will be updated in-place.
arg : ndarray
Argument to examine.
core_dims : Tuple[str, ...]
Core dimensions for this argument.
"""
if not core_dims:
return
num_core_dims = len(core_dims)
if arg.ndim < num_core_dims:
raise ValueError(
'%d-dimensional argument does not have enough '
'dimensions for all core dimensions %r'
% (arg.ndim, core_dims))
core_shape = arg.shape[-num_core_dims:]
for dim, size in zip(core_dims, core_shape):
if dim in dim_sizes:
if size != dim_sizes[dim]:
raise ValueError(
'inconsistent size for core dimension %r: %r vs %r'
% (dim, size, dim_sizes[dim]))
else:
dim_sizes[dim] = size
示例10: substitute_values
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def substitute_values(self, vect):
"""
Internal method to substitute integers into the vector, and construct
metadata to convert back to the original vector.
np.nan is always given -1, all other objects are given integers in
order of apperence.
Parameters
----------
vect : np.array
the vector in which to substitute values in
"""
try:
unique = np.unique(vect)
except:
unique = set(vect)
unique = [
x for x in unique if not isinstance(x, float) or not isnan(x)
]
arr = np.copy(vect)
for new_id, value in enumerate(unique):
np.place(arr, arr==value, new_id)
self.metadata[new_id] = value
arr = arr.astype(np.float)
np.place(arr, np.isnan(arr), -1)
self.arr = arr
if -1 in arr:
self.metadata[-1] = self._missing_id
示例11: add_newdoc
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def add_newdoc(place, obj, doc):
"""
Adds documentation to obj which is in module place.
If doc is a string add it to obj as a docstring
If doc is a tuple, then the first element is interpreted as
an attribute of obj and the second as the docstring
(method, docstring)
If doc is a list, then each element of the list should be a
sequence of length two --> [(method1, docstring1),
(method2, docstring2), ...]
This routine never raises an error.
This routine cannot modify read-only docstrings, as appear
in new-style classes or built-in functions. Because this
routine never raises an error the caller must check manually
that the docstrings were changed.
"""
try:
new = getattr(__import__(place, globals(), {}, [obj]), obj)
if isinstance(doc, str):
add_docstring(new, doc.strip())
elif isinstance(doc, tuple):
add_docstring(getattr(new, doc[0]), doc[1].strip())
elif isinstance(doc, list):
for val in doc:
add_docstring(getattr(new, val[0]), val[1].strip())
except Exception:
pass
# Based on scitools meshgrid
示例12: _lazyselect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def _lazyselect(condlist, choicelist, arrays, default=0):
"""
Mimic `np.select(condlist, choicelist)`.
Notice it assumes that all `arrays` are of the same shape, or can be
broadcasted together.
All functions in `choicelist` must accept array arguments in the order
given in `arrays` and must return an array of the same shape as broadcasted
`arrays`.
Examples
--------
>>> x = np.arange(6)
>>> np.select([x <3, x > 3], [x**2, x**3], default=0)
array([ 0, 1, 4, 0, 64, 125])
>>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
array([ 0., 1., 4., 0., 64., 125.])
>>> a = -np.ones_like(x)
>>> _lazyselect([x < 3, x > 3],
... [lambda x, a: x**2, lambda x, a: a * x**3],
... (x, a), default=np.nan)
array([ 0., 1., 4., nan, -64., -125.])
"""
arrays = np.broadcast_arrays(*arrays)
tcode = np.mintypecode([a.dtype.char for a in arrays])
out = _valarray(np.shape(arrays[0]), value=default, typecode=tcode)
for index in range(len(condlist)):
func, cond = choicelist[index], condlist[index]
if np.all(cond is False):
continue
cond, _ = np.broadcast_arrays(cond, arrays[0])
temp = tuple(np.extract(cond, arr) for arr in arrays)
np.place(out, cond, func(*temp))
return out
示例13: _stats
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def _stats(self, b, moments='mv'):
mu, mu2, g1, g2 = None, None, None, None
if 'm' in moments:
mask = b > 1
bt = np.extract(mask, b)
mu = valarray(np.shape(b), value=np.inf)
np.place(mu, mask, bt / (bt-1.0))
if 'v' in moments:
mask = b > 2
bt = np.extract(mask, b)
mu2 = valarray(np.shape(b), value=np.inf)
np.place(mu2, mask, bt / (bt-2.0) / (bt-1.0)**2)
if 's' in moments:
mask = b > 3
bt = np.extract(mask, b)
g1 = valarray(np.shape(b), value=np.nan)
vals = 2 * (bt + 1.0) * np.sqrt(bt - 2.0) / ((bt - 3.0) * np.sqrt(bt))
np.place(g1, mask, vals)
if 'k' in moments:
mask = b > 4
bt = np.extract(mask, b)
g2 = valarray(np.shape(b), value=np.nan)
vals = (6.0*np.polyval([1.0, 1.0, -6, -2], bt) /
np.polyval([1.0, -7.0, 12.0, 0.0], bt))
np.place(g2, mask, vals)
return mu, mu2, g1, g2
示例14: _pdf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def _pdf(self, x, b):
# rice.pdf(x, b) = x * exp(-(x**2+b**2)/2) * I[0](x*b)
#
# We use (x**2 + b**2)/2 = ((x-b)**2)/2 + xb.
# The factor of np.exp(-xb) is then included in the i0e function
# in place of the modified Bessel function, i0, improving
# numerical stability for large values of xb.
return x * np.exp(-(x-b)*(x-b)/2.0) * sc.i0e(x*b)
示例15: add_newdoc
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import place [as 别名]
def add_newdoc(place, obj, doc):
"""
Adds documentation to obj which is in module place.
If doc is a string add it to obj as a docstring
If doc is a tuple, then the first element is interpreted as
an attribute of obj and the second as the docstring
(method, docstring)
If doc is a list, then each element of the list should be a
sequence of length two --> [(method1, docstring1),
(method2, docstring2), ...]
This routine never raises an error.
This routine cannot modify read-only docstrings, as appear
in new-style classes or built-in functions. Because this
routine never raises an error the caller must check manually
that the docstrings were changed.
"""
try:
new = getattr(__import__(place, globals(), {}, [obj]), obj)
if isinstance(doc, str):
add_docstring(new, doc.strip())
elif isinstance(doc, tuple):
add_docstring(getattr(new, doc[0]), doc[1].strip())
elif isinstance(doc, list):
for val in doc:
add_docstring(getattr(new, val[0]), val[1].strip())
except:
pass
# Based on scitools meshgrid