本文整理匯總了Python中numpy.isscalar方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.isscalar方法的具體用法?Python numpy.isscalar怎麽用?Python numpy.isscalar使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.isscalar方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: handle_zeros_in_scale
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def handle_zeros_in_scale(scale, copy=True):
''' Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.
Adapted from sklearn.preprocessing.data'''
# if we are fitting on 1D arrays, scale might be a scalar
if np.isscalar(scale):
if scale == .0:
scale = 1.
return scale
elif isinstance(scale, np.ndarray):
if copy:
# New array to avoid side-effects
scale = scale.copy()
scale[scale == 0.0] = 1.0
return scale
示例2: extract_params_as_shared_arrays
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def extract_params_as_shared_arrays(link):
assert isinstance(link, chainer.Link)
shared_arrays = {}
for param_name, param in link.namedparams():
typecode = param.array.dtype.char
shared_arrays[param_name] = mp.RawArray(typecode, param.array.ravel())
for persistent_name, persistent in chainerrl.misc.namedpersistent(link):
if isinstance(persistent, np.ndarray):
typecode = persistent.dtype.char
shared_arrays[persistent_name] = mp.RawArray(
typecode, persistent.ravel())
else:
assert np.isscalar(persistent)
# Wrap by a 1-dim array because multiprocessing.RawArray does not
# accept a 0-dim array.
persistent_as_array = np.asarray([persistent])
typecode = persistent_as_array.dtype.char
shared_arrays[persistent_name] = mp.RawArray(
typecode, persistent_as_array)
return shared_arrays
示例3: compute_policy_gradient_full_correction
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def compute_policy_gradient_full_correction(
action_distrib, action_distrib_mu, action_value, v,
truncation_threshold):
"""Compute off-policy bias correction term wrt all actions."""
assert truncation_threshold is not None
assert np.isscalar(v)
with chainer.no_backprop_mode():
rho_all_inv = compute_full_importance(action_distrib_mu,
action_distrib)
correction_weight = (
np.maximum(1 - truncation_threshold * rho_all_inv,
np.zeros_like(rho_all_inv)) *
action_distrib.all_prob.array[0])
correction_advantage = action_value.q_values.array[0] - v
return -F.sum(correction_weight *
action_distrib.all_log_prob *
correction_advantage, axis=1)
示例4: compute_policy_gradient_sample_correction
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def compute_policy_gradient_sample_correction(
action_distrib, action_distrib_mu, action_value, v,
truncation_threshold):
"""Compute off-policy bias correction term wrt a sampled action."""
assert np.isscalar(v)
assert truncation_threshold is not None
with chainer.no_backprop_mode():
sample_action = action_distrib.sample().array
rho_dash_inv = compute_importance(
action_distrib_mu, action_distrib, sample_action)
if (truncation_threshold > 0 and
rho_dash_inv >= 1 / truncation_threshold):
return chainer.Variable(np.asarray([0], dtype=np.float32))
correction_weight = max(0, 1 - truncation_threshold * rho_dash_inv)
assert correction_weight <= 1
q = float(action_value.evaluate_actions(sample_action).array[0])
correction_advantage = q - v
return -(correction_weight *
action_distrib.log_prob(sample_action) *
correction_advantage)
示例5: add_pixels
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def add_pixels(self, uv_px, img1d, weight=None):
# Lookup row & column for each in-bounds coordinate.
mask = self.get_mask(uv_px)
xx = uv_px[0,mask]
yy = uv_px[1,mask]
# Update matrix according to assigned weight.
if weight is None:
img1d[mask] = self.img[yy,xx]
elif np.isscalar(weight):
img1d[mask] += self.img[yy,xx] * weight
else:
w1 = np.asmatrix(weight, dtype='float32')
w3 = w1.transpose() * np.ones((1,3))
img1d[mask] += np.multiply(self.img[yy,xx], w3[mask])
# A panorama image made from several FisheyeImage sources.
# TODO: Add support for supersampled anti-aliasing filters.
示例6: convert_dictionary_keys_to_dense_indices
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def convert_dictionary_keys_to_dense_indices(dictionary):
"""Convert the keys to tuples containing integers.
Example
-------
>>> dictionary = {(0.0, 1): 0, 2: 1}
>>> convert_dictionary_keys_to_dense_indices(dictionary)
{(0, 1): 0, (2,): 1}
"""
new_dictionary = {}
for key, val in dictionary.items():
new_key = (int(key),) if np.isscalar(key) else tuple(int(i) for i in key)
new_dictionary[new_key] = val
return new_dictionary
示例7: sparse_to_dense
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def sparse_to_dense(voxel_data, dims, dtype=np.bool):
if voxel_data.ndim != 2 or voxel_data.shape[0] != 3:
raise ValueError('voxel_data is wrong shape; should be 3xN array.')
if np.isscalar(dims):
dims = [dims] * 3
dims = np.atleast_2d(dims).T
# truncate to integers
xyz = voxel_data.astype(np.int)
# discard voxels that fall outside dims
valid_ix = ~np.any((xyz < 0) | (xyz >= dims), 0)
xyz = xyz[:, valid_ix]
out = np.zeros(dims.flatten(), dtype=dtype)
out[tuple(xyz)] = True
return out
# def get_linear_index(x, y, z, dims):
# """ Assuming xzy order. (y increasing fastest.
# TODO ensure this is right when dims are not all same
# """
# return x*(dims[1]*dims[2]) + z*dims[1] + y
示例8: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def __init__(self, zval, pz, shape, var_axes=(0,),\
is_complex=False,name=None):
# Convert scalars to arrays
if np.isscalar(zval):
zval = np.array([zval])
if np.isscalar(pz):
pz = np.array([pz])
# Set parameters of base estimator
dtype = zval.dtype
BaseEst.__init__(self,shape=shape, var_axes=var_axes, dtype=dtype, name=name,\
type_name='DiscreteEst', nvars=1, cost_avail=True)
# Set parameters
self.zval = zval
self.pz = pz
self.shape = shape
self.is_complex = is_complex
self.fz = -np.log(pz)
示例9: _tojson
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def _tojson(*numpy_objs):
'''Utility function which returns a list where each element of numpy_objs
is converted to its python equivalent (float or list)'''
ret = []
# problem: browsers might not be happy with JSON 'NAN', so convert
# NaNs to None. Unfortunately, the conversion must be done element wise
# in numpy (seems not to exist a pandas na filter):
for obj in numpy_objs:
isscalar = np.isscalar(obj)
nan_indices = None if isscalar else \
np.argwhere(np.isnan(obj)).flatten()
# note: numpy.float64(N).tolist() returns a python float, so:
obj = None if isscalar and np.isnan(obj) else obj.tolist()
if nan_indices is not None:
for idx in nan_indices:
obj[idx] = None
ret.append(obj)
return ret # tuple(_.tolist() for _ in numpy_objs)
示例10: gen_random_legcharge_nq
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def gen_random_legcharge_nq(chinfo, ind_len, n_qsector):
"""return a random (unsorted) LegCharge with a given number of charge sectors.
`nqsector` gives the (desired) number of sectors for each of the charges.
"""
if np.isscalar(n_qsector):
n_qsector = [n_qsector] * chinfo.qnumber
n_qsector = np.asarray(n_qsector, dtype=np.intp)
if n_qsector.shape != (chinfo.qnumber, ):
raise ValueError
slices = rand_partitions(0, ind_len, np.prod(n_qsector, dtype=int))
qs = np.zeros((len(slices) - 1, len(n_qsector)), int)
q_combos = [a for a in it.product(*[range(-(nq // 2), nq // 2 + 1) for nq in n_qsector])]
qs = np.array(q_combos)[rand_distinct_int(0, len(q_combos) - 1, len(slices) - 1), :]
qs = chinfo.make_valid(qs)
return npc.LegCharge.from_qind(chinfo, slices, qs)
示例11: gen_random_legcharge_nq
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def gen_random_legcharge_nq(chinfo, ind_len, n_qsector):
"""return a random (unsorted) LegCharge with a given number of charge sectors.
`nqsector` gives the (desired) number of sectors for each of the charges.
"""
if np.isscalar(n_qsector):
n_qsector = [n_qsector] * chinfo.qnumber
n_qsector = np.asarray(n_qsector, dtype=np.intp)
if n_qsector.shape != (chinfo.qnumber, ):
raise ValueError
slices = rand_partitions(0, ind_len, np.prod(n_qsector, dtype=int))
qs = np.zeros((len(slices) - 1, len(n_qsector)), int)
q_combos = [a for a in it.product(*[range(-(nq // 2), nq // 2 + 1) for nq in n_qsector])]
qs = np.array(q_combos)[rand_distinct_int(0, len(q_combos) - 1, len(slices) - 1), :]
qs = chinfo.make_valid(qs)
return charges.LegCharge.from_qind(chinfo, slices, qs)
示例12: test_dense_embeddings
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def test_dense_embeddings(make_categories, reps, layer):
"""Test the embedding layer."""
x, K = make_categories
x = np.repeat(x, reps, axis=-1)
N = len(x)
S = 3
x_, X_ = _make_placeholders(x, S, tf.int32)
output, reg = layer(output_dim=D, n_categories=K)(X_)
tc = tf.test.TestCase()
with tc.test_session():
tf.global_variables_initializer().run()
r = reg.eval()
assert np.isscalar(r)
assert r >= 0
Phi = output.eval(feed_dict={x_: x})
assert Phi.shape == (S, N, D * reps)
示例13: test_dense_outputs
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def test_dense_outputs(dense, make_data):
"""Make sure the dense layers output expected dimensions."""
x, _, _ = make_data
S = 3
x_, X_ = _make_placeholders(x, S)
N = x.shape[0]
Phi, KL = dense(output_dim=D)(X_)
tc = tf.test.TestCase()
with tc.test_session():
tf.global_variables_initializer().run()
P = Phi.eval(feed_dict={x_: x})
assert P.shape == (S, N, D)
assert P.dtype == np.float32
assert np.isscalar(KL.eval(feed_dict={x_: x}))
示例14: test_kl_gaussian_normal
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def test_kl_gaussian_normal(random):
"""Test Gaussian/Normal KL."""
dim = (5, 10)
Dim = (5, 10, 10)
mu0 = random.randn(*dim).astype(np.float32)
L0 = random_chol(Dim)
q = tfp.distributions.MultivariateNormalTriL(mu0, L0)
mu1 = random.randn(*dim).astype(np.float32)
std1 = 1.0
L1 = [(std1 * np.eye(dim[1])).astype(np.float32) for _ in range(dim[0])]
p = tf.distributions.Normal(mu1, std1)
KL = kl_sum(q, p)
KLr = KLdiv(mu0, L0, mu1, L1)
tc = tf.test.TestCase()
with tc.test_session():
kl = KL.eval()
assert np.isscalar(kl)
assert np.allclose(kl, KLr)
示例15: __add__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import isscalar [as 別名]
def __add__(self, other):
if np.isscalar(other):
other = Constant(other, "Constant({})".format(other))
name = "Add({},{})".format(self.name, other.name)
return BinOp(np.add, name)(self, other)
assert isinstance(other, Node)
name = "Add({},{})".format(self.name, other.name)
return BinOp(np.add, name)(self, other)