def sparse_bool_mask(x, mask, axis=0): # Only necessary if indices may have non-unique elements indices = tf.boolean_mask(tf.range(tf.shape(x)[axis]), mask) n_indices = tf.size(indices) # Get indices for the axis idx = x.indices[:, axis] # Find where indices match the selection eq = tf.equal(tf.expand_dims(idx, 1), tf.cast(indices, tf.int64)) # TODO this has quadratic cost # Mask for selected values sel = tf.reduce_any(eq, axis=1) # Selected values values_new = tf.boolean_mask(x.values, sel, axis=0) # New index value for selected elements n_indices = tf.cast(n_indices, tf.int64) idx_new = tf.reduce_sum(tf.cast(eq, tf.int64) * tf.range(n_indices), axis=1) idx_new = tf.boolean_mask(idx_new, sel, axis=0) # New full indices tensor indices_new = tf.boolean_mask(x.indices, sel, axis=0) indices_new = tf.concat([ indices_new[:, :axis], tf.expand_dims(idx_new, 1), indices_new[:, axis + 1:] ], axis=1) # New shape shape_new = tf.concat( [x.dense_shape[:axis], [n_indices], x.dense_shape[axis + 1:]], axis=0) return tf.SparseTensor(indices_new, values_new, shape_new)
def _row_kernel(upsampled_region_size, upsample_factor, axis_offsets, data_shape): data_shape_float = tf.cast(data_shape, tf.float32) row_constant = tf.cast(data_shape_float[1] * upsample_factor, tf.complex64) row_constant = (-1j * 2 * np.pi / row_constant) row_kernel_a = tf.range(0, upsampled_region_size, dtype=tf.float32) row_kernel_a = tf.reshape(row_kernel_a, (1, -1)) row_kernel_a = tf.tile(row_kernel_a, (data_shape[0], 1)) row_kernel_a = tf.transpose(row_kernel_a) row_kernel_a = row_kernel_a - axis_offsets[:, 0] row_kernel_b = tf.range(0, data_shape_float[1], dtype=tf.float32) row_kernel_b = fftshift1d(row_kernel_b) row_kernel_b = tf.reshape(row_kernel_b, (1, -1)) row_kernel_b = tf.tile(row_kernel_b, (data_shape[0], 1)) row_kernel_b = row_kernel_b - tf.floor(data_shape_float[1] / 2.) row_kernel_a = tf.expand_dims(row_kernel_a, 1) row_kernel_b = tf.expand_dims(row_kernel_b, -1) row_kernel = tf.transpose(row_kernel_a) * row_kernel_b row_kernel = tf.transpose(row_kernel, perm=(0, 2, 1)) row_kernel = row_constant * tf.cast(row_kernel, tf.complex64) row_kernel = tf.exp(row_kernel) return row_kernel
def _col_kernel(upsampled_region_size, upsample_factor, axis_offsets, data_shape): data_shape_float = tf.cast(data_shape, tf.float32) col_constant = tf.cast(data_shape_float[2] * upsample_factor, tf.complex64) col_constant = (-1j * 2 * np.pi / col_constant) col_kernel_a = tf.range(0, data_shape_float[2], dtype=tf.float32) col_kernel_a = fftshift1d(col_kernel_a) col_kernel_a = tf.reshape(col_kernel_a, (-1, 1)) col_kernel_a -= tf.floor(data_shape_float[2] / 2.) col_kernel_a = tf.reshape(col_kernel_a, (1, -1)) col_kernel_a = tf.tile(col_kernel_a, (data_shape[0], 1)) col_kernel_b = tf.range(0, upsampled_region_size, dtype=tf.float32) col_kernel_b = tf.reshape(col_kernel_b, (1, -1)) col_kernel_b = tf.tile(col_kernel_b, (data_shape[0], 1)) col_kernel_b = tf.transpose(col_kernel_b) col_kernel_b -= tf.transpose(axis_offsets[:, 1]) col_kernel_b = tf.transpose(col_kernel_b) col_kernel_a = tf.expand_dims(col_kernel_a, 1) col_kernel_b = tf.expand_dims(col_kernel_b, -1) col_kernel = col_kernel_a * col_kernel_b col_kernel = tf.transpose(col_kernel, perm=(0, 2, 1)) col_kernel = col_constant * tf.cast(col_kernel, tf.complex64) col_kernel = tf.exp(col_kernel) return col_kernel
def degree_matrix(A, return_sparse_batch=False): """ Computes the degree matrix of A, deals with sparse A and batch mode automatically. :param A: Tensor or SparseTensor with rank k = {2, 3}. :param return_sparse_batch: if operating in batch mode, return a SparseTensor. Note that the sparse degree tensor returned by this function cannot be used for sparse matrix multiplication afterwards. :return: SparseTensor of rank k. """ D = degrees(A) batch_mode = K.ndim(D) == 2 N = tf.shape(D)[-1] batch_size = tf.shape(D)[0] if batch_mode else 1 inner_index = tf.tile(tf.stack([tf.range(N)] * 2, axis=1), (batch_size, 1)) if batch_mode: if return_sparse_batch: outer_index = tf_repeat_1d( tf.range(batch_size), tf.ones(batch_size) * tf.cast(N, tf.float32)) indices = tf.concat([outer_index[:, None], inner_index], 1) dense_shape = (batch_size, N, N) else: return tf.linalg.diag(D) else: indices = inner_index dense_shape = (N, N) indices = tf.cast(indices, tf.int64) values = tf.reshape(D, (-1, )) return tf.SparseTensor(indices, values, dense_shape)
def gaussian_kernel_1d(size, sigma): size = tf.constant(size, dtype=tf.float32) sigma = tf.constant(sigma, dtype=tf.float32) x = tf.range(-(size // 2), (size // 2) + 1, dtype=tf.float32) kernel = 1 / (sigma * tf.sqrt(2 * np.pi)) kernel *= tf.exp(-0.5 * (x / sigma)**2) return tf.expand_dims(kernel, axis=-1)
def call(self, x): x_shape = x.get_shape() offsets = super(Conv2DOffset, self).call(x) #offsets *= 10 channels = int(offsets.get_shape()[3].value) n_batches = tf.shape(offsets)[0] # Change offset's order from [x1, x2, ..., y1, y2, ...] to [x1, y1, x2, y2, ...] # Codes below are written to make sure same results of MXNet implementation. # You can remove them, and it won't influence the module's performance. ind_shuffle = tf.concat( [tf.range(0, channels, 2), tf.range(1, channels + 1, 2)], axis=0) #ind_shuffle = tf.expand_dims(ind_shuffle, axis=0) #ind_shuffle = tf.expand_dims(ind_shuffle, axis=0) #ind_shuffle = tf.tile(ind_shuffle, [input_w, input_h, 1]) offsets = tf.gather(offsets, ind_shuffle, axis=3) # ------------------------------------------------------------------------ #x = tf.transpose(x, [0, 3, 1, 2]) #x = tf.reshape(x, (-1, int(x_shape[1]), int(x_shape[2]))) #offsets = tf.resampler(x, offsets) offsets = batch_map_offsets(x, offsets) #offsets = tf.reshape(x, (-1, int(x_shape[3]), int(x_shape[1]), int(x_shape[2]))) #offsets = tf.transpose(x, [0, 2, 3, 1]) offset_shape = offsets.get_shape() num_channels = offset_shape[1].value height = offset_shape[2].value width = offset_shape[3].value f_offset = [ tf.reshape(offsets[..., ind:ind + 3], (-1, num_channels, height, width * 3)) for ind in range(0, 9, 3) ] f_offset = tf.concat(f_offset, axis=-1) f_offset = tf.reshape(f_offset, (-1, num_channels, height * 3, width * 3)) f_offset = tf.transpose(f_offset, (0, 2, 3, 1)) return f_offset
def batch_map_offsets(input, offsets, order=1): """Batch map offsets into input Adds index of every entry to the entry to make it's interpolation relevant to it's location """ offset_shape = offsets.get_shape() batch_size = tf.shape(offsets)[0] input_h = offset_shape[1] input_w = offset_shape[2] channel_size = int(offset_shape[3].value) #offsets = tf.reshape(offsets, (batch_size, -1, 2)) #################### DEFAULT COORDINATES FOR EVERY POINT #################### ind_add = tf.meshgrid(tf.range(1, input_h + 1, delta=1), tf.range(1, input_w + 1, delta=1), indexing='ij') ind_add = tf.stack(ind_add, axis=-1) ind_add = tf.cast(ind_add, 'float32') ind_add = tf.reshape(ind_add, (1, input_h, input_w, 2)) ind_add = tf.tile(ind_add, [batch_size, 1, 1, int(channel_size / 2)]) ############################################################################# #################### KERNEL OFFSET FOR EVERY POINT #################### ind_zero = tf.meshgrid(tf.range(-1, 2, delta=1), tf.range(-1, 2, delta=1), indexing='ij') ind_zero = tf.stack(ind_zero, axis=-1) ind_zero = tf.cast(ind_zero, 'float32') ind_zero = tf.reshape(ind_zero, (1, 1, 1, channel_size)) ind_zero = tf.tile(ind_zero, [batch_size, input_h, input_w, 1]) ####################################################################### coords = offsets + ind_add + ind_zero int_vals = batch_map_coordinates(input, coords, int(channel_size / 2)) return int_vals
def batch_map_offsets(input, offsets, order=1): """Batch map offsets into input Adds index of every entry to the entry to make it's interpolation relevant to it's location """ input_shape = tf.shape(input) batch_size = input_shape[0] input_w = input_shape[1] input_h = input_shape[2] offsets = tf.reshape(offsets, (batch_size, -1, 2)) ind_add = tf.meshgrid(tf.range(input_w), tf.range(input_h), indexing='ij') ind_add = tf.stack(ind_add, axis=-1) ind_add = tf.cast(ind_add, 'float32') ind_add = tf.reshape(ind_add, (-1, 2)) ind_add = tf.expand_dims(ind_add, 0) ind_add = tf.tile(ind_add, [batch_size, 1, 1]) coords = offsets + ind_add int_vals = batch_map_coordinates(input, coords) return int_vals
def top_k(scores, I, ratio, top_k_var): """ Returns indices to get the top K values in `scores` segment-wise, with segments defined by I. K is not fixed, but it is defined as a ratio of the number of elements in each segment. :param scores: a rank 1 tensor with scores; :param I: a rank 1 tensor with segment IDs; :param ratio: float, ratio of elements to keep for each segment; :param top_k_var: a tf.Variable without shape validation (e.g., `tf.Variable(0.0, validate_shape=False)`); :return: a rank 1 tensor containing the indices to get the top K values of each segment in `scores`. """ num_nodes = tf.segment_sum(tf.ones_like(I), I) # Number of nodes in each graph cumsum = tf.cumsum(num_nodes) # Cumulative number of nodes (A, A+B, A+B+C) cumsum_start = cumsum - num_nodes # Start index of each graph n_graphs = tf.shape(num_nodes)[0] # Number of graphs in batch max_n_nodes = tf.reduce_max(num_nodes) # Order of biggest graph in batch batch_n_nodes = tf.shape(I)[0] # Number of overall nodes in batch to_keep = tf.ceil(ratio * tf.cast(num_nodes, tf.float32)) to_keep = tf.cast(to_keep, tf.int32) # Nodes to keep in each graph index = tf.range(batch_n_nodes) index = (index - tf.gather(cumsum_start, I)) + (I * max_n_nodes) y_min = tf.reduce_min(scores) dense_y = tf.ones((n_graphs * max_n_nodes, )) dense_y = dense_y * tf.cast( y_min - 1, tf.float32 ) # subtract 1 to ensure that filler values do not get picked dense_y = tf.assign( top_k_var, dense_y, validate_shape=False ) # top_k_var is a variable with unknown shape defined in the elsewhere dense_y = tf.scatter_update(dense_y, index, scores) dense_y = tf.reshape(dense_y, (n_graphs, max_n_nodes)) perm = tf.argsort(dense_y, direction='DESCENDING') perm = perm + cumsum_start[:, None] perm = tf.reshape(perm, (-1, )) to_rep = tf.tile(tf.constant([1., 0.]), (n_graphs, )) rep_times = tf.reshape( tf.concat((to_keep[:, None], (max_n_nodes - to_keep)[:, None]), -1), (-1, )) mask = tf_repeat_1d(to_rep, rep_times) perm = tf.boolean_mask(perm, mask) return perm
def tf_repeat_1d(x, repeats): """ Repeats each value `x[i]` a number of times `repeats[i]`. :param x: a rank 1 tensor; :param repeats: a rank 1 tensor; :return: a rank 1 tensor, of shape `(sum(repeats), )`. """ x = tf.expand_dims(x, 1) max_repeats = tf.reduce_max(repeats) tile_repeats = [1, max_repeats] arr_tiled = tf.tile(x, tile_repeats) mask = tf.less(tf.range(max_repeats), tf.expand_dims(repeats, 1)) result = tf.reshape(tf.boolean_mask(arr_tiled, mask), [-1]) return result
def batch_map_coordinates(input, coords, order=1): """Batch version of tf_map_coordinates""" input_shape = tf.shape(input) batch_size = input_shape[0] input_size = input_shape[1] #coords = tf.reshape(coords, (batch_size, -1, 2)) n_coords = tf.shape(coords)[1] coords = tf.clip_by_value(coords, 0, tf.cast(input_size, 'float32') - 1) coords_tl = tf.cast(tf.floor(coords), 'int32') coords_br = tf.cast(tf.ceil(coords), 'int32') coords_bl = tf.stack([coords_tl[..., 0], coords_br[..., 1]], axis=-1) coords_tr = tf.stack([coords_br[..., 0], coords_tl[..., 1]], axis=-1) idx = tf.range(batch_size) idx = tf.expand_dims(idx, -1) idx = tf.tile(idx, [1, n_coords]) idx = tf.reshape(idx, [-1]) def _get_vals_by_coords(input, coords): coords_0_flat = tf.reshape(coords[..., 0], [-1]) coords_1_flat = tf.reshape(coords[..., 1], [-1]) indices = tf.stack([idx, coords_0_flat, coords_1_flat], axis=-1) vals = tf.gather_nd(input, indices) vals = tf.reshape(vals, (batch_size, n_coords)) return vals vals_tl = _get_vals_by_coords(input, coords_tl) vals_br = _get_vals_by_coords(input, coords_br) vals_bl = _get_vals_by_coords(input, coords_bl) vals_tr = _get_vals_by_coords(input, coords_tr) h_offset = coords[..., 0] - tf.cast(coords_tl[..., 0], tf.float32) h_int_t = (((1.0 - h_offset) * vals_tl) + (h_offset * vals_tr)) h_int_b = (((1.0 - h_offset) * vals_bl) + (h_offset * vals_br)) v_offset = coords[..., 1] - tf.cast(coords_tl[..., 1], tf.float32) int_vals = (((1.0 - v_offset) * h_int_t) + (v_offset * h_int_b)) return int_vals
def build(self, input_shape): self.xx, self.yy = ktf.meshgrid(ktf.range(self.image_size[1]), ktf.range(self.image_size[0])) self.xx = ktf.expand_dims(ktf.cast(self.xx, 'float32'), 2) self.yy = ktf.expand_dims(ktf.cast(self.yy, 'float32'), 2)