本文整理汇总了Python中autograd.numpy.transpose方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.transpose方法的具体用法?Python numpy.transpose怎么用?Python numpy.transpose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autograd.numpy
的用法示例。
在下文中一共展示了numpy.transpose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: G
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [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
示例2: _process_event
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def _process_event(self, event):
e_type = self.demo._event_type(event)
if e_type == 'leaf':
self._process_leaf_likelihood(event)
elif e_type == 'merge_subpops':
self._process_merge_subpops_likelihood(event)
elif e_type == 'merge_clusters':
self._process_merge_clusters_likelihood(event)
elif e_type == 'pulse':
self._process_pulse_likelihood(event)
else:
raise Exception("Unrecognized event type.")
for newpop in self.demo._parent_pops(event):
lik = self._get_likelihoods(newpop)
lik.make_last_axis(newpop)
n = lik.get_last_axis_n()
if n > 0:
lik.add_last_axis_sfs(self.demo._truncated_sfs(newpop))
if event != self.demo._event_root:
lik.matmul_last_axis(
np.transpose(moran_transition(
self.demo._scaled_time(newpop), n)))
示例3: _get_subsample_counts
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def _get_subsample_counts(configs, n):
subconfigs, weights = [], []
for pop_comb in it.combinations_with_replacement(configs.sampled_pops, n):
subsample_n = co.Counter(pop_comb)
subsample_n = np.array([subsample_n[pop]
for pop in configs.sampled_pops], dtype=int)
if np.any(subsample_n > configs.sampled_n):
continue
for sfs_entry in it.product(*(range(sub_n + 1)
for sub_n in subsample_n)):
sfs_entry = np.array(sfs_entry, dtype=int)
if np.all(sfs_entry == 0) or np.all(sfs_entry == subsample_n):
# monomorphic
continue
sfs_entry = np.transpose([subsample_n - sfs_entry, sfs_entry])
cnt_vec = configs.subsample_probs(sfs_entry)
if not np.all(cnt_vec == 0):
subconfigs.append(sfs_entry)
weights.append(cnt_vec)
return np.array(subconfigs), np.array(weights)
示例4: build_config_list
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def build_config_list(sampled_pops, counts, sampled_n=None, ascertainment_pop=None):
"""
if sampled_n is not None, counts is the derived allele counts
if sampled_n is None, counts has an extra trailing axis:
counts[...,0] is ancestral allele count,
counts[...,1] is derived allele count
"""
if sampled_n is not None:
sampled_n = np.array(sampled_n, dtype=int)
counts1 = np.array(counts, dtype=int, ndmin=2)
counts0 = sampled_n - counts1
counts = np.array([counts0, counts1], dtype=int)
counts = np.transpose(counts, axes=[1, 2, 0])
counts = np.array(counts, ndmin=3, dtype=int)
assert counts.shape[1:] == (len(sampled_pops), 2)
counts.setflags(write=False)
return ConfigList(sampled_pops, counts, sampled_n, ascertainment_pop)
示例5: W
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def W(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)
# Then we transpose so that the weight matrix is (outgoing x incoming)
W = WT.T
return W
示例6: check_symmetric
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def check_symmetric(X):
Xt = np.transpose(X)
assert np.allclose(X, Xt)
return 0.5 * (X + Xt)
示例7: check_psd
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def check_psd(X, **tol_kwargs):
X = check_symmetric(X)
d, U = np.linalg.eigh(X)
d = truncate0(d, **tol_kwargs)
ret = np.dot(U, np.dot(np.diag(d), np.transpose(U)))
#assert np.allclose(ret, X)
return np.array(ret, ndmin=2)
示例8: make_last_axis
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def make_last_axis(self, pop):
axis = self.pop_axis(pop)
perm = [i for i in range(self.n_axes)
if i != axis] + [axis]
self.liks = np.transpose(self.liks, perm)
self.pop_labels = [p for p in self.pop_labels if p != pop] + [pop]
assert len(self.pop_labels) + 1 == len(self.liks.shape)
示例9: _vecs_and_idxs
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def _vecs_and_idxs(self, folded):
augmented_configs = self._augmented_configs(folded)
augmented_idxs = self._augmented_idxs(folded)
# construct the vecs
vecs = [np.zeros((len(augmented_configs), n + 1))
for n in self.sampled_n]
for i in range(len(vecs)):
n = self.sampled_n[i]
derived = np.einsum(
"i,j->ji", np.ones(len(augmented_configs)), np.arange(n + 1))
curr = scipy.stats.hypergeom.pmf(
k=augmented_configs[:, i, 1],
M=n,
n=derived,
N=augmented_configs[:, i].sum(1)
)
assert not np.any(np.isnan(curr))
vecs[i] = np.transpose(curr)
# copy augmented_idxs to make it safe
return vecs, dict(augmented_idxs)
# def _config_str_iter(self):
# for c in self.value:
# yield _config2hashable(c)
示例10: _transpose
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def _transpose(in_arr, in_sublist, out_sublist):
if set(in_sublist) != set(out_sublist):
raise ValueError("Input and output subscripts don't match")
for sublist in (in_sublist, out_sublist):
if len(set(sublist)) != len(sublist):
raise NotImplementedError("Repeated subscripts not implemented")
in_idxs = {k:v for v,k in enumerate(in_sublist)}
return np.transpose(in_arr, axes=[in_idxs[s] for s in out_sublist])
示例11: test_grad
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def test_grad():
p = .05
def fun0(B, Bdims):
return einsum2.einsum2(np.exp(B**2), Bdims, np.transpose(B), Bdims[::-1], [])
def fun1(B, Bdims):
if Bdims: Bdims = list(range(len(Bdims)))
return np.einsum(np.exp(B**2), Bdims,
np.transpose(B), Bdims[::-1], [])
grad0 = autograd.grad(fun0)
grad1 = autograd.grad(fun1)
B, Bdims = random_tensor(p)
assert np.allclose(grad0(B, Bdims), grad1(B, Bdims))
示例12: add_control_surface
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def add_control_surface(self, deflection=0., hinge_point=0.75):
# Returns a version of the airfoil with a control surface added at a given point.
# Inputs:
# # deflection: the deflection angle, in degrees. Downwards-positive.
# # hinge_point: the location of the hinge, as a fraction of chord.
# Make the rotation matrix for the given angle.
sintheta = np.sin(np.radians(-deflection))
costheta = np.cos(np.radians(-deflection))
rotation_matrix = np.array(
[[costheta, -sintheta],
[sintheta, costheta]]
)
# Find the hinge point
hinge_point = np.array(
(hinge_point, self.get_camber_at_chord_fraction(hinge_point))) # Make hinge_point a vector.
# Split the airfoil into the sections before and after the hinge
split_index = np.where(self.mcl_coordinates[:, 0] > hinge_point[0])[0][0]
mcl_coordinates_before = self.mcl_coordinates[:split_index, :]
mcl_coordinates_after = self.mcl_coordinates[split_index:, :]
upper_minus_mcl_before = self.upper_minus_mcl[:split_index, :]
upper_minus_mcl_after = self.upper_minus_mcl[split_index:, :]
# Rotate the mean camber line (MCL) and "upper minus mcl"
new_mcl_coordinates_after = np.transpose(
rotation_matrix @ np.transpose(mcl_coordinates_after - hinge_point)) + hinge_point
new_upper_minus_mcl_after = np.transpose(rotation_matrix @ np.transpose(upper_minus_mcl_after))
# Do blending
# Assemble airfoil
new_mcl_coordinates = np.vstack((mcl_coordinates_before, new_mcl_coordinates_after))
new_upper_minus_mcl = np.vstack((upper_minus_mcl_before, new_upper_minus_mcl_after))
upper_coordinates = np.flipud(new_mcl_coordinates + new_upper_minus_mcl)
lower_coordinates = new_mcl_coordinates - new_upper_minus_mcl
coordinates = np.vstack((upper_coordinates, lower_coordinates[1:, :]))
new_airfoil = Airfoil(name=self.name + " flapped", coordinates=coordinates, repanel=False)
return new_airfoil # TODO fix self-intersecting airfoils at high deflections
示例13: convolve
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def convolve(A, B, axes=None, dot_axes=[(),()], mode='full'):
assert mode in ['valid', 'full'], "Mode {0} not yet implemented".format(mode)
if axes is None:
axes = [list(range(A.ndim)), list(range(A.ndim))]
wrong_order = any([B.shape[ax_B] < A.shape[ax_A] for ax_A, ax_B in zip(*axes)])
if wrong_order:
if mode=='valid' and not all([B.shape[ax_B] <= A.shape[ax_A] for ax_A, ax_B in zip(*axes)]):
raise Exception("One array must be larger than the other along all convolved dimensions")
elif mode != 'full' or B.size <= A.size: # Tie breaker
i1 = B.ndim - len(dot_axes[1]) - len(axes[1]) # B ignore
i2 = i1 + A.ndim - len(dot_axes[0]) - len(axes[0]) # A ignore
i3 = i2 + len(axes[0])
ignore_B = list(range(i1))
ignore_A = list(range(i1, i2))
conv = list(range(i2, i3))
return convolve(B, A, axes=axes[::-1], dot_axes=dot_axes[::-1], mode=mode).transpose(ignore_A + ignore_B + conv)
if mode == 'full':
B = pad_to_full(B, A, axes[::-1])
B_view_shape = list(B.shape)
B_view_strides = list(B.strides)
flipped_idxs = [slice(None)] * A.ndim
for ax_A, ax_B in zip(*axes):
B_view_shape.append(abs(B.shape[ax_B] - A.shape[ax_A]) + 1)
B_view_strides.append(B.strides[ax_B])
B_view_shape[ax_B] = A.shape[ax_A]
flipped_idxs[ax_A] = slice(None, None, -1)
B_view = as_strided(B, B_view_shape, B_view_strides)
A_view = A[tuple(flipped_idxs)]
all_axes = [list(axes[i]) + list(dot_axes[i]) for i in [0, 1]]
return einsum_tensordot(A_view, B_view, all_axes)
示例14: grad_convolve
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def grad_convolve(argnum, ans, A, B, axes=None, dot_axes=[(),()], mode='full'):
assert mode in ['valid', 'full'], "Grad for mode {0} not yet implemented".format(mode)
axes, shapes = parse_axes(A.shape, B.shape, axes, dot_axes, mode)
if argnum == 0:
X, Y = A, B
_X_, _Y_ = 'A', 'B'
ignore_Y = 'ignore_B'
elif argnum == 1:
X, Y = B, A
_X_, _Y_ = 'B', 'A'
ignore_Y = 'ignore_A'
else:
raise NotImplementedError("Can't take grad of convolve w.r.t. arg {0}".format(argnum))
if mode == 'full':
new_mode = 'valid'
else:
if any([x_size > y_size for x_size, y_size in zip(shapes[_X_]['conv'], shapes[_Y_]['conv'])]):
new_mode = 'full'
else:
new_mode = 'valid'
def vjp(g):
result = convolve(g, Y[flipped_idxs(Y.ndim, axes[_Y_]['conv'])],
axes = [axes['out']['conv'], axes[_Y_]['conv']],
dot_axes = [axes['out'][ignore_Y], axes[_Y_]['ignore']],
mode = new_mode)
new_order = npo.argsort(axes[_X_]['ignore'] + axes[_X_]['dot'] + axes[_X_]['conv'])
return np.transpose(result, new_order)
return vjp
示例15: _vjp_sqrtm
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import transpose [as 别名]
def _vjp_sqrtm(ans, A, disp=True, blocksize=64):
assert disp, "sqrtm vjp not implemented for disp=False"
ans_transp = anp.transpose(ans)
def vjp(g):
return anp.real(solve_sylvester(ans_transp, ans_transp, g))
return vjp