本文整理汇总了Python中tensorflow.meshgrid方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.meshgrid方法的具体用法?Python tensorflow.meshgrid怎么用?Python tensorflow.meshgrid使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.meshgrid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: encode_coordinates_fn
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def encode_coordinates_fn(self, net):
"""Adds one-hot encoding of coordinates to different views in the networks.
For each "pixel" of a feature map it adds a onehot encoded x and y
coordinates.
Args:
net: a tensor of shape=[batch_size, height, width, num_features]
Returns:
a tensor with the same height and width, but altered feature_size.
"""
mparams = self._mparams['encode_coordinates_fn']
if mparams.enabled:
batch_size, h, w, _ = net.shape.as_list()
x, y = tf.meshgrid(tf.range(w), tf.range(h))
w_loc = slim.one_hot_encoding(x, num_classes=w)
h_loc = slim.one_hot_encoding(y, num_classes=h)
loc = tf.concat([h_loc, w_loc], 2)
loc = tf.tile(tf.expand_dims(loc, 0), [batch_size, 1, 1, 1])
return tf.concat([net, loc], 3)
else:
return net
示例2: yolo_boxes
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def yolo_boxes(pred, anchors, num_classes, training=True):
# pred: (batch_size, grid, grid, anchors, (x, y, w, h, obj, ...classes))
grid_size = tf.shape(pred)[1:3][::-1]
grid_y, grid_x = tf.shape(pred)[1], tf.shape(pred)[2]
box_xy, box_wh, objectness, class_probs = tf.split(pred, (2, 2, 1, num_classes), axis=-1)
box_xy = tf.sigmoid(box_xy)
objectness = tf.sigmoid(objectness)
class_probs = tf.nn.softmax(class_probs)
pred_box = tf.concat((box_xy, box_wh), axis=-1) # original xywh for loss
# !!! grid[x][y] == (y, x)
grid = tf.meshgrid(tf.range(grid_x), tf.range(grid_y))
grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2) # [gx, gy, 1, 2]
box_xy = (box_xy + tf.cast(grid, tf.float32)) / tf.cast(grid_size, tf.float32)
box_wh = tf.exp(box_wh) * anchors
box_x1y1 = box_xy - box_wh / 2
box_x2y2 = box_xy + box_wh / 2
bbox = tf.concat([box_x1y1, box_x2y2], axis=-1)
return bbox, objectness, class_probs, pred_box
示例3: get_cells
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def get_cells(self):
"""Returns the locations of all grid points in box.
Suppose start is -10 Angstrom, stop is 10 Angstrom, nbr_cutoff is 1.
Then would return a list of length 20^3 whose entries would be
[(-10, -10, -10), (-10, -10, -9), ..., (9, 9, 9)]
Returns
-------
cells: tf.Tensor
(n_cells, ndim) shape.
"""
start, stop, nbr_cutoff = self.start, self.stop, self.nbr_cutoff
mesh_args = [tf.range(start, stop, nbr_cutoff) for _ in range(self.ndim)]
return tf.cast(
tf.reshape(
tf.transpose(tf.stack(tf.meshgrid(*mesh_args))),
(self.n_cells, self.ndim)), tf.float32)
示例4: get_cells
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def get_cells(self):
"""Returns the locations of all grid points in box.
Suppose start is -10 Angstrom, stop is 10 Angstrom, nbr_cutoff is 1.
Then would return a list of length 20^3 whose entries would be
[(-10, -10, -10), (-10, -10, -9), ..., (9, 9, 9)]
Returns
-------
cells: tf.Tensor
(n_cells, ndim) shape.
"""
start, stop, nbr_cutoff = self.start, self.stop, self.nbr_cutoff
mesh_args = [tf.range(start, stop, nbr_cutoff) for _ in range(self.ndim)]
return tf.to_float(
tf.reshape(
tf.transpose(tf.stack(tf.meshgrid(*mesh_args))),
(self.n_cells, self.ndim)))
示例5: generate_anchors_pre
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def generate_anchors_pre(rpn_cls_score, feat_stride, anchor_scales=(8, 16, 32), anchor_ratios=(0.5, 1, 2)):
""" A wrapper function to generate anchors given different scales
Also return the number of anchors in variable 'length'
"""
height, width = rpn_cls_score.shape[1:3]
anchors = generate_anchors(ratios=np.array(anchor_ratios), scales=np.array(anchor_scales))
A = anchors.shape[0]
shift_x = np.arange(0, width) * feat_stride
shift_y = np.arange(0, height) * feat_stride
shift_x, shift_y = np.meshgrid(shift_x, shift_y)
shifts = np.vstack((shift_x.ravel(), shift_y.ravel(), shift_x.ravel(), shift_y.ravel())).transpose()
K = shifts.shape[0]
# width changes faster, so here it is H, W, C
anchors = anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2))
anchors = anchors.reshape((K * A, 4)).astype(np.float32, copy=False)
length = np.int32(anchors.shape[0])
return anchors, length
示例6: generate_anchors_pre_tf
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def generate_anchors_pre_tf(rpn_cls_score, feat_stride=16, anchor_scales=(8, 16, 32), anchor_ratios=(0.5, 1, 2)):
height = tf.shape(rpn_cls_score)[1]
width = tf.shape(rpn_cls_score)[2]
shift_x = tf.range(width) * feat_stride # width
shift_y = tf.range(height) * feat_stride # height
shift_x, shift_y = tf.meshgrid(shift_x, shift_y)
sx = tf.reshape(shift_x, shape=(-1,))
sy = tf.reshape(shift_y, shape=(-1,))
shifts = tf.transpose(tf.stack([sx, sy, sx, sy]))
K = tf.multiply(width, height)
shifts = tf.transpose(tf.reshape(shifts, shape=[1, K, 4]), perm=(1, 0, 2))
anchors = generate_anchors(ratios=np.array(anchor_ratios), scales=np.array(anchor_scales))
A = anchors.shape[0]
anchor_constant = tf.constant(anchors.reshape((1, A, 4)), dtype=tf.int32)
length = K * A
anchors_tf = tf.reshape(tf.add(anchor_constant, shifts), shape=(length, 4))
return tf.cast(anchors_tf, dtype=tf.float32), length
示例7: _multi_kmax_context_concat
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def _multi_kmax_context_concat(inputs, top_k, poses):
x, context_input = inputs
idxes, topk_vs = list(), list()
for p in poses:
val, idx = tf.nn.top_k(tf.slice(x, [0,0,0], [-1,-1, p]), k=top_k, sorted=True, name=None)
topk_vs.append(val)
idxes.append(idx)
concat_topk_max = tf.concat(topk_vs, -1, name='concat_val')
concat_topk_idx = tf.concat(idxes, -1, name='concat_idx')
# hack that requires the context to have the same shape as similarity matrices
# https://stackoverflow.com/questions/41897212/how-to-sort-a-multi-dimensional-tensor-using-the-returned-indices-of-tf-nn-top-k
shape = tf.shape(x)
mg = tf.meshgrid(*[tf.range(d) for d in (tf.unstack(shape[:(x.get_shape().ndims - 1)]) + [top_k*len(poses)])], indexing='ij')
val_contexts = tf.gather_nd(context_input, tf.stack(mg[:-1] + [concat_topk_idx], axis=-1))
return tf.concat([concat_topk_max, val_contexts], axis=-1)
# return backend.concatenate([concat_topk_max, val_contexts])
示例8: enum_ratios_and_thetas
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def enum_ratios_and_thetas(anchors, anchor_ratios, anchor_angles):
'''
ratio = h /w
:param anchors:
:param anchor_ratios:
:return:
'''
ws = anchors[:, 2] # for base anchor: w == h
hs = anchors[:, 3]
anchor_angles = tf.constant(anchor_angles, tf.float32)
sqrt_ratios = tf.sqrt(tf.constant(anchor_ratios))
ws = tf.reshape(ws / sqrt_ratios[:, tf.newaxis], [-1])
hs = tf.reshape(hs * sqrt_ratios[:, tf.newaxis], [-1])
ws, _ = tf.meshgrid(ws, anchor_angles)
hs, anchor_angles = tf.meshgrid(hs, anchor_angles)
anchor_angles = tf.reshape(anchor_angles, [-1, 1])
ws = tf.reshape(ws, [-1, 1])
hs = tf.reshape(hs, [-1, 1])
return ws, hs, anchor_angles
示例9: _perspective_correct_barycentrics
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix,
perspective_matrix, image_size_float):
"""Creates the pixels grid and computes barycentrics."""
# Construct the pixel grid with half-integer pixel centers.
width = image_size_float[1]
height = image_size_float[0]
px = tf.linspace(0.5, width - 0.5, num=int(width))
py = tf.linspace(0.5, height - 0.5, num=int(height))
xv, yv = tf.meshgrid(px, py)
pixel_position = tf.stack((xv, yv), axis=-1)
return glm.perspective_correct_barycentrics(vertices_per_pixel,
pixel_position,
model_to_eye_matrix,
perspective_matrix,
(width, height))
示例10: _grid
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def _grid(starts, stops, nums):
"""Generates a M-D uniform axis-aligned grid.
Warning:
This op is not differentiable. Indeed, the gradient of tf.linspace and
tf.meshgrid are currently not defined.
Args:
starts: A tensor of shape `[M]` representing the start points for each
dimension.
stops: A tensor of shape `[M]` representing the end points for each
dimension.
nums: A tensor of shape `[M]` representing the number of subdivisions for
each dimension.
Returns:
A tensor of shape `[nums[0], ..., nums[M-1], M]` containing an M-D uniform
grid.
"""
params = [tf.unstack(tensor) for tensor in [starts, stops, nums]]
layout = [tf.linspace(*param) for param in zip(*params)]
return tf.stack(tf.meshgrid(*layout, indexing="ij"), axis=-1)
示例11: volshape_to_meshgrid
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def volshape_to_meshgrid(volshape, **kwargs):
"""
compute Tensor meshgrid from a volume size
Parameters:
volshape: the volume size
**args: "name" (optional)
Returns:
A list of Tensors
See Also:
tf.meshgrid, meshgrid, ndgrid, volshape_to_ndgrid
"""
isint = [float(d).is_integer() for d in volshape]
if not all(isint):
raise ValueError("volshape needs to be a list of integers")
linvec = [tf.range(0, d) for d in volshape]
return meshgrid(*linvec, **kwargs)
示例12: K
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def K(self, X, X2=None, presliced=False):
if not presliced:
X, X2 = self._slice(X, X2)
if X2 is None:
X2 = X
pi = np.pi
# exp term; x^T * [1 rho; rho 1] * x, x=[x,-x']^T
XX, XX2 = tf.meshgrid(X, X2, indexing='ij')
R = tf.square(XX) + tf.square(XX2) - 2.0*self.correlation*XX*XX2
exp_term = tf.exp(-2.0 * pi**2 * tf.square(self.lengthscale) * R)
# phi cosine terms
mu = self.frequency
phi1 = tf.stack([tf.cos(2*pi*mu[0]*X) + tf.cos(2*pi*mu[1]*X),
tf.sin(2*pi*mu[0]*X) + tf.sin(2*pi*mu[1]*X)], axis=1)
phi2 = tf.stack([tf.cos(2*pi*mu[0]*X2) + tf.cos(2*pi*mu[1]*X2),
tf.sin(2*pi*mu[0]*X2) + tf.sin(2*pi*mu[1]*X2)], axis=1)
phi = tf.matmul(tf.squeeze(phi1), tf.squeeze(phi2), transpose_b=True)
return self.variance * exp_term * phi
示例13: roll_sequence
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def roll_sequence(tensor, offsets):
"""Shifts sequences by an offset.
Args:
tensor: A ``tf.Tensor`` of shape :math:`[B, T, ...]`.
offsets : The offset of each sequence of shape :math:`[B]`.
Returns:
A ``tf.Tensor`` with the same shape as :obj:`tensor` and with sequences
shifted by :obj:`offsets`.
"""
batch_size = tf.shape(tensor)[0]
time = tf.shape(tensor)[1]
cols, rows = tf.meshgrid(tf.range(time), tf.range(batch_size))
cols -= tf.expand_dims(offsets, 1)
cols %= time
indices = tf.stack([rows, cols], axis=-1)
return tf.gather_nd(tensor, indices)
示例14: meshgrid
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def meshgrid(self, height, width, ones_flag=None):
# get the mesh-grid in a special area(-1,1)
# output:
# @shape --> 2,H*W
# @explanation --> (0,:) means all x-coordinate in a mesh
# (1,:) means all y-coordinate in a mesh
with tf.variable_scope('meshgrid'):
y_linspace = tf.linspace(-1., 1., height)
x_linspace = tf.linspace(-1., 1., width)
x_coordinates, y_coordinates = tf.meshgrid(x_linspace, y_linspace)
x_coordinates = tf.reshape(x_coordinates, shape=[-1])
y_coordinates = tf.reshape(y_coordinates, shape=[-1])
if ones_flag is None:
indices_grid = tf.stack([x_coordinates, y_coordinates], axis=0)
else:
indices_grid = tf.stack([x_coordinates, y_coordinates, tf.ones_like(x_coordinates)], axis=0)
return indices_grid
示例15: CalculateReceptiveBoxes
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import meshgrid [as 别名]
def CalculateReceptiveBoxes(height, width, rf, stride, padding):
"""Calculate receptive boxes for each feature point.
Args:
height: The height of feature map.
width: The width of feature map.
rf: The receptive field size.
stride: The effective stride between two adjacent feature points.
padding: The effective padding size.
Returns:
rf_boxes: [N, 4] receptive boxes tensor. Here N equals to height x width.
Each box is represented by [ymin, xmin, ymax, xmax].
"""
x, y = tf.meshgrid(tf.range(width), tf.range(height))
coordinates = tf.reshape(tf.stack([y, x], axis=2), [-1, 2])
# [y,x,y,x]
point_boxes = tf.to_float(tf.concat([coordinates, coordinates], 1))
bias = [-padding, -padding, -padding + rf - 1, -padding + rf - 1]
rf_boxes = stride * point_boxes + bias
return rf_boxes