本文整理汇总了Python中autograd.numpy.sum方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.sum方法的具体用法?Python numpy.sum怎么用?Python numpy.sum使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autograd.numpy
的用法示例。
在下文中一共展示了numpy.sum方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _evaluate
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def _evaluate(self, x, out, *args, **kwargs):
l = []
for j in range(self.n_var):
l.append((j + 1) * x[:, j] ** 2)
sum_jx = anp.sum(anp.column_stack(l), axis=1)
a = anp.sum(anp.cos(x) ** 4, axis=1)
b = 2 * anp.prod(anp.cos(x) ** 2, axis=1)
c = (anp.sqrt(sum_jx)).flatten()
c = c + (c == 0) * 1e-20
f = -anp.absolute((a - b) / c)
# Constraints
g1 = -anp.prod(x, 1) + 0.75
g2 = anp.sum(x, axis=1) - 7.5 * self.n_var
out["F"] = f
out["G"] = anp.column_stack([g1, g2])
示例2: __init__
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def __init__(self, n_var=2, n_constr=1, option="linear"):
super().__init__(n_var=n_var, n_obj=2, n_constr=n_constr, xl=0, xu=1, type_var=anp.double)
def g_linear(x):
return 1 + anp.sum(x, axis=1)
def g_multimodal(x):
A = 10
return 1 + A * x.shape[1] + anp.sum(x ** 2 - A * anp.cos(2 * anp.pi * x), axis=1)
if option == "linear":
self.calc_g = g_linear
elif option == "multimodal":
self.calc_g = g_multimodal
self.xl[:, 1:] = -5.12
self.xu[:, 1:] = 5.12
else:
print("Unknown option for CTP single.")
示例3: _evaluate
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def _evaluate(self, x, out, *args, **kwargs):
f1 = - (25 * (x[:, 0] - 2) ** 2 + (x[:, 1] - 2) ** 2 + (x[:, 2] - 1) ** 2 + (x[:, 3] - 4) ** 2 + (
x[:, 4] - 1) ** 2)
f2 = anp.sum(anp.square(x), axis=1)
g1 = (x[:, 0] + x[:, 1] - 2.0) / 2.0
g2 = (6.0 - x[:, 0] - x[:, 1]) / 6.0
g3 = (2.0 - x[:, 1] + x[:, 0]) / 2.0
g4 = (2.0 - x[:, 0] + 3.0 * x[:, 1]) / 2.0
g5 = (4.0 - (x[:, 2] - 3.0) ** 2 - x[:, 3]) / 4.0
g6 = ((x[:, 4] - 3.0) ** 2 + x[:, 5] - 4.0) / 4.0
out["F"] = anp.column_stack([f1, f2])
out["G"] = anp.column_stack([g1, g2, g3, g4, g5, g6])
out["G"] = - out["G"]
示例4: _evaluate
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def _evaluate(self, x, out, *args, **kwargs):
_x = [x[:, :30]]
for i in range(self.m - 1):
_x.append(x[:, 30 + i * self.n: 30 + (i + 1) * self.n])
u = anp.column_stack([x_i.sum(axis=1) for x_i in _x])
v = (2 + u) * (u < self.n) + 1 * (u == self.n)
g = v[:, 1:].sum(axis=1)
f1 = 1 + u[:, 0]
f2 = g * (1 / f1)
if self.normalize:
f1 = normalize(f1, 1, 31)
f2 = normalize(f2, (self.m-1) * 1/31, (self.m-1))
out["F"] = anp.column_stack([f1, f2])
示例5: get_loss
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def get_loss(self, model):
"""Computes the loss/fidelity of a given model wrt to the observation
Parameters
----------
model: array
The model from `Blend`
Returns
-------
result: array
Scalar tensor with the likelihood of the model
given the image data
"""
model_ = self.render(model)
if self.frame != self.model_frame:
images_ = self.images[self.slices_for_images]
weights_ = self.weights[self.slices_for_images]
else:
images_ = self.images
weights_ = self.weights
return self.log_norm + np.sum(weights_ * (model_ - images_) ** 2) / 2
示例6: log_norm
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def log_norm(self):
try:
return self._log_norm
except AttributeError:
if self.frame != self.model_frame:
images_ = self.images[self.slices_for_images]
weights_ = self.weights[self.slices_for_images]
else:
images_ = self.images
weights_ = self.weights
# normalization of the single-pixel likelihood:
# 1 / [(2pi)^1/2 (sigma^2)^1/2]
# with inverse variance weights: sigma^2 = 1/weight
# full likelihood is sum over all data samples: pixel in images
# NOTE: this assumes that all pixels are used in likelihood!
log_sigma = np.zeros(weights_.shape, dtype=self.weights.dtype)
cuts = weights_ > 0
log_sigma[cuts] = np.log(1 / weights_[cuts])
self._log_norm = (
np.prod(images_.shape) / 2 * np.log(2 * np.pi)
+ np.sum(log_sigma) / 2
)
return self._log_norm
示例7: objective
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def objective(self, w):
obj = 0
N = float(sum([np.sum(d[1]) for d in self.data_list]))
for F,S in self.data_list:
psi = np.dot(F, w)
lam = self.link(psi)
obj -= np.sum(S * np.log(lam) -lam*self.dt) / N
# assert np.isfinite(ll)
# Add penalties
obj += (0.5 * np.sum(w[1:]**2) / self.sigma**2) / N
obj += np.sum(np.abs(w[1:]) * self.lmbda) / N
# assert np.isfinite(obj)
return obj
示例8: G
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def G(self):
full_W = np.array([node.w for node in self.nodes])
WB = full_W[:,1:].reshape((self.K,self.K, self.B))
# Weight matrix is summed over impulse response functions
WT = WB.sum(axis=2)
# Impulse response weights are normalized weights
GT = WB / WT[:,:,None]
# Then we transpose so that the impuolse matrix is (outgoing x incoming x basis)
G = np.transpose(GT, [1,0,2])
# TODO: Decide if this is still necessary
for k1 in range(self.K):
for k2 in range(self.K):
if G[k1,k2,:].sum() < 1e-2:
G[k1,k2,:] = 1.0/self.B
return G
示例9: get_treeseq_configs
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def get_treeseq_configs(treeseq, sampled_n):
mat = np.zeros((len(sampled_n), sum(sampled_n)), dtype=int)
j = 0
for i, n in enumerate(sampled_n):
for _ in range(n):
mat[i, j] = 1
j += 1
mat = scipy.sparse.csr_matrix(mat)
def get_config(genos):
derived_counts = mat.dot(genos)
return np.array([
sampled_n - derived_counts,
derived_counts
]).T
for v in treeseq.variants():
yield get_config(v.genotypes)
示例10: resample
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [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)
示例11: _entropy
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def _entropy(self):
counts = self._total_freqs
n_snps = float(self.n_snps())
p = counts / n_snps
# return np.sum(p * np.log(p))
ret = np.sum(p * np.log(p))
# correct for missing data
sampled_n = np.sum(self.configs.value, axis=2)
sampled_n_counts = co.Counter()
assert len(counts) == len(sampled_n)
for c, n in zip(counts, sampled_n):
n = tuple(n)
sampled_n_counts[n] += c
sampled_n_counts = np.array(
list(sampled_n_counts.values()), dtype=float)
ret = ret + np.sum(sampled_n_counts / n_snps *
np.log(n_snps / sampled_n_counts))
assert not np.isnan(ret)
return ret
示例12: _build_old_new_idxs
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def _build_old_new_idxs(self, folded):
idxs = self.full_configs._augmented_idxs(folded)
denom_idx_key = 'denom_idx'
denom_idx = idxs[denom_idx_key]
idxs = {k: v[self.sub_idxs]
for k, v in list(idxs.items()) if k != denom_idx_key}
old_idxs = np.array(
list(set(sum(map(list, idxs.values()), [denom_idx]))))
old_2_new_idxs = {old_id: new_id for new_id,
old_id in enumerate(old_idxs)}
idxs = {k: np.array([old_2_new_idxs[old_id]
for old_id in v], dtype=int)
for k, v in list(idxs.items())}
idxs[denom_idx_key] = old_2_new_idxs[denom_idx]
return old_idxs, idxs
示例13: _many_score_cov
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def _many_score_cov(params, data, demo_func, **kwargs):
params = np.array(params)
def f_vec(x):
ret = _composite_log_likelihood(
data, demo_func(*x), vector=True, **kwargs)
# centralize
return ret - np.mean(ret)
# g_out = einsum('ij,ik', jacobian(f_vec)(params), jacobian(f_vec)(params))
# but computed in a roundabout way because jacobian implementation is slow
def _g_out_antihess(x):
l = f_vec(x)
lc = make_constant(l)
return np.sum(0.5 * (l**2 - l * lc - lc * l))
return autograd.hessian(_g_out_antihess)(params)
示例14: sfs
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def sfs(self, n):
if n == 0:
return np.array([0.])
Et_jj = self.etjj(n)
#assert np.all(Et_jj[:-1] - Et_jj[1:] >= 0.0) and np.all(Et_jj >= 0.0) and np.all(Et_jj <= self.tau)
ret = np.sum(Et_jj[:, None] * Wmatrix(n), axis=0)
before_tmrca = self.tau - np.sum(ret * np.arange(1, n) / n)
# ignore branch length above untruncated TMRCA
if self.tau == float('inf'):
before_tmrca = 0.0
ret = np.concatenate((np.array([0.0]), ret, np.array([before_tmrca])))
return ret
# def transition_prob(self, v, axis=0):
# return moran_model.moran_action(self.scaled_time, v, axis=axis)
示例15: _mut_factor_het
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import sum [as 别名]
def _mut_factor_het(sfs, demo, mut_rate, vector, p_missing):
mut_rate = mut_rate * np.ones(sfs.n_loci)
E_het = expected_heterozygosity(
demo,
restrict_to_pops=np.array(
sfs.sampled_pops)[sfs.ascertainment_pop])
p_missing = p_missing * np.ones(len(sfs.ascertainment_pop))
p_missing = p_missing[sfs.ascertainment_pop]
lambd = np.einsum("i,j->ij", mut_rate, E_het * (1.0 - p_missing))
counts = sfs.avg_pairwise_hets[:, sfs.ascertainment_pop]
ret = -lambd + counts * np.log(lambd) - scipy.special.gammaln(counts + 1)
ret = ret * sfs.sampled_n[sfs.ascertainment_pop] / float(
np.sum(sfs.sampled_n[sfs.ascertainment_pop]))
if not vector:
ret = np.sum(ret)
else:
ret = np.sum(ret, axis=1)
return ret