Python tensorflow.meshgrid() Examples
The following are 30
code examples of tensorflow.meshgrid().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
tensorflow
, or try the search function
.
Example #1
Source File: feature_extractor.py From yolo_v2 with Apache License 2.0 | 6 votes |
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
Example #2
Source File: snippets.py From SSH-TensorFlow with MIT License | 6 votes |
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
Example #3
Source File: model.py From DOTA_models with Apache License 2.0 | 6 votes |
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
Example #4
Source File: snippets.py From tf-faster-rcnn with MIT License | 6 votes |
def generate_anchors_pre_tf(height, width, feat_stride=16, anchor_scales=(8, 16, 32), anchor_ratios=(0.5, 1, 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
Example #5
Source File: snippets.py From SSH-TensorFlow with MIT License | 6 votes |
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
Example #6
Source File: layers.py From PADME with MIT License | 6 votes |
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)))
Example #7
Source File: snippets.py From tf-faster-rcnn with MIT License | 6 votes |
def generate_anchors_pre(height, width, 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' """ 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
Example #8
Source File: layers.py From deepchem with MIT License | 6 votes |
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)
Example #9
Source File: models.py From tf2-yolo3 with Apache License 2.0 | 6 votes |
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
Example #10
Source File: drmm_utils.py From BERT with Apache License 2.0 | 6 votes |
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])
Example #11
Source File: generate_rotate_anchors.py From R3Det_Tensorflow with MIT License | 6 votes |
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
Example #12
Source File: grid.py From graphics with Apache License 2.0 | 6 votes |
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)
Example #13
Source File: feature_extractor.py From Gun-Detector with Apache License 2.0 | 6 votes |
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
Example #14
Source File: model.py From Gun-Detector with Apache License 2.0 | 6 votes |
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
Example #15
Source File: spectral_kernels.py From nssm-gp with MIT License | 6 votes |
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
Example #16
Source File: utils.py From voxelmorph with GNU General Public License v3.0 | 6 votes |
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)
Example #17
Source File: tensor.py From OpenNMT-tf with MIT License | 6 votes |
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)
Example #18
Source File: generate_rotate_anchors.py From RetinaNet_Tensorflow_Rotation with MIT License | 6 votes |
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
Example #19
Source File: model.py From DeepWarp with Apache License 2.0 | 6 votes |
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
Example #20
Source File: utils.py From neuron with GNU General Public License v3.0 | 6 votes |
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)
Example #21
Source File: deformable_conv_layer.py From tf-deformable-conv-layer with MIT License | 6 votes |
def _get_conv_indices(self, feature_map_size): """the x, y coordinates in the window when a filter sliding on the feature map :param feature_map_size: :return: y, x with shape [1, out_h, out_w, filter_h * filter_w] """ feat_h, feat_w = [int(i) for i in feature_map_size[0: 2]] x, y = tf.meshgrid(tf.range(feat_w), tf.range(feat_h)) x, y = [tf.reshape(i, [1, *i.get_shape(), 1]) for i in [x, y]] # shape [1, h, w, 1] x, y = [tf.image.extract_image_patches(i, [1, *self.kernel_size, 1], [1, *self.strides, 1], [1, *self.dilation_rate, 1], 'VALID') for i in [x, y]] # shape [1, out_h, out_w, filter_h * filter_w] return y, x
Example #22
Source File: triangle_rasterizer.py From graphics with Apache License 2.0 | 6 votes |
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))
Example #23
Source File: model.py From yolo_v2 with Apache License 2.0 | 6 votes |
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
Example #24
Source File: eval_pix3d.py From Silhouette-Guided-3D with MIT License | 5 votes |
def get_emd_metrics(pcl_gt, pred, batch_size, num_points): ''' Calculate emd between ground truth and predicted point clouds. They may or may not be scaled. GT and pred need to be of the same dimension. Args: pcl_gt: tf placeholder of shape (B,N,3) corresponding to GT point cloud pred: tensor of shape (B,N,3) corresponding to predicted point cloud Returns: emd: (B,) ''' X,_ = tf.meshgrid(tf.range(batch_size), tf.range(num_points), indexing='ij') ind, _ = tf_auctionmatch.auction_match(pred, pcl_gt) # Ind corresponds to points in pcl_gt ind = tf.stack((X, ind), -1) emd = tf.reduce_mean(tf.sqrt(tf.reduce_sum((tf.gather_nd(pcl_gt, ind) - pred)**2, axis=-1)), axis=1) # (B, ) return emd
Example #25
Source File: spatial_transformer.py From CRNN with MIT License | 5 votes |
def _meshgrid(self, height, width): x_linspace = tf.linspace(-1., 1., width) y_linspace = tf.linspace(-1., 1., height) x_coordinates, y_coordinates = tf.meshgrid(x_linspace, y_linspace) x_coordinates = tf.reshape(x_coordinates, shape=(1, -1)) y_coordinates = tf.reshape(y_coordinates, shape=(1, -1)) ones = tf.ones_like(x_coordinates) indices_grid = tf.concat([x_coordinates, y_coordinates, ones], 0) return indices_grid
Example #26
Source File: ContactMapTask.py From tape-neurips2019 with MIT License | 5 votes |
def loss_function(self, inputs: Dict[str, tf.Tensor], outputs: Dict[str, tf.Tensor]) -> Tuple[tf.Tensor, Dict[str, tf.Tensor]]: mask = self.get_mask(inputs) label = inputs[self._label_name] pred = tf.squeeze(outputs[self._output_name], 3) batch_size, seqlen = get_shape(label, (0, 1)) # with tf.control_dependencies([tf.print(tf.shape(mask), tf.shape(inputs['valid_mask']), batch_size, seqlen)]): mask = tf.reshape(mask, (batch_size, seqlen * seqlen)) label = tf.reshape(label, (batch_size, seqlen * seqlen)) pred = tf.reshape(pred, (batch_size, seqlen * seqlen)) mask = tf.cast(mask, pred.dtype) loss = tf.losses.sigmoid_cross_entropy(label, pred, mask) max_prot_len = tf.reduce_max(inputs['protein_length']) top_l_over_5, indices = tf.nn.top_k(pred - (1000 * (1 - mask)), max_prot_len // 5) ii, _ = tf.meshgrid(tf.range(batch_size), tf.range(max_prot_len // 5), indexing='ij') l5_labels = tf.gather_nd(label, tf.stack([ii, indices], -1)) l5_mask = tf.gather_nd(mask, tf.stack([ii, indices], -1)) l5_labels = tf.cast(l5_labels, l5_mask.dtype) accuracy = tf.reduce_sum(l5_labels * l5_mask) / (tf.reduce_sum(l5_mask) + 1e-8) metrics = {self.key_metric: accuracy} return loss, metrics
Example #27
Source File: lyapunov.py From safe_learning with MIT License | 5 votes |
def smallest_boundary_value(fun, discretization): """Determine the smallest value of a function on its boundary. Parameters ---------- fun : callable A tensorflow function that we want to evaluate. discretization : instance of `GridWorld` The discretization. If None, then the function is assumed to be defined on a discretization already. Returns ------- min_value : float The smallest value on the boundary. """ min_value = np.inf feed_dict = get_feed_dict(tf.get_default_graph()) # Check boundaries for each axis for i in range(discretization.ndim): # Use boundary values only for the ith element tmp = list(discretization.discrete_points) tmp[i] = discretization.discrete_points[i][[0, -1]] # Generate all points columns = (x.ravel() for x in np.meshgrid(*tmp, indexing='ij')) all_points = np.column_stack(columns) # Update the minimum value smallest = tf.reduce_min(fun(all_points)) min_value = min(min_value, smallest.eval(feed_dict=feed_dict)) return min_value
Example #28
Source File: utils.py From voxelmorph with GNU General Public License v3.0 | 5 votes |
def ndgrid(*args, **kwargs): """ broadcast Tensors on an N-D grid with ij indexing uses meshgrid with ij indexing Parameters: *args: Tensors with rank 1 **args: "name" (optional) Returns: A list of Tensors """ return meshgrid(*args, indexing='ij', **kwargs)
Example #29
Source File: anchor_utils.py From RetinaNet_Tensorflow_Rotation with MIT License | 5 votes |
def make_anchors(base_anchor_size, anchor_scales, anchor_ratios, featuremap_height, featuremap_width, stride, name='make_anchors'): ''' :param base_anchor_size:256 :param anchor_scales: :param anchor_ratios: :param featuremap_height: :param featuremap_width: :param stride: :return: ''' with tf.variable_scope(name): base_anchor = tf.constant([0, 0, base_anchor_size, base_anchor_size], tf.float32) # [x_center, y_center, w, h] ws, hs = enum_ratios(enum_scales(base_anchor, anchor_scales), anchor_ratios) # per locations ws and hs x_centers = tf.range(featuremap_width, dtype=tf.float32) * stride y_centers = tf.range(featuremap_height, dtype=tf.float32) * stride if cfgs.USE_CENTER_OFFSET: x_centers = x_centers + stride / 2. y_centers = y_centers + stride / 2. x_centers, y_centers = tf.meshgrid(x_centers, y_centers) ws, x_centers = tf.meshgrid(ws, x_centers) hs, y_centers = tf.meshgrid(hs, y_centers) anchor_centers = tf.stack([x_centers, y_centers], 2) anchor_centers = tf.reshape(anchor_centers, [-1, 2]) box_sizes = tf.stack([ws, hs], axis=2) box_sizes = tf.reshape(box_sizes, [-1, 2]) # anchors = tf.concat([anchor_centers, box_sizes], axis=1) anchors = tf.concat([anchor_centers - 0.5*box_sizes, anchor_centers + 0.5*box_sizes], axis=1) return anchors
Example #30
Source File: generate_rotate_anchors.py From RetinaNet_Tensorflow_Rotation with MIT License | 5 votes |
def make_anchors(base_anchor_size, anchor_scales, anchor_ratios, anchor_angles, featuremap_height, featuremap_width, stride, name='make_ratate_anchors'): ''' :param base_anchor_size: :param anchor_scales: :param anchor_ratios: :param anchor_thetas: :param featuremap_height: :param featuremap_width: :param stride: :return: ''' with tf.variable_scope(name): base_anchor = tf.constant([0, 0, base_anchor_size, base_anchor_size], tf.float32) # [y_center, x_center, h, w] ws, hs, angles = enum_ratios_and_thetas(enum_scales(base_anchor, anchor_scales), anchor_ratios, anchor_angles) # per locations ws and hs and thetas x_centers = tf.range(featuremap_width, dtype=tf.float32) * stride + stride // 2 y_centers = tf.range(featuremap_height, dtype=tf.float32) * stride + stride // 2 x_centers, y_centers = tf.meshgrid(x_centers, y_centers) angles, _ = tf.meshgrid(angles, x_centers) ws, x_centers = tf.meshgrid(ws, x_centers) hs, y_centers = tf.meshgrid(hs, y_centers) anchor_centers = tf.stack([x_centers, y_centers], 2) anchor_centers = tf.reshape(anchor_centers, [-1, 2]) box_parameters = tf.stack([ws, hs, angles], axis=2) box_parameters = tf.reshape(box_parameters, [-1, 3]) anchors = tf.concat([anchor_centers, box_parameters], axis=1) return anchors