本文整理汇总了Python中autograd.numpy.asarray方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.asarray方法的具体用法?Python numpy.asarray怎么用?Python numpy.asarray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autograd.numpy
的用法示例。
在下文中一共展示了numpy.asarray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resample
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def resample(self):
"""Create a new SFS by resampling blocks with replacement.
Note the resampled SFS is assumed to have the same length in base pairs \
as the original SFS, which may be a poor assumption if the blocks are not of equal length.
:returns: Resampled SFS
:rtype: :class:`Sfs`
"""
loci = np.random.choice(
np.arange(self.n_loci), size=self.n_loci, replace=True)
mat = self.freqs_matrix[:, loci]
to_keep = np.asarray(mat.sum(axis=1) > 0).squeeze()
to_keep = np.arange(len(self.configs))[to_keep]
mat = mat[to_keep, :]
configs = _ConfigList_Subset(self.configs, to_keep)
return self.from_matrix(mat, configs, self.folded, self.length)
示例2: __init__
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def __init__(self, sigma2s, wts=None):
"""
Mixture of isotropic Gaussian kernels:
sum wts[i] * exp(- ||x - y||^2 / (2 * sigma2s[i]))
sigma2s: a list/array of squared bandwidths
wts: a list/array of weights. Defaults to equal weights summing to 1.
"""
self.sigma2s = sigma2s = np.asarray(sigma2s)
assert len(sigma2s) > 0
if wts is None:
self.wts = wts = np.full(len(sigma2s), 1/len(sigma2s))
else:
self.wts = wts = np.asarray(wts)
assert len(wts) == len(sigma2s)
assert all(w >= 0 for w in wts)
示例3: _set_precision_prior
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _set_precision_prior(self, precision_prior):
if precision_prior is None:
self._precision_prior_ = \
np.zeros((self.n_components, self.n_features, self.n_features))
else:
precision_prior = np.asarray(precision_prior)
if len(precision_prior) == 1:
self._precision_prior_ = np.tile(precision_prior,
(self.n_components, self.n_features, self.n_features))
elif \
(precision_prior.reshape(self.n_unique, self.n_features, self.n_features)).shape \
== (self.n_unique, self.n_features, self.n_features):
self._precision_prior_ = \
np.zeros((self.n_components, self.n_features, self.n_features))
for u in range(self.n_unique):
for t in range(self.n_chain):
self._precision_prior_[u*(self.n_chain)+t] = precision_prior[u].copy()
else:
raise ValueError("cannot match shape of precision_prior")
示例4: _set_startprob
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _set_startprob(self, startprob):
if startprob is None:
startprob = np.tile(1.0 / self.n_components, self.n_components)
else:
startprob = np.asarray(startprob, dtype=np.float)
normalize(startprob)
if len(startprob) != self.n_components:
if len(startprob) == self.n_unique:
startprob_split = np.copy(startprob) / (1.0+self.n_tied)
startprob = np.zeros(self.n_components)
for u in range(self.n_unique):
for t in range(self.n_chain):
startprob[u*(self.n_chain)+t] = \
startprob_split[u].copy()
else:
raise ValueError("cannot match shape of startprob")
if not np.allclose(np.sum(startprob), 1.0):
raise ValueError('startprob must sum to 1.0')
self._log_startprob = np.log(np.asarray(startprob).copy())
示例5: _set_transmat
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _set_transmat(self, transmat_val):
if transmat_val is None:
transmat = np.tile(1.0 / self.n_components,
(self.n_components, self.n_components))
else:
transmat_val[np.isnan(transmat_val)] = 0.0
normalize(transmat_val, axis=1)
if (np.asarray(transmat_val).shape == (self.n_components,
self.n_components)):
transmat = np.copy(transmat_val)
elif transmat_val.shape[0] == self.n_unique:
transmat = self._ntied_transmat(transmat_val)
else:
raise ValueError("cannot match shape of transmat")
if not np.all(np.allclose(np.sum(transmat, axis=1), 1.0)):
raise ValueError('Rows of transmat must sum to 1.0')
self._log_transmat = np.log(np.asarray(transmat).copy())
underflow_idx = np.isnan(self._log_transmat)
self._log_transmat[underflow_idx] = NEGINF
示例6: _centered
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _centered(arr, newshape):
"""Return the center newshape portion of the array.
This function is used by `fft_convolve` to remove
the zero padded region of the convolution.
Note: If the array shape is odd and the target is even,
the center of `arr` is shifted to the center-right
pixel position.
This is slightly different than the scipy implementation,
which uses the center-left pixel for the array center.
The reason for the difference is that we have
adopted the convention of `np.fft.fftshift` in order
to make sure that changing back and forth from
fft standard order (0 frequency and position is
in the bottom left) to 0 position in the center.
"""
newshape = np.asarray(newshape)
currshape = np.array(arr.shape)
if not np.all(newshape <= currshape):
msg = (
"arr must be larger than newshape in both dimensions, received {0}, and {1}"
)
raise ValueError(msg.format(arr.shape, newshape))
startind = (currshape - newshape + 1) // 2
endind = startind + newshape
myslice = [slice(startind[k], endind[k]) for k in range(len(endind))]
return arr[tuple(myslice)]
示例7: _pad
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _pad(arr, newshape, axes=None, mode="constant", constant_values=0):
"""Pad an array to fit into newshape
Pad `arr` with zeros to fit into newshape,
which uses the `np.fft.fftshift` convention of moving
the center pixel of `arr` (if `arr.shape` is odd) to
the center-right pixel in an even shaped `newshape`.
"""
if axes is None:
newshape = np.asarray(newshape)
currshape = np.array(arr.shape)
dS = newshape - currshape
startind = (dS + 1) // 2
endind = dS - startind
pad_width = list(zip(startind, endind))
else:
# only pad the axes that will be transformed
pad_width = [(0, 0) for axis in arr.shape]
try:
len(axes)
except TypeError:
axes = [axes]
for a, axis in enumerate(axes):
dS = newshape[a] - arr.shape[axis]
startind = (dS + 1) // 2
endind = dS - startind
pad_width[axis] = (startind, endind)
if mode == "constant" and constant_values == 0:
result = fast_zero_pad(arr, pad_width)
else:
result = np.pad(arr, pad_width, mode=mode)
return result
示例8: __new__
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def __new__(
cls,
array,
name="unnamed",
prior=None,
constraint=None,
step=0,
std=None,
m=None,
v=None,
vhat=None,
fixed=False,
):
obj = np.asarray(array, dtype=array.dtype).view(cls)
obj.name = name
if prior is not None:
assert isinstance(prior, Prior)
obj.prior = prior
if constraint is not None:
assert isinstance(constraint, Constraint) or isinstance(
constraint, ConstraintChain
)
obj.constraint = constraint
obj.step = step
obj.std = std
obj.m = m
obj.v = v
obj.vhat = vhat
obj.fixed = fixed
return obj
示例9: make_grad_softplus
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def make_grad_softplus(ans, x):
x = np.asarray(x)
def gradient_product(g):
return np.full(x.shape, g) * np.exp(x - ans)
return gradient_product
示例10: print_training_prediction
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def print_training_prediction(weights):
print("Training text Predicted text")
logprobs = np.asarray(rnn_predict(weights, train_inputs))
for t in range(logprobs.shape[1]):
training_text = one_hot_to_string(train_inputs[:,t,:])
predicted_text = one_hot_to_string(logprobs[:,t,:])
print(training_text.replace('\n', ' ') + "|" +
predicted_text.replace('\n', ' '))
示例11: print_training_prediction
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def print_training_prediction(weights):
print("Training text Predicted text")
logprobs = np.asarray(lstm_predict(weights, train_inputs))
for t in range(logprobs.shape[1]):
training_text = one_hot_to_string(train_inputs[:,t,:])
predicted_text = one_hot_to_string(logprobs[:,t,:])
print(training_text.replace('\n', ' ') + "|" +
predicted_text.replace('\n', ' '))
示例12: multivariate_t_rvs
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def multivariate_t_rvs(self, m, S, random_state = None):
'''generate random variables of multivariate t distribution
Parameters
----------
m : array_like
mean of random variable, length determines dimension of random variable
S : array_like
square array of covariance matrix
df : int or float
degrees of freedom
n : int
number of observations, return random array will be (n, len(m))
random_state : int
seed
Returns
-------
rvs : ndarray, (n, len(m))
each row is an independent draw of a multivariate t distributed
random variable
'''
np.random.rand(9)
m = np.asarray(m)
d = self.n_features
df = self.degree_freedom
n = 1
if df == np.inf:
x = 1.
else:
x = random_state.chisquare(df, n)/df
np.random.rand(90)
z = random_state.multivariate_normal(np.zeros(d),S,(n,))
return m + z/np.sqrt(x)[:,None]
# same output format as random.multivariate_normal
示例13: _set_mu_prior
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _set_mu_prior(self, mu_prior):
if mu_prior is None:
self._mu_prior_ = np.zeros((self.n_components, self.n_features))
else:
mu_prior = np.asarray(mu_prior)
mu_prior = mu_prior.reshape(self.n_unique, self.n_features)
if mu_prior.shape == (self.n_unique, self.n_features):
for u in range(self.n_unique):
for t in range(self.n_chain):
self._mu_prior[u*(self.n_chain)+t] = mu_prior[u].copy()
else:
raise ValueError("cannot match shape of mu_prior")
示例14: _set_var_prior
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _set_var_prior(self, var_prior):
var_prior = np.asarray(var_prior)
if self.n_features == 1:
self._set_precision_prior(1.0 / var_prior)
else:
self._set_precision_prior(np.linalg.inv(var_prior))
示例15: _get_fft_shape
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import asarray [as 别名]
def _get_fft_shape(im_or_shape1, im_or_shape2, padding=3, axes=None, max=False):
"""Return the fast fft shapes for each spatial axis
Calculate the fast fft shape for each dimension in
axes.
"""
if hasattr(im_or_shape1, "shape"):
shape1 = np.asarray(im_or_shape1.shape)
else:
shape1 = np.asarray(im_or_shape1)
if hasattr(im_or_shape2, "shape"):
shape2 = np.asarray(im_or_shape2.shape)
else:
shape2 = np.asarray(im_or_shape2)
# Make sure the shapes are the same size
if len(shape1) != len(shape2):
msg = (
"img1 and img2 must have the same number of dimensions, but got {0} and {1}"
)
raise ValueError(msg.format(len(shape1), len(shape2)))
# Set the combined shape based on the total dimensions
if axes is None:
if max:
shape = np.max([shape1, shape2], axis=1)
else:
shape = shape1 + shape2
else:
shape = np.zeros(len(axes), dtype='int')
try:
len(axes)
except TypeError:
axes = [axes]
for n, ax in enumerate(axes):
shape[n] = shape1[ax] + shape2[ax]
if max == True:
shape[n] = np.max([shape1[ax], shape2[ax]])
shape += padding
# Use the next fastest shape in each dimension
shape = [fftpack.helper.next_fast_len(s) for s in shape]
# autograd.numpy.fft does not currently work
# if the last dimension is odd
while shape[-1] % 2 != 0:
shape[-1] += 1
shape[-1] = fftpack.helper.next_fast_len(shape[-1])
if shape2[-2] % 2 == 0:
while shape[-2] % 2 != 0:
shape[-2] += 1
shape[-2] = fftpack.helper.next_fast_len(shape[-2])
return shape