本文整理汇总了Python中autograd.numpy.expand_dims方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.expand_dims方法的具体用法?Python numpy.expand_dims怎么用?Python numpy.expand_dims使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autograd.numpy
的用法示例。
在下文中一共展示了numpy.expand_dims方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_mcl_normal_direction_at_chord_fraction
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def get_mcl_normal_direction_at_chord_fraction(self, chord_fraction):
# Returns the normal direction of the mean camber line at a specified chord fraction.
# If you input a single value, returns a 1D numpy array with 2 elements (x,y).
# If you input a vector of values, returns a 2D numpy array. First index is the point number, second index is (x,y)
# Right now, does it by finite differencing camber values :(
# When I'm less lazy I'll make it do it in a proper, more efficient way
# TODO make this not finite difference
epsilon = np.sqrt(np.finfo(float).eps)
cambers = self.get_camber_at_chord_fraction(chord_fraction)
cambers_incremented = self.get_camber_at_chord_fraction(chord_fraction + epsilon)
dydx = (cambers_incremented - cambers) / epsilon
if dydx.shape == 1: # single point
normal = np.hstack((-dydx, 1))
normal /= np.linalg.norm(normal)
return normal
else: # multiple points vectorized
normal = np.column_stack((-dydx, np.ones(dydx.shape)))
normal /= np.expand_dims(np.linalg.norm(normal, axis=1), axis=1) # normalize
return normal
示例2: compute_rotation_velocity_geometry_axes
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def compute_rotation_velocity_geometry_axes(self, points):
# Computes the effective velocity due to rotation at a set of points.
# Input: a Nx3 array of points
# Output: a Nx3 array of effective velocities
angular_velocity_vector_geometry_axes = np.array(
[-self.p, self.q, -self.r]) # signs convert from body axes to geometry axes
angular_velocity_vector_geometry_axes = np.expand_dims(angular_velocity_vector_geometry_axes, axis=0)
rotation_velocity_geometry_axes = np.cross(
angular_velocity_vector_geometry_axes,
points,
axis=1
)
rotation_velocity_geometry_axes = -rotation_velocity_geometry_axes # negative sign, since we care about the velocity the WING SEES, not the velocity of the wing.
return rotation_velocity_geometry_axes
示例3: callback
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def callback(params, t, g):
print("Iteration {} lower bound {}".format(t, -objective(params, t)))
# Sample functions from posterior.
rs = npr.RandomState(0)
mean, log_std = unpack_params(params)
#rs = npr.RandomState(0)
sample_weights = rs.randn(10, num_weights) * np.exp(log_std) + mean
plot_inputs = np.linspace(-8, 8, num=400)
outputs = predictions(sample_weights, np.expand_dims(plot_inputs, 1))
# Plot data and functions.
plt.cla()
ax.plot(inputs.ravel(), targets.ravel(), 'bx')
ax.plot(plot_inputs, outputs[:, :, 0].T)
ax.set_ylim([-2, 3])
plt.draw()
plt.pause(1.0/60.0)
# Initialize variational parameters
示例4: _calc_pareto_front
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def _calc_pareto_front(self, ref_dirs, *args, **kwargs):
F = super()._calc_pareto_front(ref_dirs, *args, **kwargs)
a = anp.sqrt(anp.sum(F ** 2, 1) - 3 / 4 * anp.max(F ** 2, axis=1))
a = anp.expand_dims(a, axis=1)
a = anp.tile(a, [1, ref_dirs.shape[1]])
F = F / a
return F
示例5: constraint_c4_cylindrical
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def constraint_c4_cylindrical(f, r): # cylindrical
l = anp.mean(f, axis=1)
l = anp.expand_dims(l, axis=1)
g = -anp.sum(anp.power(f - l, 2), axis=1) + anp.power(r, 2)
return g
示例6: get_sharp_TE_airfoil
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def get_sharp_TE_airfoil(self):
# Returns a version of the airfoil with a sharp trailing edge.
upper_original_coors = self.upper_coordinates() # Note: includes leading edge point, be careful about duplicates
lower_original_coors = self.lower_coordinates() # Note: includes leading edge point, be careful about duplicates
# Find data about the TE
# Get the scale factor
x_mcl = self.mcl_coordinates[:, 0]
x_max = np.max(x_mcl)
x_min = np.min(x_mcl)
scale_factor = (x_mcl - x_min) / (x_max - x_min) # linear contraction
# Do the contraction
upper_minus_mcl_adjusted = self.upper_minus_mcl - self.upper_minus_mcl[-1, :] * np.expand_dims(scale_factor, 1)
# Recreate coordinates
upper_coordinates_adjusted = np.flipud(self.mcl_coordinates + upper_minus_mcl_adjusted)
lower_coordinates_adjusted = self.mcl_coordinates - upper_minus_mcl_adjusted
coordinates = np.vstack((
upper_coordinates_adjusted[:-1, :],
lower_coordinates_adjusted
))
# Make a new airfoil with the coordinates
name = self.name + ", with sharp TE"
new_airfoil = Airfoil(name=name, coordinates=coordinates, repanel=False)
return new_airfoil
示例7: angle_axis_rotation_matrix
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def angle_axis_rotation_matrix(angle, axis, axis_already_normalized=False):
# Gives the rotation matrix from an angle and an axis.
# An implmentation of https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
# Inputs:
# * angle: can be one angle or a vector (1d ndarray) of angles. Given in radians.
# * axis: a 1d numpy array of length 3 (x,y,z). Represents the angle.
# * axis_already_normalized: boolean, skips normalization for speed if you flag this true.
# Outputs:
# * If angle is a scalar, returns a 3x3 rotation matrix.
# * If angle is a vector, returns a 3x3xN rotation matrix.
if not axis_already_normalized:
axis = axis / np.linalg.norm(axis)
sintheta = np.sin(angle)
costheta = np.cos(angle)
cpm = np.array(
[[0, -axis[2], axis[1]],
[axis[2], 0, -axis[0]],
[-axis[1], axis[0], 0]]
) # The cross product matrix of the rotation axis vector
outer_axis = np.outer(axis, axis)
angle = np.array(angle) # make sure angle is a ndarray
if len(angle.shape) == 0: # is a scalar
rot_matrix = costheta * np.eye(3) + sintheta * cpm + (1 - costheta) * outer_axis
return rot_matrix
else: # angle is assumed to be a 1d ndarray
rot_matrix = costheta * np.expand_dims(np.eye(3), 2) + sintheta * np.expand_dims(cpm, 2) + (
1 - costheta) * np.expand_dims(outer_axis, 2)
return rot_matrix
示例8: taylor_approx
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def taylor_approx(target, stencil, values):
"""Use taylor series to approximate up to second order derivatives.
Args:
target: An array of shape (..., n), a batch of n-dimensional points
where one wants to approximate function value and derivatives.
stencil: An array of shape broadcastable to (..., k, n), for each target
point a set of k = triangle(n + 1) points to use on its approximation.
values: An array of shape broadcastable to (..., k), the function value at
each of the stencil points.
Returns:
An array of shape (..., k), for each target point the approximated
function value, gradient and hessian evaluated at that point (flattened
and in the same order as returned by derivative_names).
"""
# Broadcast arrays to their required shape.
batch_shape, ndim = target.shape[:-1], target.shape[-1]
stencil = np.broadcast_to(stencil, batch_shape + (triangular(ndim + 1), ndim))
values = np.broadcast_to(values, stencil.shape[:-1])
# Subtract target from each stencil point.
delta_x = stencil - np.expand_dims(target, axis=-2)
delta_xy = np.matmul(
np.expand_dims(delta_x, axis=-1), np.expand_dims(delta_x, axis=-2))
i = np.arange(ndim)
j, k = np.triu_indices(ndim, k=1)
# Build coefficients for the Taylor series equations, namely:
# f(stencil) = coeffs @ [f(target), df/d0(target), ...]
coeffs = np.concatenate([
np.ones(delta_x.shape[:-1] + (1,)), # f(target)
delta_x, # df/di(target)
delta_xy[..., i, i] / 2, # d^2f/di^2(target)
delta_xy[..., j, k], # d^2f/{dj dk}(target)
], axis=-1)
# Then: [f(target), df/d0(target), ...] = coeffs^{-1} @ f(stencil)
return np.squeeze(
np.matmul(np.linalg.inv(coeffs), values[..., np.newaxis]), axis=-1)
示例9: non_uniform_approx_nearest
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def non_uniform_approx_nearest(points, values):
"""Approximate derivatives using nearest points in non-uniform grid."""
ndim = points.shape[-1]
k = triangular(ndim + 1)
diffs = np.expand_dims(points, axis=0) - np.expand_dims(points, axis=1)
norms = np.linalg.norm(diffs, axis=-1)
nearest_k = np.argpartition(norms, k)[..., :k]
return taylor_approx(points, points[nearest_k], values[nearest_k])
示例10: rbf_covariance
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def rbf_covariance(kernel_params, x, xp):
output_scale = np.exp(kernel_params[0])
lengthscales = np.exp(kernel_params[1:])
diffs = np.expand_dims(x /lengthscales, 1)\
- np.expand_dims(xp/lengthscales, 0)
return output_scale * np.exp(-0.5 * np.sum(diffs**2, axis=2))
示例11: make_nn_funs
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def make_nn_funs(layer_sizes, L2_reg, noise_variance, nonlinearity=np.tanh):
"""These functions implement a standard multi-layer perceptron,
vectorized over both training examples and weight samples."""
shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))
num_weights = sum((m+1)*n for m, n in shapes)
def unpack_layers(weights):
num_weight_sets = len(weights)
for m, n in shapes:
yield weights[:, :m*n] .reshape((num_weight_sets, m, n)),\
weights[:, m*n:m*n+n].reshape((num_weight_sets, 1, n))
weights = weights[:, (m+1)*n:]
def predictions(weights, inputs):
"""weights is shape (num_weight_samples x num_weights)
inputs is shape (num_datapoints x D)"""
inputs = np.expand_dims(inputs, 0)
for W, b in unpack_layers(weights):
outputs = np.einsum('mnd,mdo->mno', inputs, W) + b
inputs = nonlinearity(outputs)
return outputs
def logprob(weights, inputs, targets):
log_prior = -L2_reg * np.sum(weights**2, axis=1)
preds = predictions(weights, inputs)
log_lik = -np.sum((preds - targets)**2, axis=1)[:, 0] / noise_variance
return log_prior + log_lik
return num_weights, predictions, logprob
示例12: covgrad
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def covgrad(x, mean, cov, allow_singular=False):
if allow_singular:
raise NotImplementedError("The multivariate normal pdf is not "
"differentiable w.r.t. a singular covariance matix")
J = np.linalg.inv(cov)
solved = np.matmul(J, np.expand_dims(x - mean, -1))
return 1./2 * (generalized_outer_product(solved) - J)
示例13: fwd_grad_logsumexp
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def fwd_grad_logsumexp(g, ans, x, axis=None, b=1.0, keepdims=False):
if not keepdims:
if isinstance(axis, int):
ans = np.expand_dims(ans, axis)
elif isinstance(axis, tuple):
for ax in sorted(axis):
ans = np.expand_dims(ans, ax)
return np.sum(g * b * np.exp(x - ans), axis=axis, keepdims=keepdims)
示例14: draw
# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import expand_dims [as 别名]
def draw(self):
# Draw the airplane in a new window.
# Using PyVista Polydata format
vertices = np.empty((0, 3))
faces = np.empty((0))
for wing in self.wings:
wing_vertices = np.empty((0, 3))
wing_tri_faces = np.empty((0, 4))
wing_quad_faces = np.empty((0, 5))
for i in range(len(wing.xsecs) - 1):
is_last_section = i == len(wing.xsecs) - 2
le_start = wing.xsecs[i].xyz_le + wing.xyz_le
te_start = wing.xsecs[i].xyz_te() + wing.xyz_le
wing_vertices = np.vstack((wing_vertices, le_start, te_start))
wing_quad_faces = np.vstack((
wing_quad_faces,
np.expand_dims(np.array([4, 2 * i + 0, 2 * i + 1, 2 * i + 3, 2 * i + 2]), 0)
))
if is_last_section:
le_end = wing.xsecs[i + 1].xyz_le + wing.xyz_le
te_end = wing.xsecs[i + 1].xyz_te() + wing.xyz_le
wing_vertices = np.vstack((wing_vertices, le_end, te_end))
vertices_starting_index = len(vertices)
wing_quad_faces_reformatted = np.ndarray.copy(wing_quad_faces)
wing_quad_faces_reformatted[:, 1:] = wing_quad_faces[:, 1:] + vertices_starting_index
wing_quad_faces_reformatted = np.reshape(wing_quad_faces_reformatted, (-1), order='C')
vertices = np.vstack((vertices, wing_vertices))
faces = np.hstack((faces, wing_quad_faces_reformatted))
if wing.symmetric:
vertices_starting_index = len(vertices)
wing_vertices = reflect_over_XZ_plane(wing_vertices)
wing_quad_faces_reformatted = np.ndarray.copy(wing_quad_faces)
wing_quad_faces_reformatted[:, 1:] = wing_quad_faces[:, 1:] + vertices_starting_index
wing_quad_faces_reformatted = np.reshape(wing_quad_faces_reformatted, (-1), order='C')
vertices = np.vstack((vertices, wing_vertices))
faces = np.hstack((faces, wing_quad_faces_reformatted))
plotter = pv.Plotter()
wing_surfaces = pv.PolyData(vertices, faces)
plotter.add_mesh(wing_surfaces, color='#7EFC8F', show_edges=True, smooth_shading=True)
xyz_ref = pv.PolyData(self.xyz_ref)
plotter.add_points(xyz_ref, color='#50C7C7', point_size=10)
plotter.show_grid(color='#444444')
plotter.set_background(color="black")
plotter.show(cpos=(-1, -1, 1), full_screen=False)