seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
from tensorflow.python.ops import math_ops return math_ops.square(logits - math_ops.to_float(target)) def _log_loss_with_two_classes(logits, target): # sigmoid_cross_entropy_with_logits requires [batch_size, 1] target. if len(target.get_shape()) == 1: target = array_ops.expand_dims(target, dim=[1]) loss_vec = nn.sigmoid_cross_entropy_with_logits(logits, math_ops.to_float(target)) return loss_vec def _softmax_cross_entropy_loss(logits, target): # sigmoid_cross_entropy_with_logits requires [batch_size, 1] target. # Check that we got int32/int64 for classification. if (not target.dtype.is_compatible_with(dtypes.int64) and
tensorflow.python.ops.math_ops.to_float
7,400
import tensorflow as tf pred1, pred2 = tf.split(horizon_pred, 2, axis=0) tgt1, tgt2 = tf.split(horizon_tgt, 2, axis=0) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1) loss = tf.maximum(0.0, ((tgt_larg - tgt_small) - (pred_larg - pred_small))) loss = tf.reduce_mean(loss) return loss # randrom horizon def contra_traj_lossV3(pred, tgt, horizon=12): # Step-wise contrastive loss horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
tensorflow.maximum
7,401
import tensorflow as tf din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag)
tensorflow.layers.dense
7,402
import tensorflow as tf size = tf.random.uniform(shape=[],minval=3,maxval=7,dtype=tf.int32) # size [7-15] self.kernel = self.gaussian_kernel(size,mean,std) self.kernel = tf.tile(self.kernel[:, :, tf.newaxis, tf.newaxis], [1, 1, 3, 1]) self.paddings = tf.convert_to_tensor([[size,size],[size,size],[0,0]]) x_aug = tf.nn.separable_conv2d(tf.expand_dims(tf.pad(x,self.paddings,'SYMMETRIC'), 0), self.kernel, self.pointwise_filter,strides=[1, 1, 1, 1], padding='VALID') x_aug = tf.squeeze(x_aug) return tf.concat([x, x_aug],axis=2) def high_low_pass(self,x): x_low = tf.nn.separable_conv2d(tf.expand_dims(tf.pad(x,self.paddings,'SYMMETRIC'), 0), self.kernel, self.pointwise_filter,strides=[1, 1, 1, 1], padding='VALID') x_low = tf.squeeze(x_low) x_high = x - x_low
tensorflow.concat
7,403
import tensorflow as tf def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
tensorflow.logging.info
7,404
from tensorflow.python.ops import variables def _setupDense(self, is_distributed, dtype): with self._maybeWithDevice("/job:ps" if is_distributed else None): var0 = variables.Variable([[0.0, 1.0], [2.0, 3.0]], dtype=dtype) var1 = variables.Variable([4.0, 5.0], dtype=dtype) with self._maybeWithDevice("/job:worker" if is_distributed else None): grads0 = constant_op.constant([[0.1, 0.1], [0.1, 0.1]], dtype=dtype)
tensorflow.python.ops.variables.Variable
7,405
import tensorflow as tf This method computes the mean and (co)variance of q(g1) = \int q(g2) p(g1|g2) :param Kmn: M x N :param Kmm: M x M :param Knn: N x N or N :param f: M x R :param full_cov: bool :param q_sqrt: None or R x M x M (lower triangular) :param white: bool :return: N x R or R x N x N """ logger.debug("base conditional") # compute kernel stuff num_func = tf.shape(f)[1] # R Lm = tf.cholesky(Kmm) # Compute the projection matrix A A = tf.matrix_triangular_solve(Lm, Kmn, lower=True) # compute the covariance due to the conditioning if full_cov: fvar = Knn - tf.matmul(A, A, transpose_a=True) fvar = tf.tile(fvar[None, :, :], [num_func, 1, 1]) # R x N x N else: fvar = Knn - tf.reduce_sum(tf.square(A), 0) fvar = tf.tile(fvar[None, :], [num_func, 1]) # R x N # another backsubstitution in the unwhitened case
tensorflow.cholesky
7,406
import tensorflow as tf if not is_training: return self._lr = tf.Variable(0.0, trainable=False) tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(self._cost, tvars),
tensorflow.Variable
7,407
import tensorflow as tf dec_inp_dict = {} dec_inp_dict["0"] = [ tf.constant(i, tf.int32, shape=[2]) for i in range(3)] dec_inp_dict["1"] = [
tensorflow.constant
7,408
import tensorflow as tf sqrt_diag[:, n][:, None] if diag else sqrt[n, :, :][None, :, :], # 1 x M x M or M x 1 K if shared_k else K_batch[n, :, :][None,:,:])) # 1 x M x M or M x M kl_sum =tf.reduce_sum(kl_sum) assert_almost_equal(kl_sum.eval(), kl_batch.eval())
tensorflow.reduce_sum
7,409
import tensorflow as tf grid = tf.expand_dims(grid, 0) grid = tf.reshape(grid, [-1]) grid = tf.tile(grid, tf.stack([num_batch])) grid = tf.reshape(grid, tf.stack([num_batch, 4, -1])) # Transform A x (x_t', y_t', 1, d_t)^T -> (x_s, y_s, z_s, 1). t_g = tf.matmul(theta, grid) z_s = tf.slice(t_g, [0, 0, 0], [-1, 1, -1]) y_s = tf.slice(t_g, [0, 1, 0], [-1, 1, -1]) x_s = tf.slice(t_g, [0, 2, 0], [-1, 1, -1]) z_s_flat = tf.reshape(z_s, [-1]) y_s_flat = tf.reshape(y_s, [-1]) x_s_flat = tf.reshape(x_s, [-1]) input_transformed = _interpolate(input_dim, x_s_flat, y_s_flat, z_s_flat,
tensorflow.slice
7,410
import tensorflow as tf :param x: [Tensor] Convolution feature map, 4D, dtype float32. :param w: [Tensor] Convolution kernel, 4D, dtype float32. :param mask: [Tensor] Binary mask, 3D or 4D, [N, H, W] or [N, H, W, 1], dtype float32. :param strides: [list] List of 4 int. Convolution strides. :param padding: [string] Convolution padding method, `VALID` or `SAME`. """ assert len(mask.get_shape()) in [3, 4], 'Mask shape must be 3D or 4D.' if len(mask.get_shape()) == 3: mask_ = tf.expand_dims(mask, 3) elif len(mask.get_shape()) == 4: mask_ = mask assert mask.get_shape()[-1] == 1, '4D mask last dimension must be 1.' ksize = [int(ss) for ss in w.get_shape()] psize = [1, ksize[0], ksize[1], 1] mask_ = tf.nn.max_pool(mask_, psize, strides, padding) return tf.nn.conv2d(x, w, strides, padding) * mask_
tensorflow.expand_dims
7,411
import tensorflow as tf if mode == tf.estimator.ModeKeys.TRAIN: global_step = tf.train.get_or_create_global_step() lr_values = [params['warmup_learning_rate']] + [base_learning_rate * decay for decay in params['lr_decay_factors']] learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32), [params['warmup_steps']] + [int(float(ep)*params['steps_per_epoch']) for ep in params['decay_boundaries']], lr_values) truncated_learning_rate = tf.maximum(learning_rate, tf.constant(params['end_learning_rate'], dtype=learning_rate.dtype), name='learning_rate') tf.summary.scalar('lr', truncated_learning_rate) optimizer = tf.train.MomentumOptimizer(learning_rate=truncated_learning_rate, momentum=params['momentum']) # Batch norm requires update_ops to be added as a train_op dependency. update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): train_op = optimizer.minimize(loss, global_step) else: train_op = None return tf.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=loss, train_op=train_op, eval_metric_ops=metrics, scaffold=tf.train.Scaffold(init_fn=train_helper.get_init_fn_for_scaffold_(params['checkpoint_path'], params['model_dir'], params['checkpoint_exclude_scopes'], params['model_scope'], params['checkpoint_model_scope'], params['ignore_missing_vars'])))
tensorflow.get_collection
7,412
import tensorflow as tf with self.assertRaisesOpError("not in the support"): x = tf.placeholder_with_default(input=[2., 2., 5.], shape=[3]) log_prob = pareto.log_prob(x) self.evaluate(log_prob) with self.assertRaisesOpError("not in the support"): x = tf.placeholder_with_default(input=[1., 3., 5.], shape=[3]) log_prob = pareto.log_prob(x) self.evaluate(log_prob) def testParetoLogPdfMultidimensional(self): batch_size = 6
tensorflow.placeholder_with_default
7,413
import tensorflow as tf test_pre = tf.argmax(test_pre, 1) test_true = tf.argmax(test_labels, 1) valid_image_batch,valid_label_batch=get_valid_batch(valid_image,valid_label,validnum) valid_inf=work.valid_inference(valid_image_batch) valid_labels=tf.one_hot(valid_label_batch,classnum) #train_step=tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy) valid_pre = tf.reshape(valid_inf, [validnum, classnum]) valid_correct_prediction=tf.equal(tf.argmax(valid_inf,1),tf.argmax(valid_labels,1)) valid_accuracy=tf.reduce_mean(tf.cast(valid_correct_prediction,tf.float32)) valid_pre = tf.argmax(valid_pre, 1) valid_true = tf.argmax(valid_labels, 1) target_names = ['class sg', 'class bm', 'class wd', 'class wt', 'class wj', 'class wo', 'class ym', 'class shq', 'class shj', 'class no', 'class yh', 'class fb'] init = tf.initialize_all_variables() config=tf.ConfigProto()
tensorflow.cast
7,414
import tensorflow as tf def fc_layer(self, bottom, name): with tf.variable_scope(name):
tensorflow.variable_scope
7,415
import tensorflow as tf q_emb = tf.nn.dropout(tf.nn.embedding_lookup(self.word_mat, self.q), 1.0 - self.dropout) c_emb = tf.concat([c_emb, ch_emb], axis=2) q_emb = tf.concat([q_emb, qh_emb], axis=2)
tensorflow.concat
7,416
import tensorflow as tf # Load IRK weights tmp = np.float32(np.loadtxt('../../Utilities/IRK_weights/Butcher_IRK%d.txt' % (q), ndmin = 2)) weights = np.reshape(tmp[0:q**2+q], (q+1,q)) self.IRK_alpha = weights[0:-1,:] self.IRK_beta = weights[-1:,:] self.IRK_times = tmp[q**2+q:] # tf placeholders and graph self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)) self.x0_tf = tf.placeholder(tf.float32, shape=(None, self.x0.shape[1])) self.x1_tf = tf.placeholder(tf.float32, shape=(None, self.x1.shape[1])) self.u0_tf = tf.placeholder(tf.float32, shape=(None, self.u0.shape[1])) self.u1_tf = tf.placeholder(tf.float32, shape=(None, self.u1.shape[1])) self.dummy_x0_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients self.dummy_x1_tf = tf.placeholder(tf.float32, shape=(None, self.q)) # dummy variable for fwd_gradients self.U0_pred = self.net_U0(self.x0_tf) # N0 x q self.U1_pred = self.net_U1(self.x1_tf) # N1 x q self.loss = tf.reduce_sum(tf.square(self.u0_tf - self.U0_pred)) + \ tf.reduce_sum(tf.square(self.u1_tf - self.U1_pred)) self.optimizer = tf.contrib.opt.ScipyOptimizerInterface(self.loss, method = 'L-BFGS-B', options = {'maxiter': 50000, 'maxfun': 50000, 'maxcor': 50, 'maxls': 50,
tensorflow.placeholder
7,417
import tensorflow as tf def cat_entropy_softmax(p0): return - tf.reduce_sum(p0 * tf.log(p0 + 1e-6), axis = 1)
tensorflow.log
7,418
import tensorflow as tf import losses import mask_rcnn_architecture _WEIGHT_DECAY = 1e-4 def create_optimizer(learning_rate, params): """Creates optimized based on the specified flags.""" if params['optimizer'] == 'momentum': optimizer = tf.train.MomentumOptimizer( learning_rate, momentum=params['momentum']) elif params['optimizer'] == 'adam': optimizer = tf.train.AdamOptimizer(learning_rate) elif params['optimizer'] == 'adadelta': optimizer = tf.train.AdadeltaOptimizer(learning_rate) elif params['optimizer'] == 'adagrad': optimizer = tf.train.AdagradOptimizer(learning_rate) elif params['optimizer'] == 'rmsprop': optimizer = tf.train.RMSPropOptimizer(
tensorflow.train.MomentumOptimizer
7,419
import tensorflow as tf print(mtype, fig_obj_count, 2) fig_obj_count += 1 intersection = tf.reduce_sum(tf.math.sign(tf.nn.relu(sdf_values - 1))) union = tf.reduce_sum(tf.math.sign(sdf_values)) iou = intersection / union if not tf.math.is_nan(iou): ious.append(iou)
tensorflow.math.sign
7,420
import tensorflow as tf target_emb = tf.expand_dims(top_span_emb, 1) # [k, 1, emb] similarity_emb = top_antecedent_emb * target_emb # [k, c, emb] target_emb = tf.tile(target_emb, [1, c, 1]) # [k, c, emb]
tensorflow.tile
7,421
import tensorflow as tf # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return example def main(_): tf.logging.set_verbosity(tf.logging.INFO) if FLAGS.use_hvd: hvd.init() if FLAGS.reduce_log and (hvd.rank() != 0): tf.logging.set_verbosity(tf.logging.ERROR) FLAGS.output_dir = FLAGS.output_dir if hvd.rank() == 0 else os.path.join(FLAGS.output_dir, str(hvd.rank())) if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_train_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True.")
tensorflow.logging.set_verbosity
7,422
import tensorflow as tf num_classes = FLAGS.src_num_classes finetune_one_hot_labels = tf.one_hot( tf.cast(labels['finetune'], tf.int64), target_num_classes) target_one_hot_labels = tf.one_hot( tf.cast(labels['target'], tf.int64), target_num_classes) with tf.variable_scope('rl_controller') as rl_scope: # It creates a `rl_scope` which will be used for ops. pass rl_entropy, label_weights, log_prob = rl_label_weights(rl_scope) loss_entropy, loss_weights, loss_log_prob = get_loss_weights(rl_scope) def gather_init_weights():
tensorflow.variable_scope
7,423
import tensorflow as tf self.dt = dt self.q = max(q,1) # Initialize NN self.weights, self.biases = self.initialize_NN(layers) # Initialize parameters self.lambda_1 = tf.Variable([0.0], dtype=tf.float32) self.lambda_2 = tf.Variable([-6.0], dtype=tf.float32) # Load IRK weights tmp = np.float32(np.loadtxt('../../Utilities/IRK_weights/Butcher_IRK%d.txt' % (q), ndmin = 2)) weights = np.reshape(tmp[0:q**2+q], (q+1,q)) self.IRK_alpha = weights[0:-1,:] self.IRK_beta = weights[-1:,:] self.IRK_times = tmp[q**2+q:]
tensorflow.Variable
7,424
import tensorflow as tf Args: x: an input tensor with the dimensions (N_examples, 3072), where 3072 is the number of pixels in a standard CIFAR10 image. Returns: y: is a tensor of shape (N_examples, 10), with values equal to the logits of classifying the object images into one of 10 classes (airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck) img_summary: a string tensor containing sampled input images. """ # Reshape to use within a convolutional neural net. Last dimension is for # 'features' - it would be 1 one for a grayscale image, 3 for an RGB image, # 4 for RGBA, etc. x_image = tf.reshape(x, [-1, FLAGS.img_width, FLAGS.img_height, FLAGS.img_channels]) x_image = tf.cond(train, lambda: tf.map_fn(tf.image.random_flip_left_right, x_image), lambda: x_image) x_image = tf.cond(train, lambda: tf.map_fn(lambda x: tf.image.random_brightness(x, 0.5), x_image), lambda: x_image) img_summary = tf.summary.image('Input_images', x_image) # First convolutional layer - maps one image to 32 feature maps. with tf.variable_scope('Conv_1'): conv1 = tf.layers.conv2d( inputs=x_image, filters=32, kernel_size=[5,5], padding='same',
tensorflow.reshape
7,425
import tensorflow as tf self.n_data = n_data def data_map(self, img_path): n_bits = config.model.data.n_bits n_bins = 2**n_bits rgb = tf.image.decode_png(tf.read_file(img_path), channels=3, dtype=tf.uint8) h = config.model.data.dimensions.h w = config.model.data.dimensions.w c = config.model.data.dimensions.c # rgb.set_shape([h,w,c]) # variable size per example # crop for lsun 96 rgb = tf.image.random_crop(rgb,size=[h,w,c]) # crop for patch training crop_h = h//self.crop_factor crop_w = w//self.crop_factor rgb = tf.image.random_crop(rgb,size=[crop_h,crop_w,c]) # cast, bit conversion, compress domain, center rgb = tf.cast(rgb, tf.float32) if n_bits < 8: rgb = tf.floor(rgb/(2**(8-n_bits))) rgb = rgb/(n_bins) - 0.5
tensorflow.image.random_crop
7,426
import tensorflow as tf # print(final_loss, avg_loss) # p = tf.print('debug loss ', [final_loss, avg_loss]) # with tf.control_dependencies([p]): # avg_loss = 1. * avg_loss # print(avg_loss) # exit() return avg_loss def compute_contra_loss(pred1, pred2, tgt1, tgt2, hard_ratio=1.0): geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1) loss = tf.maximum(0., (tgt_larg - tgt_small) - (pred_larg - pred_small)) if hard_ratio < 1.0: hard_num = tf.cast(tools.shape(pred1)[0] * hard_ratio, tf.int32) loss = tf.reshape(loss, [-1]) hard_loss, _ = tf.math.top_k(loss, k=hard_num) return hard_loss return loss
tensorflow.where
7,427
import tensorflow as tf :param tol: [float] Lower bound of occupancy for creating a rectangle. :return [tuple] bin_counts: [Tensor]. Number of active locations for each bin. active_block_indices: [Tensor]. [M]. Center locations of M rectangles. Dtype int64. """ def to_tensor(a, dtype): if type(a) == tf.Tensor: if a.dtype != dtype: return tf.cast(a, dtype) else: return a elif type(a) == list: if type(a[0]) == tf.Tensor: return tf.stack(a, 0) else: return tf.constant(a, dtype) else: print(type(a))
tensorflow.cast
7,428
import tensorflow as tf adjcents: A list of N `tf.SparseTensor` of `int64`. Specify adjacent matrix between hops. """ nodes = tf.reshape(nodes, [-1]) nodes_list = [nodes] adj_list = [] for hop_edge_types in edge_types: neighbor, weight, _ = get_full_neighbor(nodes, hop_edge_types) next_nodes, next_idx = tf.unique(neighbor.values, out_idx=tf.int64) next_indices = tf.stack([neighbor.indices[:, 0], next_idx], 1) next_values = weight.values next_shape = [tf.size(nodes), tf.size(next_nodes)] next_adj = tf.sparse.SparseTensor(next_indices, next_values, next_shape) next_adj = tf.sparse.reorder(next_adj) nodes_list.append(next_nodes) adj_list.append(next_adj) nodes = next_nodes return nodes_list, adj_list
tensorflow.sparse.SparseTensor
7,429
import tensorflow as tf def cross_entropy_layer(tensor, target, **opts): if _rank(tensor) > 1: target = tf.reshape(target, shape=(-1, )) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=tensor, labels=target) mask = tf.cast(tf.not_equal(target, tf.zeros_like(target)), dtype=tf.float32) out = cross_entropy * mask return out
tensorflow.nn.sparse_softmax_cross_entropy_with_logits
7,430
import tensorflow as tf self.weight_norms = [tf.norm(v) + NUMTOL for (g, v) in clipped_grads_and_vars] # check that gradients are finite grads = [tf.check_numerics(g, "grads is not finite") for (g, v) in clipped_grads_and_vars] variables = [tf.check_numerics(v, "grads is not finite") for (g, v) in clipped_grads_and_vars]
tensorflow.check_numerics
7,431
import tensorflow as tf pairwise_improvement = tf.nn.relu(dists[1:] - pred_error)
tensorflow.nn.relu
7,432
import tensorflow as tf passed to the Loss or Postprocess functions. """ flattened_inputs = tf.contrib.layers.flatten(preprocessed_inputs) class_prediction = tf.contrib.layers.fully_connected( flattened_inputs, self._num_classes) box_prediction = tf.contrib.layers.fully_connected(flattened_inputs, 4)
tensorflow.contrib.layers.fully_connected
7,433
import tensorflow as tf Returns: A boolean tensor with the same shape as input (indicator) tensor """ indices = tf.where(indicator) indices = tf.random.shuffle(indices) indices = tf.reshape(indices, [-1]) num_samples = tf.minimum(tf.size(indices), num_samples) selected_indices = tf.slice(indices, [0], tf.reshape(num_samples, [1])) selected_indicator = ops.indices_to_dense_vector(selected_indices, tf.shape(indicator)[0]) return tf.equal(selected_indicator, 1) def sample_balanced_positive_negative(indicator, sample_size, labels, positive_fraction=0.5): """Subsamples minibatches to a desired balance of positives and negatives.
tensorflow.reshape
7,434
import tensorflow as tf def testLarge(self): with self.test_session() as sess: x = tf.zeros([1000000], dtype=np.float32) y = tf.py_func(lambda x: x + 1, [x], [tf.float32])
tensorflow.zeros
7,435
import tensorflow as tf import tensorflow as tf import warnings def conv2d(x, dim=(32, [3, 3], [1, 1]), pad='SAME', scope="conv2d", training=True, ema=None, init=False, bias_initializer=tf.constant_initializer(0.)): num_filters, filter_size, stride = dim with tf.variable_scope(scope): V = tf.get_variable('V', shape=list(filter_size) + [int(x.get_shape()[-1]), num_filters], dtype=tf.float32,
tensorflow.constant_initializer
7,436
import tensorflow as tf print(fc1) # now to upscale to actual image size deconv_shape1 = image_net["pool4"].get_shape() W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, 278], name="W_t1") b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1") conv_t1 = utils.conv2d_transpose_strided(concat1, W_t1, b_t1, output_shape=tf.shape(image_net["pool4"])) fuse_1 = tf.add(conv_t1, image_net["pool4"], name="fuse_1") deconv_shape2 = image_net["pool3"].get_shape() W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2") b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2") conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=tf.shape(image_net["pool3"])) fuse_2 = tf.add(conv_t2, image_net["pool3"], name="fuse_2") shape = tf.shape(image) deconv_shape3 = tf.stack([shape[0], shape[1], shape[2], 3]) W_t3 = utils.weight_variable([16, 16, 3, deconv_shape2[3].value], name="W_t3") b_t3 = utils.bias_variable([3], name="b_t3") conv_t3 = tf.nn.relu(utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)) annotation_pred = tf.argmax(conv_t3, dimension=3, name="prediction") return tf.expand_dims(annotation_pred, dim=3), conv_t3
tensorflow.add
7,437
from tensorflow.python.framework import ops ops.RegisterShape("Relu")(common_shapes.unchanged_shape) ops.RegisterShape("Relu6")(common_shapes.unchanged_shape) ops.RegisterShape("Elu")(common_shapes.unchanged_shape)
tensorflow.python.framework.ops.RegisterShape
7,438
import tensorflow as tf def call(self, sp_matrices, dense_matrices, adjoint_a=False, adjoint_b=False): sp_indices = [sp_m.indices for sp_m in sp_matrices] sp_values = [sp_m.values for sp_m in sp_matrices] sp_shape = [sp_m.dense_shape for sp_m in sp_matrices] return self.b_module.bspmdt(sp_ids = sp_indices, sp_values = sp_values, sp_shape = sp_shape, rhs = dense_matrices, adjoint_a = adjoint_a, adjoint_b = adjoint_b) b_module = tf.load_op_library('./batched.so') @ops.RegisterGradient("Bspmdt") def _bspmdt_grad(op, *grad): """Gradients for the dense tensors in the SparseTensorDenseMatMul ops. Args:
tensorflow.load_op_library
7,439
import tensorflow as tf # Step-wise contrastive loss even = [2 * i for i in range(25)] odd = [2 * i + 1 for i in range(25)] pred1 = tf.gather(pred, even) pred2 = tf.gather(pred, odd) tgt1 = tf.gather(tgt, even) tgt2 = tf.gather(tgt, odd)
tensorflow.gather
7,440
import tensorflow as tf def test_maximum_batch_size(self): with self.test_session() as session: @dynamic_batching.batch_fn_with_options(maximum_batch_size=2) def f(a, b): batch_size = tf.shape(a)[0] return a + b, tf.tile([batch_size], [batch_size]) outputs = [ f(tf.constant([1]), tf.constant([2])), f(tf.constant([1]), tf.constant([2])), f(tf.constant([1]), tf.constant([2])), f(tf.constant([1]), tf.constant([2])), f(tf.constant([1]), tf.constant([2])), ] tf.train.start_queue_runners() results = session.run(outputs) for value, batch_size in results:
tensorflow.constant
7,441
import tensorflow as tf res = tf.square(input_ - mean) max_sqr = tf.reduce_max(res, axes) res /= max_sqr res = tf.reduce_mean(res, axes) res *= max_sqr
tensorflow.reduce_mean
7,442
import tensorflow as tf drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" name_to_features = { "input_ids": tf.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.FixedLenFeature([seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([seq_length], tf.int64), "label_ids": tf.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): """Decodes a record to a TensorFlow example.""" example = tf.parse_single_example(record, name_to_features) # tf.Example only supports tf.int64, but the TPU only supports tf.int32. # So cast all int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t return example
tensorflow.parse_single_example
7,443
import tensorflow as tf is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32) is_training = (mode == tf.estimator.ModeKeys.TRAIN) (total_loss, per_example_loss, probabilities, logits, predictions) = \ create_model(config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings, task_name) tvars = tf.trainable_variables() initialized_variable_names = {} scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold():
tensorflow.trainable_variables
7,444
import tensorflow as tf all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), "input_mask": tf.constant( all_input_mask, shape=[num_examples, seq_length],
tensorflow.constant
7,445
import tensorflow as tf 'The values of learning_rate decay factor for each segment between boundaries (comma-separated list).') # checkpoint related configuration tf.app.flags.DEFINE_string( 'checkpoint_path', './model', 'The path to a checkpoint from which to fine-tune.') tf.app.flags.DEFINE_string( 'checkpoint_model_scope', '', 'Model scope in the checkpoint. None if the same as the trained model.') tf.app.flags.DEFINE_string( #'blouse', 'dress', 'outwear', 'skirt', 'trousers', 'all' 'model_scope', None, 'Model scope name used to replace the name_scope in checkpoint.') tf.app.flags.DEFINE_string( 'checkpoint_exclude_scopes', None, 'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.') tf.app.flags.DEFINE_boolean(
tensorflow.app.flags.DEFINE_string
7,446
import tensorflow as tf dtype=self.dtype, trainable=True, initializer=initialization.xavier_initializer( shape=m_shape, dtype=self.dtype, uniform=self.normal_initializer, mask=None))) # Gain bias bias_shape = [1, 1, 1, 1, self.hgru_k[idx]] if self.gate_bias_init == 'chronos': bias_init = -tf.log( tf.random_uniform( bias_shape, minval=1, maxval=self.timesteps - 1, dtype=self.dtype)) else: bias_init = tf.ones(bias_shape, dtype=self.dtype) setattr( self, 'gain_bias_%s' % layer, tf.get_variable( name='%s_gain_bias' % self.layer_name,
tensorflow.random_uniform
7,447
import tensorflow as tf type_list = [] for hop_edge_types, count in zip(edge_types, counts): neighbors, weights, types = sample_neighbor( neighbors_list[-1], hop_edge_types, count, default_node=default_node) neighbors_list.append(tf.reshape(neighbors, [-1])) weights_list.append(tf.reshape(weights, [-1])) type_list.append(tf.reshape(weights, [-1])) return neighbors_list, weights_list, type_list
tensorflow.reshape
7,448
import tensorflow as tf def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = tf.concat(facts, 2) if len(facts.get_shape().as_list()) == 2: facts = tf.expand_dims(facts, 1) if time_major: # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2])
tensorflow.expand_dims
7,449
import tensorflow as tf def random_batch(batch_size, config): shape = (batch_size,) + config.input_shape images = tf.random_uniform(shape) labels = tf.random_uniform( [batch_size], minval=0, maxval=config.n_classes, dtype=tf.int32) return images, labels
tensorflow.random_uniform
7,450
import tensorflow as tf self.assertAllClose(1.60944, res) average_loss_per_sequence = tf.nn.seq2seq.sequence_loss( logits, targets, weights,
tensorflow.nn.seq2seq.sequence_loss
7,451
import tensorflow as tf loss = tf.reduce_mean(loss) return loss def contra_step_lossV2(pred, tgt): # Step-wise contrastive loss pred1, pred2 = tf.split(pred, 2, axis=0) tgt1, tgt2 = tf.split(tgt, 2, axis=0) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1) loss = tf.maximum(0.0, (tgt_larg - tgt_small) - (pred_larg - pred_small)) loss = tf.reduce_mean(loss) return loss def contra_step_lossV3(pred, tgt, margin=1.0): # Step-wise contrastive loss pred1, pred2 = tf.split(pred, 2, axis=0) tgt1, tgt2 = tf.split(tgt, 2, axis=0) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1) pred_larg = tf.where(geq, pred1, pred2) pred_small = tf.where(geq, pred2, pred1)
tensorflow.maximum
7,452
import tensorflow as tf (nms_masks1, nms_scores1, nms_classes1, _) = isu.instance_non_maximum_suppression_1d_scores( masks, scores, classes, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=True) nms_masks_expected1 = tf.stack([mask0, mask4]) nms_scores_expected1 = tf.constant([1.0, 0.85], dtype=tf.float32) nms_classes_expected1 = tf.constant([1, 2], dtype=tf.int32) (nms_masks2, nms_scores2, nms_classes2, _) = isu.instance_non_maximum_suppression_1d_scores( masks, scores, classes, min_score_thresh=0.65, min_iou_thresh=0.5,
tensorflow.constant
7,453
from tensorflow.python.ops import state_ops or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'mean', [values, weights]): total = _create_local('total_tensor', shape=values.get_shape()) count = _create_local('count_tensor', shape=values.get_shape()) num_values = array_ops.ones_like(values) if weights is not None: weights = math_ops.to_float(weights) values = math_ops.mul(values, weights) num_values = math_ops.mul(num_values, weights) total_compute_op = state_ops.assign_add(total, values) count_compute_op = state_ops.assign_add(count, num_values) def compute_mean(total, count, name): non_zero_count = math_ops.maximum(count, array_ops.ones_like(count), name=name) return math_ops.truediv(total, non_zero_count, name=name) mean = compute_mean(total, count, 'value') with ops.control_dependencies([total_compute_op, count_compute_op]): update_op = compute_mean(total, count, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, mean)
tensorflow.python.ops.state_ops.assign_add
7,454
from tensorflow.python.framework import ops self._config.task * self._config.training_worker_session_startup_stagger_secs) if sleep_secs: logging.info('Waiting %d secs before starting task %d.', sleep_secs, self._config.task) time.sleep(sleep_secs) # Device allocation device_fn = device_fn or self._device_fn with ops.Graph().as_default() as g, g.device(device_fn): random_seed.set_random_seed(self._config.tf_random_seed) global_step = contrib_framework.create_global_step(g) features, targets = input_fn() self._check_inputs(features, targets) train_op, loss_op = self._get_train_ops(features, targets) return train( graph=g, output_dir=self._model_dir, train_op=train_op,
tensorflow.python.framework.ops.Graph
7,455
import tensorflow as tf tf.reset_default_graph()
tensorflow.reset_default_graph
7,456
import tensorflow as tf tf.logging.info(eval_results) tf.logging.info('Finished model {}.'.format(model_scope)) def main(_): # Using the Winograd non-fused algorithms provides a small performance boost. os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1' gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = FLAGS.gpu_memory_fraction) sess_config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = False, intra_op_parallelism_threads = FLAGS.num_cpu_threads, inter_op_parallelism_threads = FLAGS.num_cpu_threads, gpu_options = gpu_options) # Set up a RunConfig to only save checkpoints once per training cycle. run_config = tf.estimator.RunConfig().replace( save_checkpoints_secs=FLAGS.save_checkpoints_secs).replace( save_checkpoints_steps=None).replace(
tensorflow.GPUOptions
7,457
import tensorflow as tf all_layer_outputs = [] if input_width != hidden_size: prev_output = dense_layer_2d( input_tensor, hidden_size, create_initializer(initializer_range), None, name="embedding_hidden_mapping_in") else: prev_output = input_tensor with tf.variable_scope("transformer", reuse=tf.AUTO_REUSE): for layer_idx in range(num_hidden_layers): group_idx = int(layer_idx / num_hidden_layers * num_hidden_groups) with tf.variable_scope("group_%d" % group_idx): with tf.name_scope("layer_%d" % layer_idx): layer_output = prev_output for inner_group_idx in range(inner_group_num):
tensorflow.variable_scope
7,458
import tensorflow as tf o_d1 = self.general_deconv2d(o_c5, self.base_number_of_features * 8, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_1') o_me1 = tf.concat([o_d1, o_c4], 3) # Skip connection o_d2 = self.general_deconv2d(o_me1, self.base_number_of_features * 4, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_2') o_me2 = tf.concat([o_d2, o_c3], 3) # Skip connection o_d3 = self.general_deconv2d(o_me2, self.base_number_of_features * 2, 3, stride = 2, padding = 'SAME', activation_function = 'relu', do_norm = False, name = name + '_deconv2d_3') o_me3 = tf.concat([o_d3, o_c2], 3) # Skip connection
tensorflow.concat
7,459
import tensorflow as tf """ if stride is None: stride = kernel_size kernel = [1, kernel_size, kernel_size, 1] if data_format == 'NHWC' \ else [1, 1, kernel_size, kernel_size] strides = [1, stride, stride, 1] if data_format == 'NHWC' else [1, 1, stride, stride] return tf.nn.avg_pool(value=inputdata, ksize=kernel, strides=strides, padding=padding, data_format=data_format, name=name) @staticmethod def globalavgpooling(inputdata, data_format='NHWC', name=None): """ :param name: :param inputdata:
tensorflow.nn.avg_pool
7,460
import tensorflow as tf else: self.c, self.q, self.ch, self.qh, self.y1, self.y2, self.qa_id = batch.get_next() # self.word_unk = tf.get_variable("word_unk", shape = [config.glove_dim], initializer=initializer()) self.word_mat = tf.get_variable("word_mat", initializer=tf.constant( word_mat, dtype=tf.float32), trainable=False) self.char_mat = tf.get_variable( "char_mat", initializer=tf.constant(char_mat, dtype=tf.float32))
tensorflow.constant
7,461
import tensorflow as tf [0.95, 0.92, 0.1], [0.1, 0.05, 0.0], [0.2, 0.3, 0.7], [0.1, 0.2, 0.8]], dtype=tf.float32) (nms_masks1, nms_scores1, nms_classes1) = isu.instance_non_maximum_suppression_2d_scores( masks, scores, 3, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=True) nms_masks_expected1 = tf.stack([mask0, mask5, mask4]) nms_scores_expected1 = tf.constant([1.0, 0.8, 0.7], dtype=tf.float32) nms_classes_expected1 = tf.constant([1, 2, 2], dtype=tf.int32) (nms_masks2, nms_scores2, nms_classes2) = isu.instance_non_maximum_suppression_2d_scores( masks, scores, 3, min_score_thresh=0.65, min_iou_thresh=0.5, is_class_agnostic=False) nms_masks_expected2 = tf.stack([mask2, mask0, mask5, mask4]) nms_scores_expected2 = tf.constant([0.95, 1.0, 0.8, 0.7], dtype=tf.float32) nms_classes_expected2 = tf.constant([0, 1, 2, 2], dtype=tf.int32) self.assertAllEqual(nms_masks1.numpy(), nms_masks_expected1.numpy())
tensorflow.constant
7,462
import tensorflow as tf false_fn=lambda: (tf.concat([vx_keys, tf.reshape(u, (-1, 1))], axis=0), tf.constant(1, dtype=tf.int64, name='constant')) ) vx.insert(u, r) for i in tf.range(start=0, limit=z_t_len - self._p + 1, delta=1, dtype=None, name='range'): u = tf.string_join(z_t[i:i + self._p], '') vz_keys, r = tf.cond( tf.greater(vz.lookup(u), -1), true_fn=lambda: (vz_keys, tf.add(vz.lookup(u), 1)), false_fn=lambda: ( tf.concat([vz_keys, tf.reshape(u, (-1, 1))], axis=0), tf.constant(1, dtype=tf.int64)) ) vz.insert(u, r) kk = tf.Variable(0, dtype=tf.int64) for i in tf.range(start=0, limit=tf.size(vx_keys), delta=1, dtype=None, name='range'): for j in tf.range(start=0, limit=tf.size(vz_keys), delta=1, dtype=None, name='range'): to_add = tf.cond( tf.greater(vz.lookup(vx_keys[i]), -1), true_fn=lambda: tf.math.multiply(vx.lookup(vx_keys[i]), vz.lookup(vz_keys[j])), false_fn=lambda: tf.constant(0, dtype=tf.int64)
tensorflow.constant
7,463
import tensorflow as tf coord.join() # Session closed. def test_minimum_batch_size(self): with self.test_session() as session: @dynamic_batching.batch_fn_with_options( minimum_batch_size=2, timeout_ms=1000) def f(a, b): batch_size = tf.shape(a)[0] return a + b, tf.tile([batch_size], [batch_size]) output = f(tf.constant([[1, 3]]), tf.constant([2])) tf.train.start_queue_runners() start = datetime.datetime.now() session.run(output) duration = datetime.datetime.now() - start # There should have been a timeout here because only one sample was added # and the minimum batch size is 2. self.assertLessEqual(.9, duration.total_seconds())
tensorflow.constant
7,464
import tensorflow as tf train_input_fn = input_fn_builder( input_files=input_files, max_seq_length=FLAGS.max_seq_length, max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=True, ) eval_input_fn = input_fn_builder( input_files=input_files, max_seq_length=FLAGS.max_seq_length, max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=False, ) tf.estimator.train_and_evaluate( estimator, train_spec=tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=100), eval_spec=tf.estimator.EvalSpec(input_fn=eval_input_fn, steps=10), ) # if FLAGS.do_train: # tf.logging.info("***** Running training *****") # tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) # train_input_fn = input_fn_builder( # input_files=input_files, # max_seq_length=FLAGS.max_seq_length, # max_predictions_per_seq=FLAGS.max_predictions_per_seq, # is_training=True) # estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps) # if FLAGS.do_eval: # tf.logging.info("***** Running evaluation *****") # tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
tensorflow.estimator.EvalSpec
7,465
import tensorflow as tf next_indices = tf.stack([neighbor.indices[:, 0], next_idx], 1) next_values = weight.values next_shape = [tf.size(nodes), tf.size(next_nodes)] next_adj = tf.sparse.SparseTensor(next_indices, next_values, next_shape)
tensorflow.size
7,466
from tensorflow.python.framework import ops return [input_shape] + ([tensor_shape.vector(vector_dim)] * 4) ops.RegisterShape("Conv2D")(common_shapes.conv2d_shape) ops.RegisterShape("DepthwiseConv2dNative")( common_shapes.depthwise_conv2d_native_shape) ops.RegisterShape("AvgPool")(common_shapes.avg_pool_shape) ops.RegisterShape("MaxPool")(common_shapes.max_pool_shape) @ops.RegisterShape("MaxPoolWithArgmax") def _MaxPoolWithArgMaxShape(op): """Shape function for MaxPoolWithArgmax op.""" return common_shapes.max_pool_shape(op) * 2
tensorflow.python.framework.ops.RegisterShape
7,467
import tensorflow as tf tf.app.flags.DEFINE_bool('RCE_train', False, 'Whether use RCE to train the model.') tf.app.flags.DEFINE_string('attack_method', 'fgsm', 'The attacking method used') tf.app.flags.DEFINE_float('eps', 0.01, 'The eps in attacking methods.') tf.app.flags.DEFINE_string('save_pwd', None, '')
tensorflow.app.flags.DEFINE_float
7,468
import tensorflow as tf if __name__ == "__main__": # flags.mark_flag_as_required("input_file") # flags.mark_flag_as_required("bert_config_file") # flags.mark_flag_as_required("output_dir") tf.app.run()
tensorflow.app.run
7,469
import tensorflow as tf tf.nn.softmax(policy.q_values) * (tf.log(tf.nn.softmax(policy.q_values)) - tf.log(tf.nn.softmax(adaptive_policy.q_values))),
tensorflow.nn.softmax
7,470
import tensorflow as tf self.conv1 = self._conv('conv1', self.x_preprocessed, padding= [[0,0],[3,3],[3,3],[0,0]], num_filters=64, kernel_size=(7, 7), stride=(2, 2), l2_strength=self.wd, bias=self.bias) self.conv1 = self._bn('bn1', self.conv1) self.conv1 = self._relu('relu1', self.conv1) _debug(self.conv1) self.conv1= tf.pad(self.conv1, tf.constant([[0,0],[1,1],[1,1],[0,0]]), "CONSTANT") self.conv1 = tf.nn.max_pool(self.conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID', name='max_pool1') _debug(self.conv1) print('conv1-shape: ' + str(self.conv1.shape.as_list())) with tf.variable_scope('conv2_x'): self.conv2 = self._residual_block('conv2_1', self.conv1, 64) _debug(self.conv2) self.conv2 = self._residual_block('conv2_2', self.conv2, 64) _debug(self.conv2) with tf.variable_scope('conv3_x'): self.conv3 = self._residual_block('conv3_1', self.conv2, 128, pool_first=True, strides=2) _debug(self.conv3) self.conv3 = self._residual_block('conv3_2', self.conv3, 128) _debug(self.conv3) with tf.variable_scope('conv4_x'): self.conv4 = self._residual_block('conv4_1', self.conv3, 256, pool_first=True, strides=2)
tensorflow.variable_scope
7,471
import tensorflow as tf entropy, log_prob): indices = tf.range(0, layer_id, dtype=tf.int32) start_id = 4 * (layer_id - 2) prev_layers = [] for i in range(2): # index_1, index_2 next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm) prev_c, prev_h = next_c, next_h query = anchors_w_1.gather(indices) query = tf.reshape(query, [layer_id, self.lstm_size]) query = tf.tanh(query + tf.matmul(next_h[-1], self.w_attn_2)) query = tf.matmul(query, self.v_attn) logits = tf.reshape(query, [1, layer_id]) if self.temperature is not None: logits /= self.temperature if self.tanh_constant is not None: logits = self.tanh_constant * tf.tanh(logits) index = tf.multinomial(logits, 1) index = tf.to_int32(index)
tensorflow.matmul
7,472
import tensorflow as tf image_height, image_width = tf.shape(images)[1], tf.shape(images)[2] cutout_center_height = tf.random.uniform( shape=[], minval=0, maxval=image_height, dtype=tf.int32) cutout_center_width = tf.random.uniform( shape=[], minval=0, maxval=image_width, dtype=tf.int32) lower_pad = tf.maximum(0, cutout_center_height - length // 2) upper_pad = tf.maximum(0, image_height - cutout_center_height - length // 2) left_pad = tf.maximum(0, cutout_center_width - length // 2) right_pad = tf.maximum(0, image_width - cutout_center_width - length // 2) cutout_shape = [image_height - (lower_pad + upper_pad), image_width - (left_pad + right_pad)] padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]]
tensorflow.maximum
7,473
import tensorflow as tf return 1.0 @property def is_training(self): return self.hparams.mode == tf.estimator.ModeKeys.TRAIN def infer(self, features, *args, **kwargs): # pylint: disable=arguments-differ del args, kwargs x = features["inputs"] batch_size = common_layers.shape_list(x)[0] features["targets"] = tf.zeros(shape=(batch_size, 1, 1, 1)) _, _ = self(features) # pylint: disable=not-callable ops = [glow_ops.get_variable_ddi, glow_ops.actnorm, glow_ops.get_dropout] var_scope = tf.variable_scope("glow/body", reuse=True) # If eps=None, images are sampled from the prior. with arg_scope(ops, init=False), var_scope: predictions, _, _, _ = glow_ops.encoder_decoder( "codec", self.z_sample, self.hparams, eps=None, reverse=True, temperature=self.temperature)
tensorflow.zeros
7,474
import tensorflow as tf self.real_pc_pred, real_pc_end_points = self.get_pred(self.real_pc_rotated) self.real_pc_rot_loss = self.get_loss(self.real_pc_pred, self.rot_label_pl, real_pc_end_points) with tf.variable_scope('generator'): self.generator_out = self.generator(self.noise, self.n_output, **gen_kwargs) self.gen_out_rotated = self.rotate_n_angles(self.generator_out, self.rot_label_pl) self.gen_out_pred, gen_out_end_points = self.get_pred(self.gen_out_rotated) self.gen_out_rot_loss = self.get_loss(self.gen_out_pred, self.rot_label_pl, gen_out_end_points) #classification loss #need to fix if self.ms_task: with tf.variable_scope('mixed'): #add fake pc as a rotation class num_to_add = int(max(self.batch_size/self.num_angles, 1)) idx = tf.range(0, self.batch_size, 1) idx = tf.random_shuffle(idx)[0:num_to_add] self.fake_to_add = tf.gather(self.generator_out, idx) self.mixed_pc = tf.concat([self.real_pc_rotated, self.fake_to_add], 0) self.mixed_label = tf.concat([self.rot_label_pl, tf.constant(self.num_angles, shape = (num_to_add,))], axis = 0) mixed_idx = tf.range(0, self.mixed_label.get_shape().as_list()[0], 1) mixed_idx = tf.random_shuffle(mixed_idx)[0:self.batch_size]
tensorflow.variable_scope
7,475
import tensorflow as tf y_true: tensor, observations. y_pred: tensor, output of network. Returns: loss value, means negative log-likelihood. """ logL = 0 # pre-calculate cumsum cumsum_y_pred = tf.cumsum(y_pred) hazard_ratio = tf.exp(y_pred) cumsum_hazard_ratio = tf.cumsum(hazard_ratio) if self.train_data['ties'] == 'noties': log_risk = tf.log(cumsum_hazard_ratio) likelihood = y_pred - log_risk # dimension for E: np.array -> [None, 1] uncensored_likelihood = likelihood * y_true logL = -tf.reduce_sum(uncensored_likelihood) else: # Loop for death times for t in self.train_data['failures']: tfail = self.train_data['failures'][t] trisk = self.train_data['atrisk'][t] d = len(tfail) dr = len(trisk)
tensorflow.log
7,476
import tensorflow as tf weights_dir='weights'): """Train the model on the specified dataset. Args: data_set: dataset instance to use to access data for training/validation weights_from: str, if not None, initializes model from exisiting weights start_epoch: int, epoch number to start training from e.g. for retarining set the epoch number you want to resume training from summary_every: int, epoch interval to write summary; higher value means lower frequency of summary writing """ with tf.Graph().as_default(), tf.device('/gpu:0'): self._setup_model_loss(num_classes=num_classes) if self.is_summary: self._setup_summaries(self.capped_d_grads, self.capped_g_grads) self._setup_misc() self._print_info(data_set) self._train_semi_supervised(data_set, start_epoch, weights_from, summary_every, model_name, weights_dir) def _train_semi_supervised(self, dataset, start_epoch, weights_from, summary_every, model_name, weights_dir):
tensorflow.Graph
7,477
import tensorflow as tf s = sqrt_diag if diag else sqrt kl_batch = gauss_kl(mu,s,K if shared_k else K_batch) kl_sum = [] for n in range(Datum.N): kl_sum.append(gauss_kl(mu[:, n][:,None], # M x 1 sqrt_diag[:, n][:, None] if diag else sqrt[n, :, :][None, :, :], # 1 x M x M or M x 1 K if shared_k else K_batch[n, :, :][None,:,:])) # 1 x M x M or M x M kl_sum =tf.reduce_sum(kl_sum) assert_almost_equal(kl_sum.eval(), kl_batch.eval()) def tf_kl_1d(q_mu, q_sigma, p_var=1.0): p_var = tf.ones_like(q_sigma) if p_var is None else p_var q_var = tf.square(q_sigma) kl = 0.5 * (q_var / p_var + tf.square(q_mu) / p_var - 1 + tf.log(p_var / q_var)) return tf.reduce_sum(kl) @pytest.mark.parametrize('white', [True, False]) def test_oned(session_tf, white, mu, sqrt, K_batch): """ Check that the KL divergence matches a 1D by-hand calculation. """ m = 0
tensorflow.ones_like
7,478
import tensorflow as tf """ JPEG_OPT = {'fancy_upscaling': True, 'dct_method': 'INTEGER_ACCURATE'} def uint8_resize_bicubic(image, shape): ret = tf.image.resize_bicubic([image], shape) return tf.cast(tf.clip_by_value(ret, 0, 255), tf.uint8)[0] def resize_shortest_edge(image, image_shape, size):
tensorflow.image.resize_bicubic
7,479
import tensorflow as tf alpha=AGENT_ALPHA, dtype=tf.float32) agent_epsgreedy = neural_epsilon_greedy_agent.NeuralEpsilonGreedyAgent( time_step_spec=environment.time_step_spec(), action_spec=environment.action_spec(), reward_network=network, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=LR), emit_policy_info=emit_policy_info, epsilon=EPSILON) agent = exp3_mixture_agent.Exp3MixtureAgent( (agent_linucb, agent_lints, agent_epsgreedy))
tensorflow.compat.v1.train.AdamOptimizer
7,480
import tensorflow as tf for idx, (x, m) in enumerate(zip(xs, ms)): c = c*(1-m) h = h*(1-m) z = tf.matmul(x, wx) + tf.matmul(h, wh) + b i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(c) xs[idx] = h
tensorflow.nn.sigmoid
7,481
import tensorflow as tf x, indices.bin_counts, indices.active_block_indices, dynamic_bsize=block_params.bsize, dynamic_bstride=block_params.bstrides, dynamic_boffset=block_params.boffset, transpose=transpose) # Convolution on patches. if transpose: q = tf.nn.conv2d(p, w, strides, 'VALID', data_format='NCHW', use_cudnn_on_gpu=True) else: q = tf.nn.conv2d(p, w, strides, 'VALID', use_cudnn_on_gpu=True) # Allocate output tensor. if use_var: y = sbnet_module.sparse_scatter_var( q, indices.bin_counts, indices.active_block_indices,
tensorflow.nn.conv2d
7,482
import tensorflow as tf candidate_mention_scores = self.get_mention_scores(candidate_span_emb) # [k, 1] candidate_mention_scores = tf.squeeze(candidate_mention_scores, 1) # [k] k = tf.to_int32(tf.floor(tf.to_float(tf.shape(context_outputs)[0]) * self.config["top_span_ratio"])) top_span_indices = coref_ops.extract_spans(tf.expand_dims(candidate_mention_scores, 0), tf.expand_dims(candidate_starts, 0),
tensorflow.shape
7,483
import tensorflow as tf self.D_B_loss = (self.D_B_loss_real + self.D_B_loss_fake) / 2.0 self.D_A_loss_real = binary_cross_entropy_loss(tf.ones_like(self.D_A_real),self.D_A_real) self.D_A_loss_fake = binary_cross_entropy_loss(tf.zeros_like(self.D_A_fake),self.D_A_fake) self.D_A_loss = (self.D_A_loss_real + self.D_A_loss_fake) / 2.0 self.discriminator_loss = self.D_B_loss + self.D_A_loss self.loss_GABA_sum = tf.summary.scalar("g_loss_a2b", self.loss_GABA) self.loss_GBAB_sum = tf.summary.scalar("g_loss_b2a", self.loss_GBAB) self.g_total_loss_sum = tf.summary.scalar("g_loss", self.generator_loss) self.g_sum = tf.summary.merge([self.loss_GABA_sum,self.loss_GBAB_sum,self.g_total_loss_sum]) self.loss_db_sum = tf.summary.scalar("db_loss", self.D_B_loss) self.loss_da_sum = tf.summary.scalar("da_loss", self.D_A_loss) self.loss_d_sum = tf.summary.scalar("d_loss",self.discriminator_loss)
tensorflow.summary.scalar
7,484
import tensorflow as tf if ex_index < 5: tf.logging.info("*** Example ***") tf.logging.info("guid: %s" % (example.guid))
tensorflow.logging.info
7,485
import tensorflow as tf import numpy as np import tensorflow as tf import layers as L import vat FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('device', '/gpu:0', "device") tf.app.flags.DEFINE_string('dataset', 'cifar10', "{cifar10, svhn}") tf.app.flags.DEFINE_string('log_dir', "", "log_dir") tf.app.flags.DEFINE_integer('seed', 1, "initial random seed") tf.app.flags.DEFINE_bool('validation', False, "") tf.app.flags.DEFINE_integer('batch_size', 32, "the number of examples in a batch") tf.app.flags.DEFINE_integer('ul_batch_size', 128, "the number of unlabeled examples in a batch") tf.app.flags.DEFINE_integer('eval_batch_size', 100, "the number of eval examples in a batch") tf.app.flags.DEFINE_integer('eval_freq', 5, "") tf.app.flags.DEFINE_integer('num_epochs', 120, "the number of epochs for training") tf.app.flags.DEFINE_integer('epoch_decay_start', 80, "epoch of starting learning rate decay") tf.app.flags.DEFINE_integer('num_iter_per_epoch', 400, "the number of updates per epoch") tf.app.flags.DEFINE_float('learning_rate', 0.001, "initial leanring rate") tf.app.flags.DEFINE_float('mom1', 0.9, "initial momentum rate") tf.app.flags.DEFINE_float('mom2', 0.5, "momentum rate after epoch_decay_start")
tensorflow.app.flags.DEFINE_integer
7,486
import tensorflow as tf Returns: A 1-D tensor of length batch_size of same type as logits with softmax focal loss """ with tf.name_scope(scope, 'focal_loss', [cls_preds, onehot_labels]) as sc: logits = tf.convert_to_tensor(cls_preds) onehot_labels = tf.convert_to_tensor(onehot_labels) precise_logits = tf.cast(logits, tf.float32) if ( logits.dtype == tf.float16) else logits onehot_labels = tf.cast(onehot_labels, precise_logits.dtype) predictions = tf.nn.sigmoid(logits) predictions_pt = tf.where(tf.equal(onehot_labels, 1), predictions, 1.-predictions) # add small value to avoid 0 epsilon = 1e-8 alpha_t = tf.scalar_mul(alpha, tf.ones_like(onehot_labels, dtype=tf.float32)) alpha_t = tf.where(tf.equal(onehot_labels, 1.0), alpha_t, 1-alpha_t) losses = tf.reduce_sum(-alpha_t * tf.pow(1. - predictions_pt, gamma) * tf.log(predictions_pt+epsilon), name=name, axis=1) return losses def Evaluate(sess): test_acc = 0.0 test_loss = 0.0 for it in range(test_iteration): batch_data = next(scene_data_val) test_batch_x = batch_data['data'] test_batch_y = batch_data['label']
tensorflow.ones_like
7,487
import tensorflow as tf def random_crop_and_resize(images, ratio=0.8): b, h, w, c = images.get_shape().as_list() ch, cw = map(lambda x: int(x * ratio), (h, w)) crop = tf.random_crop(images, size=[b, ch, cw, 3]) crop = tf.image.resize(crop, [h, w]) return crop def random_apply(fn, image, prob=1.): b, *_ = image.get_shape().as_list() chance = tf.less(tf.random_uniform([b], 0, 1.0), prob) return tf.where(chance, fn(image), tf.identity(image)) def color_distortion(image, s=1.0): lower, upper, x = (1 - 0.8 * s), (1 + 0.8 * s), image x = tf.image.random_brightness(x, max_delta=0.8*s) x = tf.image.random_contrast(x, lower=lower, upper=upper) x = tf.image.random_saturation(x, lower=lower, upper=upper) x = tf.image.random_hue(x, max_delta=0.2*s) x = tf.clip_by_value(x, 0, 1) return x def color_drop(image): image = tf.image.rgb_to_grayscale(image) image = tf.tile(image, [1, 1, 1, 3]) return image # pylint: disable=not-callable @gin.configurable(blacklist=["kwargs"]) class CLGAN(modular_gan.ModularGAN): """Self-Supervised GAN with Contrastive Loss"""
tensorflow.image.random_contrast
7,488
import tensorflow as tf tf.random_normal(shape=util.shape(variable)) * learning_rate for variable in variables ] perturbation_deltas = [ pert - prev_pert for pert, prev_pert in zip(perturbations, previous_perturbations) ] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) with tf.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = tf.sign(x=(unperturbed_loss - perturbed_loss)) deltas = [ delta + direction * perturbation for delta, perturbation in zip(deltas, perturbations) ] return deltas, perturbations num_samples = self.num_samples.value() deltas, perturbations = self.while_loop( cond=util.tf_always_true, body=body, loop_vars=(deltas, previous_perturbations),
tensorflow.sign
7,489
import tensorflow as tf res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"): dec, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2,
tensorflow.global_variables_initializer
7,490
import tensorflow as tf # visualization fig = vis.get_figure() fig.canvas.draw() self.vis_placeholder = tf.placeholder(tf.uint8, ut.fig2rgb_array(fig).shape) self.vis_summary = tf.summary.image('visualization', self.vis_placeholder) # embedding dists = l2(self.embedding_test[:-1] - self.embedding_test[1:]) self.dist = dists metrics = [] metrics.append(tf.summary.histogram('point_distance', dists)) metrics.append(tf.summary.scalar('training/trajectory_length', tf.reduce_sum(dists))) self.blur_ph = tf.placeholder(dtype=tf.float32) metrics.append(tf.summary.scalar('training/blur_sigma', self.blur_ph)) pred = self.embedding_test[1:-1]*2 - self.embedding_test[0:-2] pred_error = l2(pred - self.embedding_test[2:]) mean_dist, mean_pred_error = tf.reduce_mean(dists), tf.reduce_mean(pred_error) improvement = (mean_dist-mean_pred_error)/mean_dist
tensorflow.summary.histogram
7,491
import tensorflow as tf """ with tf.name_scope(name): private_samples -= tf.reduce_mean(private_samples, 0) shared_samples -= tf.reduce_mean(shared_samples, 0) private_samples = tf.nn.l2_normalize(private_samples, 1) shared_samples = tf.nn.l2_normalize(shared_samples, 1) correlation_matrix = tf.matmul(private_samples, shared_samples, transpose_a=True) cost = tf.reduce_mean(tf.square(correlation_matrix)) * weight cost = tf.where(cost > 0, cost, 0, name='value')
tensorflow.nn.l2_normalize
7,492
import tensorflow as tf zip(grads, model.trainable_variables), global_step=global_step) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for _ in range(1): sess.run(train_op) # Benchmark related def device_and_data_format(): return ("/gpu:0", "channels_first") if tf.test.is_gpu_available() else ("/cpu:0", "channels_last") def random_batch(batch_size, config): shape = (batch_size,) + config.input_shape images = tf.random_uniform(shape) labels = tf.random_uniform( [batch_size], minval=0, maxval=config.n_classes, dtype=tf.int32) return images, labels
tensorflow.test.is_gpu_available
7,493
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc hparams = get_default_hparams() tf.enable_resource_variables() for sample_size in [10, 25, 50, 100, 200]: hparams.n_samples = sample_size tf.reset_default_graph() with tf.Graph().as_default(): energy_fn, _, _ = l2hmc.get_scg_energy_fn() x = tf.random_normal([hparams.n_samples, hparams.x_dim], dtype=tf.float32) dynamics = l2hmc.Dynamics( x_dim=hparams.x_dim, minus_loglikelihood_fn=energy_fn, n_steps=hparams.n_steps, eps=hparams.eps) loss, _, _ = l2hmc.compute_loss(dynamics, x) optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate) train_op, loss, _ = graph_step(dynamics, optimizer, x) # Single thread; fairer comparison against eager session_conf = tf.ConfigProto(inter_op_parallelism_threads=1) with tf.Session(config=session_conf) as sess: sess.run(tf.global_variables_initializer()) # Warmup to reduce initialization effect when timing for _ in range(hparams.n_warmup_iters): _, _ = sess.run([train_op, loss])
tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.compute_loss
7,494
import tensorflow as tf 'weights', [num_channels_in, num_out_channels], self.data_type, tf.random_normal_initializer(stddev=np.sqrt(init_factor / (num_channels_in)))) biases = tf.get_variable('biases', [num_out_channels], self.data_type, tf.constant_initializer(0.0)) logits = tf.matmul(input_layer, kernel) + biases if activation == 'relu': affine1 = tf.nn.relu(logits, name=name) elif activation == 'linear' or activation is None: affine1 = logits
tensorflow.constant_initializer
7,495
import tensorflow as tf if pos is not None: pos = tf.reshape(pos, [-1, 1]) pos = tf.minimum(pos, encoder_input_length - 1) if pos is not None and encoder.attn_window_size > 0: # `pred_edits` scenario, where we know the aligned pos # when the windows size is non-zero, we concatenate consecutive encoder states # and map it to the right attention vector size. weights = tf.to_float(tf.one_hot(tf.to_int32(tf.squeeze(pos, axis=1)), depth=attn_length)) weighted_average = [] for offset in range(-encoder.attn_window_size, encoder.attn_window_size + 1): pos_ = pos + offset pos_ = tf.minimum(pos_, encoder_input_length - 1) pos_ = tf.maximum(pos_, 0) # TODO: when pos is < 0, use <S> or </S> weights_ = tf.to_float(tf.one_hot(tf.to_int32(tf.squeeze(pos_, axis=1)), depth=attn_length))
tensorflow.squeeze
7,496
from tensorflow.python.ops import variable_scope if mode_gen == 'ce_train': accuracy = _mask_and_accuracy(vocab_scores, answer_batch, loss_weights) return accuracy, self._loss, sampled_words else: return None, self._loss, sampled_words def calculate_encoder_features(self, encoder_states, encoder_dim): options = self.options input_shape = tf.shape(encoder_states) batch_size = input_shape[0] passage_len = input_shape[1] with variable_scope.variable_scope("attention_decoder"): encoder_features = tf.expand_dims(encoder_states, axis=2) # now is shape [batch_size, passage_len, 1, encoder_dim] W_h = variable_scope.get_variable("W_h", [1, 1, encoder_dim, options.attention_vec_size]) self.W_h = W_h encoder_features = nn_ops.conv2d(encoder_features, W_h, [1, 1, 1, 1], "SAME") # [batch_size, passage_len, 1, attention_vec_size] encoder_features = tf.reshape(encoder_features, [batch_size, passage_len, options.attention_vec_size]) return encoder_features def decode_mode(self, word_vocab, beam_size, state_t_1, context_t_1, coverage_t_1, word_t, encoder_states, encoder_features, passage_word_idx, passage_mask): options = self.options
tensorflow.python.ops.variable_scope.variable_scope
7,497
import tensorflow as tf :param x: [Tensor] [N, H, W, C]. input tensor, dtype float32. :param ksize: [list] List of 4 int. Sparse convolution kernel size. :param strides: [list] List of 4 int. Sparse convolution stride size. :param padding: [string] `VALID` or `SAME`, padding method for sparse convolution. :param bsize [list] List of 4 int. Block size. Optional. :param bstrides: [list] List of 4 int. Block strides. Optional. :return [Tensor] [N, H+Ph, W+Pw, C]. Padded input tensor. """ x_shape = tf.shape(x) if padding == 'SAME': pad_h0, pad_h1, pad_w0, pad_w1 = calc_padding_4d(x_shape, ksize, strides, padding) if bstrides is not None: # Here we do not use the standard padding on the right hand side. # If the convolution results is larger than expected, the scatter function will not use # out-of-boundary points. assert bsize is not None, 'Must pass in bsize and bstrides together.'
tensorflow.shape
7,498
import tensorflow.contrib.graph_editor as ge def capture_ops(): """Decorator to capture ops created in the block. with capture_ops() as ops: # create some ops print(ops) # => prints ops created. """ micros = int(time.time()*10**6) scope_name = str(micros) op_list = [] with tf.name_scope(scope_name): yield op_list g = tf.get_default_graph() op_list.extend(ge.select_ops(scope_name+"/.*", graph=g)) def _to_op(tensor_or_op): if hasattr(tensor_or_op, "op"): return tensor_or_op.op return tensor_or_op def _to_ops(iterable): if not _is_iterable(iterable): return iterable return [_to_op(i) for i in iterable] def _is_iterable(o): try:
tensorflow.contrib.graph_editor.select_ops
7,499