seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf if not flat: assert(len(shape) > 1) nh = h[0].get_shape()[-1].value return tf.reshape(tf.concat(axis=1, values=h), [-1, nh]) else: return tf.reshape(tf.stack(values=h, axis=1), [-1])
tensorflow.concat
3,500
import tensorflow as tf ignored_matches = tf.logical_and( ignored_matches, tf.less( matched_iou, self._config_dict['foreground_iou_threshold'])) background_indicator = tf.logical_or(negative_matches, ignored_matches) # re-assign negatively matched boxes to the background class. matched_gt_boxes = tf.where( tf.tile(tf.expand_dims(background_indicator, -1), [1, 1, 4]), tf.zeros_like(matched_gt_boxes), matched_gt_boxes) matched_gt_classes = tf.where( background_indicator, tf.zeros_like(matched_gt_classes), matched_gt_classes) matched_gt_indices = tf.where( background_indicator,
tensorflow.expand_dims
3,501
import tensorflow as tf y_ (tf.placeholder): Input result vector. cross_entropy (tf.Operation): Final layer of network. cross_entropy_grads (tf.Operation): Gradient computation. sess (tf.Session): Session used for training. variables (TensorFlowVariables): Extracted variables and methods to manipulate them. """ def __init__(self, shape): """Creates a LinearModel object.""" x = tf.placeholder(tf.float32, [None, shape[0]]) w = tf.Variable(tf.zeros(shape)) b = tf.Variable(tf.zeros(shape[1])) self.x = x self.w = w self.b = b y = tf.nn.softmax(tf.matmul(x, w) + b) y_ = tf.placeholder(tf.float32, [None, shape[1]]) self.y_ = y_ cross_entropy = tf.reduce_mean( -tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]) ) self.cross_entropy = cross_entropy self.cross_entropy_grads = tf.gradients(cross_entropy, [w, b])
tensorflow.zeros
3,502
import tensorflow as tf if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*" tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape, init_string) output_spec = None if mode == tf.estimator.ModeKeys.PREDICT:
tensorflow.logging.info
3,503
import tensorflow as tf self.R = tf.placeholder(tf.float32, [None, ], name='R') # input Reward self.a = tf.placeholder(tf.float32, [None, self.num_a], name='a') # input Action onehot for agent1 self.done = tf.placeholder(tf.float32, [None, ], name='done') # input Done info ??? self.q_m_ = tf.placeholder(tf.float32, [None, ], name='q_value_next_max') self.q_target = tf.placeholder(tf.float32, [None,], name='q_tot_target') w_initializer, b_initializer = tf.random_normal_initializer(0., 0.1), tf.constant_initializer(0.0) # ------------------ build evaluate_net ------------------ with tf.variable_scope('eval_net'): a_fc1 = tf.layers.dense(self.s, 128, tf.nn.relu, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='agent_fc1_e') # a_fc2 = tf.layers.dense(a_fc1, 128, tf.nn.relu, kernel_initializer=w_initializer,
tensorflow.constant_initializer
3,504
import tensorflow as tf def get_box_indices(proposals): proposals_shape = proposals.get_shape().as_list() if any(dim is None for dim in proposals_shape): proposals_shape = tf.shape(proposals) ones_mat = tf.ones(proposals_shape[:2], dtype=tf.int32) multiplier = tf.expand_dims( tf.range(start=0, limit=proposals_shape[0]), 1) return tf.reshape(ones_mat * multiplier, [-1]) net = image_features with slim.arg_scope(self._conv_hyperparams): net = slim.conv2d(net, self._depth, [1, 1], scope='reduce_depth')
tensorflow.range
3,505
import tensorflow as tf initializer=tf.constant_initializer(self.vocab.char_embeddings), trainable=True ) self.ch_len = tf.reshape(tf.reduce_sum( tf.cast(tf.cast(self.ch, tf.bool), tf.int32), axis=2), [-1]) self.qh_len = tf.reshape(tf.reduce_sum( tf.cast(tf.cast(self.qh, tf.bool), tf.int32), axis=2), [-1]) N, PL, QL, CL, d, dc, nh = self._params() if self.config.fix_pretrained_vector: dc = self.char_mat.get_shape()[-1] with tf.variable_scope("Input_Embedding_Layer"):
tensorflow.cast
3,506
import tensorflow as tf def file_based_input_fn_builder(input_file, seq_length, is_training, 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([seq_length], tf.int64), "is_real_example": tf.FixedLenFeature([1], 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.
tensorflow.FixedLenFeature
3,507
import tensorflow as tf """Returns `model_fn` closure for TPUEstimator.""" 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)) input_ids = features["input_ids"]
tensorflow.logging.info
3,508
import tensorflow as tf name: string, name of the Op. Returns: TensorTrain containing an identity TT-matrix of size np.prod(shape) x np.prod(shape) """ shape = np.array(shape) # In this special case shape is in the same format as in the TT-tensor case _validate_input_parameters(is_tensor=True, shape=shape) num_dims = shape.size tt_ranks = np.ones(num_dims + 1) with tf.name_scope(name): tt_cores = num_dims * [None] for i in range(num_dims): curr_core_shape = (1, shape[i], shape[i], 1) tt_cores[i] = tf.reshape(tf.eye(shape[i], dtype=dtype), curr_core_shape) true_shape = np.vstack([shape, shape]) return TensorTrain(tt_cores, true_shape, tt_ranks) def matrix_ones(shape, dtype=tf.float32, name='t3f_matrix_ones'): """Generate a TT-matrix of the given shape with each entry equal to 1.
tensorflow.name_scope
3,509
import tensorflow as tf input_shape = tf.shape(decoder_inputs) batch_size = input_shape[0] time_steps = input_shape[1] scope_name = 'decoder_{}'.format(decoder.name) scope_name += '/' + '_'.join(encoder.name for encoder in encoders) def embed(input_): embedded_input = tf.nn.embedding_lookup(embedding, input_) if decoder.use_dropout and decoder.word_keep_prob is not None: noise_shape = [1, 1] if decoder.pervasive_dropout else [tf.shape(input_)[0], 1] embedded_input = tf.nn.dropout(embedded_input, keep_prob=decoder.word_keep_prob, noise_shape=noise_shape) if decoder.use_dropout and decoder.embedding_keep_prob is not None: size = tf.shape(embedded_input)[1] noise_shape = [1, size] if decoder.pervasive_dropout else [tf.shape(input_)[0], size] embedded_input = tf.nn.dropout(embedded_input, keep_prob=decoder.embedding_keep_prob, noise_shape=noise_shape) return embedded_input def get_cell(input_size=None, reuse=False): cells = [] for j in range(decoder.layers): input_size_ = input_size if j == 0 else cell_output_size if decoder.cell_type.lower() == 'lstm': cell = CellWrapper(BasicLSTMCell(decoder.cell_size, reuse=reuse))
tensorflow.shape
3,510
import tensorflow as tf tf.summary.scalar('loss', self.loss) # Create optimizer ops self.global_step = tf.Variable(0, trainable=False, name='global_step') opt = tf.train.RMSPropOptimizer(self.config['learning_rate']) with tf.control_dependencies(update_ops): self.trainer = opt.apply_gradients( gradvars, global_step=self.global_step) def _eval_graph(self, data): tower_metrics = self._gpu_tower(data, Mode.EVAL) with tf.device('/cpu:0'): self.metrics = {m: tf.reduce_mean(tf.stack([t[m] for t in tower_metrics])) for m in tower_metrics[0]} def _pred_graph(self, data): with tf.name_scope('pred'): with tf.device('/gpu:0'): pred_out = self._model(data, Mode.PRED, **self.config) self.pred_out = {n: tf.identity(p, name=n) for n, p in pred_out.items()} def _build_graph(self): # Training and evaluation network, if tf datasets provided if self.datasets:
tensorflow.stack
3,511
import tensorflow as tf 0. """ if not isinstance(tt, TensorTrainBase): raise ValueError("`tt` has to be a Tensor Train object") else: shape = shapes.lazy_raw_shape(tt) # I guess variables=tt.tt_cores is not needed here since the output of # the function doesn't depend on the values of the TT-cores, only on their # shapes etc. But I'm not 100% sure. with tf.name_scope(name): if tt.is_tt_matrix(): return matrix_zeros(shape, dtype=tt.dtype) else: return tensor_zeros(shape[0, :], dtype=tt.dtype) def random_tensor(shape, tt_rank=2, mean=0., stddev=1., dtype=tf.float32, name='t3f_random_tensor'): """Generate a random TT-tensor of the given shape with given mean and stddev.
tensorflow.name_scope
3,512
import tensorflow as tf wshape = [rf, rf, nin, nf] with tf.variable_scope(scope): w = tf.get_variable("w", wshape, initializer=ortho_init(init_scale)) b = tf.get_variable("b", bias_var_shape, initializer=tf.constant_initializer(0.0)) if not one_dim_bias and data_format == 'NHWC': b = tf.reshape(b, bshape) return tf.nn.conv2d(x, w, strides=strides, padding=pad, data_format=data_format) + b def fc(x, scope, nh, *, init_scale=1.0, init_bias=0.0): with tf.variable_scope(scope): nin = x.get_shape()[1].value w = tf.get_variable("w", [nin, nh], initializer=ortho_init(init_scale)) b = tf.get_variable("b", [nh], initializer=tf.constant_initializer(init_bias)) return tf.matmul(x, w)+b def batch_to_seq(h, nbatch, nsteps, flat=False): if flat: h = tf.reshape(h, [nbatch, nsteps]) else: h = tf.reshape(h, [nbatch, nsteps, -1]) return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)] def seq_to_batch(h, flat = False): shape = h[0].get_shape().as_list()
tensorflow.constant_initializer
3,513
import tensorflow as tf # Unnecessary, if you have already sorted when making tfrecord and no data augmentation. gtboxes_and_label_q = tf.py_func(func=re_order, inp=[tf.reshape(gtboxes_and_label_q, [-1, 9]), True], Tout=[tf.float32]) gtboxes_and_label_q = tf.reshape(gtboxes_and_label_q, [cfgs.BATCH_SIZE, -1, 9]) img = inputs_list[i][0] img_shape = inputs_list[i][-2:] h_crop = tf.reduce_max(img_shape[0]) w_crop = tf.reduce_max(img_shape[1]) img = tf.image.crop_to_bounding_box(image=img, offset_height=0, offset_width=0, target_height=tf.cast(h_crop, tf.int32), target_width=tf.cast(w_crop, tf.int32)) outputs = fcos.build_whole_detection_network(input_img_batch=img,
tensorflow.reduce_max
3,514
import tensorflow as tf def apply_optimizers(objectives, trainer, config): # Make sure all losses are computed and apply loss scales. processed = [] values = [ob.value for ob in objectives] for ob in objectives: loss = {min: ob.value, max: -ob.value}[ob.goal] loss *= config.loss_scales[ob.name] with tf.control_dependencies(values): loss = tf.identity(loss) processed.append(ob._replace(value=loss, goal=min)) # Merge objectives that operate on the whole model to compute only one # backward pass and to share optimizer statistics. objectives = [] losses = []
tensorflow.control_dependencies
3,515
import tensorflow as tf # Optionally prepend a special token if self.prepend_token is not None: tokens = tf.concat([[self.prepend_token], tokens], 0) # Optionally append a special token
tensorflow.concat
3,516
import tensorflow as tf tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False d = tf.contrib.layers.conv2d(layer_input,filters,kernel_size=f_size,stride=2, padding='SAME') if norm: d = tf.contrib.layers.batch_norm(d) d = lrelu(d,alpha=0.2)
tensorflow.contrib.layers.conv2d
3,517
import tensorflow as tf encode = tf.placeholder(tf.int32, shape=[None], name="encode") decode = tf.placeholder(tf.int32, shape=[decode_max_length + 2], name="decode") weight = tf.placeholder(tf.float32, shape=[decode_max_length + 1], name="weight") queue = tf.PaddingFIFOQueue(capacity = capacity,
tensorflow.placeholder
3,518
import tensorflow as tf ent_coef_loss, entropy_optimizer = None, None if not isinstance(self.ent_coef, float): ent_coef_loss = -tf.reduce_mean( self.log_ent_coef * tf.stop_gradient(logp_pi + self.target_entropy)*self.weight_ph) entropy_optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate_ph) # Compute the policy loss # Alternative: policy_kl_loss = tf.reduce_mean(logp_pi - min_qf_pi)
tensorflow.train.AdamOptimizer
3,519
import tensorflow as tf original_image_shape = image.shape simulated_image = tf.transpose(tf.matmul(product2, tf.reshape(tf.transpose(image, perm=[2, 0, 1]), (image.shape[2], image.shape[0] * image.shape[1]))), perm=[1, 0]) return tf.reshape(simulated_image, original_image_shape)
tensorflow.transpose
3,520
import tensorflow as tf num_items=self.train_set.num_items, emb_size=self.num_factors, reg_user=self.regs[0], reg_item=self.regs[1], seed=self.seed) logits = tf.layers.dense(self.interaction, units=1, name='logits', kernel_initializer=tf.initializers.lecun_uniform(self.seed)) self.prediction = tf.nn.sigmoid(logits) self.loss = loss_fn(labels=self.labels, logits=logits)
tensorflow.initializers.lecun_uniform
3,521
import tensorflow as tf self.logits1, self.logits2 = [l for l in self.logits] outer = tf.matmul(tf.expand_dims(tf.nn.softmax(self.logits1), axis=2), tf.expand_dims(tf.nn.softmax(self.logits2), axis=1)) outer = tf.matrix_band_part(outer, 0, self.max_a_len) self.yp1 = tf.argmax(tf.reduce_max(outer, axis=2), axis=1) self.yp2 = tf.argmax(tf.reduce_max(outer, axis=1), axis=1) def _compute_loss(self): def focal_loss(logits, labels, weights=None, alpha=0.25, gamma=2): logits = tf.nn.sigmoid(logits) zeros = array_ops.zeros_like(logits, dtype=logits.dtype) pos_p_sub = array_ops.where(labels > zeros, labels - logits, zeros) neg_p_sub = array_ops.where(labels > zeros, zeros, logits)
tensorflow.reduce_max
3,522
import tensorflow as tf tf.summary.scalar('learning_rate', 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 cls_accuracy = tf.metrics.accuracy(glabels, predictions['classes']) metrics = {'cls_accuracy': cls_accuracy}
tensorflow.control_dependencies
3,523
import tensorflow as tf mask4 = tf.constant([[0, 0], [0, 0]], dtype=tf.float32) mask5 = tf.constant([[1, 0], [1, 0]], dtype=tf.float32)
tensorflow.constant
3,524
import tensorflow as tf reg = tf.contrib.layers.l2_regularizer(1e-3) with tf.variable_scope(name, reuse=reuse): layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg) layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg) mu = tf.layers.dense(layer_a2, self.a_dim, tf.nn.tanh, kernel_regularizer=reg) sigma = tf.layers.dense(layer_a2, self.a_dim, tf.nn.softplus, kernel_regularizer=reg) # sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5)) sigma = tf.clip_by_value(sigma, 0.0, 1.0) norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return norm_dist, params class PPO_LSTM(Base):
tensorflow.clip_by_value
3,525
import tensorflow as tf hparams = { "type": tf.train.MomentumOptimizer(0.001, 0.9)
tensorflow.train.MomentumOptimizer
3,526
import tensorflow as tf dtype=self.dtype, initializer=initialization.xavier_initializer( shape=bias_shape, dtype=self.dtype, uniform=self.normal_initializer, mask=None))) else: setattr( self, 'gamma_%s' % layer, tf.constant(1.)) if self.multiplicative_excitation: if self.lesion_kappa: setattr( self, 'kappa_%s' % layer, tf.constant(0.)) else: setattr(
tensorflow.constant
3,527
import tensorflow as tf 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'])
tensorflow.summary.scalar
3,528
import tensorflow as tf 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'])
tensorflow.train.MomentumOptimizer
3,529
import tensorflow as tf centers_batch = tf.gather(centers, label) diff = (1 - alfa) * (centers_batch - features) centers = tf.scatter_sub(centers, label, diff) # centers = tf.nn.l2_normalize(centers, 1, 1e-10, name='centers_norm') loss = tf.reduce_mean(tf.square(features - centers_batch)) return loss, centers def focal_loss(onehot_labels, cls_preds,
tensorflow.square
3,530
import tensorflow as tf beta = tf.Variable(tf.constant(0.0, shape=[num_channels]), name='beta', trainable=True) gamma = tf.Variable(tf.constant(1.0, shape=[num_channels]), name='gamma', trainable=True) batch_mean, batch_var = tf.nn.moments(inputs, moments_dims, name='moments') decay = bn_decay if bn_decay is not None else 0.9 ema = tf.train.ExponentialMovingAverage(decay=decay) # Operator that maintains moving averages of variables. ema_apply_op = tf.cond(is_training, lambda: ema.apply([batch_mean, batch_var]), lambda: tf.no_op()) # Update moving average and return current batch's avg and var. def mean_var_with_update(): with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) # ema.average returns the Variable holding the average of var. mean, var = tf.cond(is_training, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var))) normed = tf.nn.batch_normalization(inputs, mean, var, beta, gamma, 1e-3) return normed def batch_norm_for_fc(inputs, is_training, bn_decay, scope): """ Batch normalization on FC data. Args: inputs: Tensor, 2D BxC input
tensorflow.identity
3,531
import tensorflow as tf return { "eval_accuracy": accuracy, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits, is_real_example]) output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, eval_metrics=eval_metrics, scaffold_fn=scaffold_fn) else: output_spec = tf.contrib.tpu.TPUEstimatorSpec(
tensorflow.contrib.tpu.TPUEstimatorSpec
3,532
import tensorflow as tf Learning rate starting from `learning_rate` then increasing. It is computed as:: decayed_learning_rate = (max_lr - learning_rate) * (floor(global_step / step_size) - global_step / step_size) + learning_rate """ with tf.name_scope(name): learning_rate = tf.cast(learning_rate, dtype=tf.float32) global_step = tf.cast(global_step, dtype=tf.float32) step_size = tf.cast(step_size, dtype=tf.float32) max_lr = tf.cast(max_lr, dtype=tf.float32) if mode == 'tri': periodic_comp = tf.mod((global_step + step_size / 4) / step_size, 1)
tensorflow.name_scope
3,533
from tensorflow.python.framework import ops Returns: A `Tensor` with type `tf.float32`. The max pooled output tensor. """ with ops.op_scope([value], name, "MaxPool") as name: value = ops.convert_to_tensor(value, name="input") return gen_nn_ops._max_pool(value, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name) ops.RegisterShape("Relu")(common_shapes.unchanged_shape) ops.RegisterShape("Relu6")(common_shapes.unchanged_shape) ops.RegisterShape("Elu")(common_shapes.unchanged_shape) ops.RegisterShape("Softplus")(common_shapes.unchanged_shape) ops.RegisterShape("Softsign")(common_shapes.unchanged_shape) @ops.RegisterShape("ReluGrad") @ops.RegisterShape("Relu6Grad") @ops.RegisterShape("EluGrad") @ops.RegisterShape("SoftplusGrad") @ops.RegisterShape("SoftsignGrad") def _BinaryElementwiseShape(op): """Returns same shape as both inputs to op. Args:
tensorflow.python.framework.ops.RegisterShape
3,534
from tensorflow.python.ops import math_ops appropriately and whose value matches `mean_value`. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, 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]):
tensorflow.python.ops.math_ops.mul
3,535
from tensorflow.python.framework import ops `false_negatives` variables appropriately, and whose value matches `recall`. Raises: ValueError: If `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ default_name = _at_k_name('recall', k, class_id=class_id) with ops.name_scope(name, default_name, (predictions, labels)) as scope: _, top_k_idx = nn.top_k(predictions, k) top_k_idx = math_ops.to_int64(top_k_idx) weights = _mask_weights(ignore_mask, weights) tp, tp_update = _streaming_sparse_true_positive_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights) fn, fn_update = _streaming_sparse_false_negative_at_k( predictions_idx=top_k_idx, labels=labels, k=k, class_id=class_id, weights=weights)
tensorflow.python.framework.ops.name_scope
3,536
import tensorflow as tf 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], NUM_OF_CLASSESS]) W_t3 = utils.weight_variable([16, 16, NUM_OF_CLASSESS, deconv_shape2[3].value], name="W_t3") b_t3 = utils.bias_variable([NUM_OF_CLASSESS], name="b_t3") conv_t3 = 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 def train(loss_val, var_list): optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate) grads = optimizer.compute_gradients(loss_val, var_list=var_list) if FLAGS.debug: # print(len(var_list)) for grad, var in grads: utils.add_gradient_summary(grad, var)
tensorflow.argmax
3,537
import tensorflow as tf loss=loss, train_op=train_op, training_hooks=training_hooks) if output_type == "sess": try: pred_label = tf.argmax(distillation_loss["st_logits"], axis=-1, output_type=tf.int32) correct = tf.equal( tf.cast(tf.ones_like(label_ids, dtype=tf.int32), tf.int32), tf.cast(pred_label, tf.int32) ) st_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) pred_label = tf.argmax(distillation_loss["te_logits"], axis=-1, output_type=tf.int32) correct = tf.equal( tf.cast(tf.zeros_like(label_ids, dtype=tf.int32), tf.int32), tf.cast(pred_label, tf.int32) ) te_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) except: te_accuracy = tf.constant(0.0)
tensorflow.cast
3,538
import tensorflow as tf ob_space: observation space (should be one of gym.spaces) batch_size: batch size for input (default is None, so that resulting input placeholder can take tensors with any batch size) name: tensorflow variable name for input placeholder returns: tuple (input_placeholder, processed_input_tensor) ''' if isinstance(ob_space, Discrete): input_x = tf.placeholder(shape=(batch_size,), dtype=tf.int32, name=name) processed_x = tf.to_float(tf.one_hot(input_x, ob_space.n)) return input_x, processed_x elif isinstance(ob_space, Box): input_shape = (batch_size,) + ob_space.shape input_x = tf.placeholder(shape=input_shape, dtype=ob_space.dtype, name=name)
tensorflow.placeholder
3,539
import tensorflow as tf self.datasets[n] = d # Perform compatibility checks with the inputs of the child model for i, spec in self.input_spec.items(): assert i in output_shapes tf.TensorShape(output_shapes[i]).assert_is_compatible_with( tf.TensorShape(spec['shape'])) # Used for input shapes of the prediction network if self.data_shape is None: self.data_shape = output_shapes # Handle for the feedable iterator self.handle = tf.placeholder(tf.string, shape=[]) iterator = tf.data.Iterator.from_string_handle( self.handle, output_types, output_shapes) data = iterator.get_next() # Build the actual training and evaluation models self._train_graph(data) self._eval_graph(data) self.summaries = tf.summary.merge_all() # Prediction network with feed_dict self.pred_in = {i: tf.placeholder(self.input_spec[i]['type'], shape=s, name=i) for i, s in self.data_shape.items()}
tensorflow.placeholder
3,540
import tensorflow as tf start_label = tf.one_hot(self.start_label, tf.shape(self.logits1)[1], axis=1)
tensorflow.shape
3,541
import tensorflow as tf with tf.Session(): coord = tf.train.Coordinator() tf.train.start_queue_runners(coord=coord) time.sleep(_SLEEP_TIME) coord.request_stop() # Calls close operation. 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.
tensorflow.shape
3,542
import tensorflow as tf images, model_options=model_options, image_pyramid=image_pyramid, is_training=False, fine_tune_batch_norm=False) predictions = {} for output in sorted(outputs_to_scales_to_logits): scales_to_logits = outputs_to_scales_to_logits[output] logits = tf.image.resize_bilinear( scales_to_logits[_MERGED_LOGITS_SCOPE], tf.shape(images)[1:3], align_corners=True) predictions[output] = tf.argmax(logits, 3) return predictions def scale_dimension(dim, scale): """Scales the input dimension. Args:
tensorflow.shape
3,543
import tensorflow as tf train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file) tf.logging.info("***** Running training *****")
tensorflow.logging.info
3,544
import tensorflow as tf # Here comes a sample Seq2Seq model using GRU cells. def SampleGRUSeq2Seq(enc_inp, dec_inp, weights): """Example sequence-to-sequence model that uses GRU cells.""" def GRUSeq2Seq(enc_inp, dec_inp): cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(24)] * 2, state_is_tuple=True) return tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=classes, num_decoder_symbols=classes, embedding_size=24, output_projection=(w, b)) targets = [dec_inp[i+1] for i in range(len(dec_inp) - 1)] + [0] def SampledLoss(labels, inputs):
tensorflow.nn.seq2seq.embedding_attention_seq2seq
3,545
import tensorflow as tf + self.alpha * ( tf.matmul( tf.nn.relu(state), self.W_rec * self.rec_Connectivity,
tensorflow.nn.relu
3,546
import tensorflow as tf model = registry.model(hparams.policy_network)( hparams, tf.estimator.ModeKeys.TRAIN ) try: num_target_frames = hparams.video_num_target_frames except AttributeError: num_target_frames = 1 target_value_shape_suffix = [num_target_frames] if distributional_size > 1: target_value_shape_suffix = [num_target_frames, distributional_size] features = { "inputs": observations, "epoch": tf.constant(epoch + 1), "input_action": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "input_reward": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "targets": tf.zeros(obs_shape[:1] + [num_target_frames] + obs_shape[2:]), "target_action": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_reward": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_policy": tf.zeros( obs_shape[:1] + [num_target_frames] + [action_space.n]), "target_value": tf.zeros( obs_shape[:1] + target_value_shape_suffix) } model.distributional_value_size = max(distributional_size, 1) model.use_epochs = hparams.use_epochs with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
tensorflow.zeros
3,547
from tensorflow.contrib.learn.python.learn.summary_writer_cache import SummaryWriterCache def __init__(self, every_n_steps=100, output_dir=None, summary_writer=None): super(StepCounter, self).__init__(every_n_steps=every_n_steps) self._summary_tag = "global_step/sec" self._last_reported_step = None self._last_reported_time = None self._summary_writer = summary_writer if summary_writer is None and output_dir: self._summary_writer = SummaryWriterCache.get(output_dir) def set_estimator(self, estimator): super(StepCounter, self).set_estimator(estimator) if self._summary_writer is None: self._summary_writer = SummaryWriterCache.get(estimator.model_dir) def every_n_step_end(self, current_step, outputs): current_time = time.time()
tensorflow.contrib.learn.python.learn.summary_writer_cache.SummaryWriterCache.get
3,548
import tensorflow as tf facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] queries = tf.tile(query, [1, tf.shape(facts)[1]]) queries = tf.reshape(queries, tf.shape(facts)) 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) d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]]) scores = d_layer_3_all # Mask # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T] key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(scores) * (-2 ** 32 + 1) scores = tf.where(key_masks, scores, paddings) # [B, 1, T] # Scale # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5) # Activation if softmax_stag: scores = tf.nn.softmax(scores) # [B, 1, T] # Weighted sum
tensorflow.expand_dims
3,549
import tensorflow as tf """Preprocessing for LM1B: filter out targets exceeding maximum length.""" def train_right_length(example, target): l = tf.maximum(tf.shape(example['inputs'])[0], tf.shape(target)[0]) return tf.less(l, max_length + 1) def eval_right_length(example, target): l = tf.maximum(tf.shape(example['inputs'])[0], tf.shape(target)[0]) return tf.less(l, max_eval_length + 1) if max_length > 0 and training: dataset = dataset.filter(train_right_length) if max_eval_length > 0 and not training:
tensorflow.shape
3,550
import tensorflow as tf def bias_varibale(shape): initial = tf.constant(0.1, shape=shape, name='Bias') return tf.Variable(initial)
tensorflow.constant
3,551
import tensorflow as tf if is_training: # during training, compute the end logits based on the # ground truth of the start position start_positions = tf.reshape(features["start_positions"], [-1]) start_index = tf.one_hot(start_positions, depth=seq_len, axis=-1, dtype=tf.float32) start_features = tf.einsum("lbh,bl->bh", output, start_index) start_features = tf.tile(start_features[None], [seq_len, 1, 1]) end_logits = tf.layers.dense( tf.concat([output, start_features], axis=-1), xlnet_config.d_model, kernel_initializer=initializer, activation=tf.tanh, name="dense_0") end_logits = tf.contrib.layers.layer_norm( end_logits, begin_norm_axis=-1) end_logits = tf.layers.dense( end_logits, 1, kernel_initializer=initializer, name="dense_1") end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0]) end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask end_log_probs = tf.nn.log_softmax(end_logits_masked, -1) else: # during inference, compute the end logits based on beam search
tensorflow.contrib.layers.layer_norm
3,552
from tensorflow.python.framework import ops false_positives_compute_op]): update_op = compute_precision('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, precision) if updates_collections: ops.add_to_collections(updates_collections, update_op) return precision, update_op def streaming_recall_at_thresholds(predictions, labels, thresholds, weights=None, metrics_collections=None,
tensorflow.python.framework.ops.add_to_collections
3,553
import tensorflow as tf input_=res, filter_size=filter_sizes[-1], dim_in=dims_out[-1], dim_out=dim_out, name="out", stddev=1e-2, nonlinearity=None) return res # distributions # log-likelihood estimation def standard_normal_ll(input_): """Log-likelihood of standard Gaussian distribution.""" res = -.5 * (tf.square(input_) + numpy.log(2. * numpy.pi)) return res def standard_normal_sample(shape): """Samples from standard Gaussian distribution.""" return tf.random_normal(shape) SQUEEZE_MATRIX = numpy.array([[[[1., 0., 0., 0.]], [[0., 0., 1., 0.]]], [[[0., 0., 0., 1.]], [[0., 1., 0., 0.]]]]) def squeeze_2x2_ordered(input_, reverse=False):
tensorflow.square
3,554
import tensorflow as tf # Also, we can limit the size of GPU memory used, with the following option config.gpu_options.per_process_gpu_memory_fraction = 0.4 sess_limited = tf.Session(config=config) # How to set placements on multiple devices. # Here, assume we have three devies CPU:0, GPU:0, and GPU:1 if tf.test.is_built_with_cuda(): with tf.device('/cpu:0'): a = tf.constant([1.0, 3.0, 5.0], shape=[1, 3]) b = tf.constant([2.0, 4.0, 6.0], shape=[3, 1]) with tf.device('/gpu:1'): c = tf.matmul(a,b) c = tf.reshape(c, [-1]) with tf.device('/gpu:2'): d = tf.matmul(b,a) flat_d = tf.reshape(d, [-1]) combined = tf.mul(c, flat_d) print(sess.run(combined))
tensorflow.reshape
3,555
import tensorflow as tf chaining_loss_ratio=1.0, chaining_stop_gradient=False, training=True, **kwargs): decoder = decoders[0] targets = targets[0] # single decoder assert len(encoders) == 2 encoder_input_length = [] input_weights = [] for encoder_inputs_ in encoder_inputs: weights = get_weights(encoder_inputs_, utils.EOS_ID, include_first_eos=True) input_weights.append(weights) encoder_input_length.append(tf.to_int32(tf.reduce_sum(weights, axis=1))) target_weights = get_weights(targets[:, 1:], utils.EOS_ID, include_first_eos=True) parameters = dict(encoders=encoders[1:], decoder=encoders[0], training=training) attention_states, encoder_state, encoder_input_length[1:] = multi_encoder( encoder_inputs[1:], encoder_input_length=encoder_input_length[1:], **parameters) decoder_inputs = encoder_inputs[0][:, :-1] batch_size = tf.shape(decoder_inputs)[0]
tensorflow.reduce_sum
3,556
import tensorflow as tf # tft.apply_buckets will annotate the feature in the output schema to # indicate the bucket boundaries that were applied. outputs['Bucketized_foo'] = mappers.apply_buckets(inputs['foo'], boundaries_foo) outputs['Bucketized_bar'] = mappers.apply_buckets(inputs['bar'], boundaries_bar) # Create a session to actually evaluate the annotations and extract the # the output schema with annotations applied. with tf.compat.v1.Session(graph=graph) as session: schema = schema_inference.infer_feature_schema(outputs, graph, session) self.assertLen(schema.feature, 2) for feature in schema.feature: self.assertLen(feature.annotation.extra_metadata, 1) for annotation in feature.annotation.extra_metadata: # Extract the annotated message and validate its contents message = annotations_pb2.BucketBoundaries()
tensorflow.compat.v1.Session
3,557
import tensorflow as tf """Device to use for computation: cpu or gpu""") #tf.flags.DEFINE_string('data_format', 'NCHW', tf.flags.DEFINE_string('data_format', 'NHWC', """Data layout to use: NHWC (TF native) or NCHW (cuDNN native).""") tf.flags.DEFINE_integer('num_intra_threads', 1, """Number of threads to use for intra-op parallelism. If set to 0, the system will pick an appropriate number.""") tf.flags.DEFINE_integer('num_inter_threads', 0, """Number of threads to use for inter-op parallelism. If set to 0, the system will pick an appropriate number.""") tf.flags.DEFINE_string('trace_file', None, """Enable TensorFlow tracing and write trace to this file.""") tf.flags.DEFINE_string('graph_file', None, """Write the model's graph definition to this
tensorflow.flags.DEFINE_integer
3,558
import tensorflow as tf self._obs = tf.expand_dims(self._obs, -1) # ! conv1 = tf.layers.conv2d(inputs=self._obs, filters=16, kernel_size=[2, 1], # ! kernel_size = [8,8] activation=tf.nn.elu, strides=1) # ! strides = 4 conv2 = tf.layers.conv2d(inputs=conv1, filters=32, kernel_size=[2, 1], # ! kernel_size = [4,4] activation=tf.nn.elu, strides=1) # ! strides = 2 flattened_filters = policy_utils.flatten(conv2) self.z = tf.layers.dense(inputs=flattened_filters, units=256, activation=tf.nn.elu) def build_manager(self): with tf.variable_scope('manager'): # Calculate manager internal state self.s = tf.layers.dense(inputs=self.z, units=self.g_dim, activation=tf.nn.elu) # Calculate manager output g x = tf.expand_dims(self.s, [0])
tensorflow.layers.dense
3,559
import tensorflow as tf pwr = tf.square(inpOp) else: pwr = tf.pow(inpOp, pnorm) subsamp = tf.nn.avg_pool(pwr, ksize=[1, kH, kW, 1], strides=[1, dH, dW, 1], padding=padding) subsamp_sum = tf.multiply(subsamp, kH*kW) if pnorm == 2: out = tf.sqrt(subsamp_sum) else: out = tf.pow(subsamp_sum, 1/pnorm) return out
tensorflow.multiply
3,560
import tensorflow as tf step_nums = tf.range(0, limit=passage_length) # [passage_length] step_nums = tf.expand_dims(step_nums, axis=0) # shape (1, passage_length) step_nums = tf.tile(step_nums, [batch_size, 1]) # shape (batch_size, passage_length) indices = tf.stack((batch_nums, step_nums, passage_word_idx), axis=2) # shape (batch_size, passage_length, 3) indices = tf.reshape(indices, [-1, 3]) #[batch_size * passage_length, 3] indices = tf.cast(indices, tf.int64) shape = [batch_size, passage_length, extended_vsize] shape = tf.cast(shape, tf.int64) attn_dist = tf.reshape(attn_dist, shape=[-1]) # [batch_size*passage_length] one_hot_spare_rep = tf.SparseTensor(indices=indices, values=attn_dist, dense_shape=shape) # [batch_size, passage_length, extended_vsize] if passage_mask is not None: passage_mask = tf.expand_dims(passage_mask, axis=-1) one_hot_spare_rep = one_hot_spare_rep * passage_mask one_hot_spare_rep = tf.sparse_reduce_sum(one_hot_spare_rep, axis=1) # [batch_size, extended_vsize] vocab_dist = tf.add(vocab_dist, one_hot_spare_rep) if self.options.add_first_word_prob_for_phrase: vocab_dist = tf.nn.softmax(vocab_dist) # normalize return vocab_dist # [batch_size, extended_vsize] def linear(args, output_size, bias=True, bias_start=0.0, scope=None): if args is None or (isinstance(args, (list, tuple)) and not args): raise ValueError("`args` must be specified")
tensorflow.expand_dims
3,561
import tensorflow as tf gamma: The hyperparameter for penalizing the easy labeled samples name: A name for the operation (optional) 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)
tensorflow.convert_to_tensor
3,562
import tensorflow as tf grad = tf.reduce_mean(grad, 0) var = grad_and_vars[0][1] grad_and_var = (grad, var) average_grads.append(grad_and_var) return average_grads def binary_mask(shape, p=0.7): samples = tf.random_uniform(shape, minval=0.0, maxval=1.0) mask = tf.less_equal(samples, p) return tf.cast(mask, tf.float32) def weighted_arithmetic_mean(w, x): numer = tf.reduce_sum(w*x) denom = tf.reduce_sum(w) return tf.div(numer, denom)
tensorflow.div
3,563
import tensorflow as tf # Basic model parameters. tf.app.flags.DEFINE_float('learning_rate', 0.1, 'Initial learning rate.') tf.app.flags.DEFINE_string('pm', '66661', 'pooling scheme across scales. Each number specifies the number of scales remaining at each layer. The first number has to be the same as used in --num_scales.') tf.app.flags.DEFINE_integer('conv_kernel', 5, 'Size of convolutional kernel') tf.app.flags.DEFINE_integer('pool_kernel', 3, 'Size of spatial pooling kernel')
tensorflow.app.flags.DEFINE_string
3,564
import tensorflow as tf # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2])] * 3 with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell, num_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell, num_symbols=5, embedding_size=2, feed_previous=True) res1 = sess.run(d1)
tensorflow.get_variable_scope
3,565
import tensorflow as tf tmp1 = tf.tensordot(facts, w1, axes=1) tmp2 = tf.tensordot(query, w2, axes=1) tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]]) tmp = tf.tanh((tmp1 + tmp2) + b)
tensorflow.shape
3,566
import tensorflow as tf integral. """ def F(m_bound, name=None): with tf.name_scope(name, "argus_integral_phalf_primitive"): a = tf.minimum(m_bound, m0) x = 1 - tf.pow(a / m0, 2) primitive = -0.5 * m0 * m0 * (tf.exp(c * x) * tf.sqrt(x) / c + 0.5 / tf.pow(-c, 1.5) * tf.sqrt(pi) * tf.erf(gradsafe_sqrt(-c * x))) # We have to safeguard the sqrt, because otherwise the analytic # derivative blows up for x = 0 return primitive area = tf.sub(F(m_high, name="F2"), F(m_low, name="F1"), name="argus_integral_phalf")
tensorflow.sqrt
3,567
import tensorflow as tf if (change_dimension): block_conv_input = self.conv_layer(bottom = bottom, kernal_size = 1, in_channels = bottom.get_shape().as_list()[-1], out_channels = channel_list[2], stride = 1, name = name + "_branch1") else: block_conv_input = bottom input_filter = bottom.get_shape().as_list()[-1] block_conv_1 = self.conv_layer(bottom, 1, input_filter, channel_list[0], 1, name + "_branch2a") block_norm_1 = tf.layers.batch_normalization(inputs=block_conv_1, axis = 3, momentum=configs['_BATCH_NORM_DECAY'], epsilon=configs['_BATCH_NORM_EPSILON'], center=True, scale=True, training=self.is_training, fused=True) block_relu_1 = tf.nn.relu(block_norm_1) block_conv_2 = self.conv_layer(block_relu_1, 3, channel_list[0], channel_list[1], 1, name + "_branch2b") block_norm_2 = tf.layers.batch_normalization(inputs=block_conv_2, axis = 3, momentum=configs['_BATCH_NORM_DECAY'], epsilon=configs['_BATCH_NORM_EPSILON'], center=True, scale=True, training=self.is_training, fused=True) block_relu_2 = tf.nn.relu(block_norm_2) block_conv_3 = self.conv_layer(block_relu_2, 1, channel_list[1], channel_list[2], 1, name + "_branch2c") block_res = tf.add(block_conv_input, block_conv_3) relu = tf.nn.relu(block_res) return relu def avg_pool(self, bottom, kernal_size = 2, stride = 2, name = "avg"): return tf.nn.avg_pool(bottom, ksize=[1, kernal_size, kernal_size, 1], strides=[1, stride, stride, 1], padding='VALID', name=name) def max_pool(self, bottom, kernal_size = 2, stride = 2, name = "max"): return tf.nn.max_pool(bottom, ksize=[1, kernal_size, kernal_size, 1], strides=[1, stride, stride, 1], padding='SAME', name=name) def conv_layer(self, bottom, kernal_size, in_channels, out_channels, stride, name): with tf.variable_scope(name): filt, conv_biases = self.get_conv_var(kernal_size, in_channels, out_channels, name)
tensorflow.add
3,568
import tensorflow as tf conv_block = Convolutional_Block(inputs=self.layers[-1], shortcut=shortcut, num_filters=512, is_training=self.is_training, name=str(i+1)) self.layers.append(conv_block) # Extract 8 most features as mentioned in paper self.k_pooled = tf.nn.top_k(tf.transpose(self.layers[-1], [0,2,1]), k=8, name='k_pool', sorted=False)[0] print("8-maxpooling:", self.k_pooled.get_shape()) self.flatten = tf.reshape(self.k_pooled, (-1, 512*8))
tensorflow.transpose
3,569
import tensorflow as tf l[:, :, :, :, 2 * nr_mix:3 * nr_mix]) * sel, 4) # sample from logistic & clip to interval # we don't actually round to the nearest 8bit value when sampling u = tf.random_uniform(tf.shape(means), minval=1e-5, maxval=1. - 1e-5) x = means + tf.exp(log_scales) * (tf.log(u) - tf.log(1. - u)) x0 = tf.minimum(tf.maximum(x[:, :, :, 0], -1.), 1.) x1 = tf.minimum(tf.maximum( x[:, :, :, 1] + coeffs[:, :, :, 0] * x0, -1.), 1.) x2 = tf.minimum(tf.maximum( x[:, :, :, 2] + coeffs[:, :, :, 1] * x0 + coeffs[:, :, :, 2] * x1, -1.), 1.) return tf.concat([tf.reshape(x0, xs[:-1] + [1]), tf.reshape(x1, xs[:-1] + [1]), tf.reshape(x2, xs[:-1] + [1])], 3)
tensorflow.reshape
3,570
import tensorflow as tf input_size = inputs.get_shape()[2].value dtype = inputs.dtype x = inputs x0 = tf.transpose(x, perm=[1, 2,0]) # (num_nodes, total_arg_size, batch_size) x0 = tf.reshape(x0, shape=[self._num_nodes, input_size * batch_size]) x = tf.expand_dims(x0, axis=0) scope = tf.get_variable_scope() with tf.variable_scope(scope): if self._max_diffusion_step == 0: pass else: for support in self._supports: x1 = tf.sparse_tensor_dense_matmul(support, x0) x = self._concat(x, x1) for _ in range(2, self._max_diffusion_step + 1): x2 = 2 * tf.sparse_tensor_dense_matmul(support, x1) - x0 x = self._concat(x, x2) x1, x0 = x2, x1 num_matrices = len(self._supports) * self._max_diffusion_step + 1 # Adds for x itself. x = tf.reshape(x, shape=[num_matrices, self._num_nodes, input_size, batch_size]) x = tf.transpose(x, perm=[3, 1, 2, 0]) # (batch_size, num_nodes, input_size, order) x = tf.reshape(x, shape=[batch_size * self._num_nodes, input_size * num_matrices]) weights = tf.get_variable( 'weights', [input_size * num_matrices, output_size],
tensorflow.sparse_tensor_dense_matmul
3,571
from tensorflow.python.ops import random_ops def validateKolmogorovSmirnov(self, shape, mean, stddev, minval, maxval, seed=1618): try: import scipy.stats # pylint: disable=g-import-not-at-top tf.set_random_seed(seed) with self.test_session(use_gpu=self._use_gpu): samples = random_ops.parameterized_truncated_normal(shape, mean, stddev, minval, maxval).eval() assert (~np.isnan(samples)).all() minval = max(mean - stddev * 10, minval) maxval = min(mean + stddev * 10, maxval) dist = scipy.stats.norm(loc=mean, scale=stddev) cdf_min = dist.cdf(minval) cdf_max = dist.cdf(maxval) def truncated_cdf(x): return np.clip((dist.cdf(x) - cdf_min) / (cdf_max - cdf_min), 0.0, 1.0)
tensorflow.python.ops.random_ops.parameterized_truncated_normal
3,572
from tensorflow.python.ops import variable_scope `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope( name, 'false_positives', [predictions, labels]): predictions.get_shape().assert_is_compatible_with(labels.get_shape())
tensorflow.python.ops.variable_scope.variable_scope
3,573
import tensorflow as tf noise_shape=None): """ Dropout layer. Args: inputs: tensor is_training: boolean tf.Variable scope: string keep_prob: float in [0,1] noise_shape: list of ints Returns: tensor variable """ with tf.variable_scope(scope) as sc: outputs = tf.cond(is_training, lambda: tf.nn.dropout(inputs, keep_prob, noise_shape), lambda: inputs) return outputs
tensorflow.nn.dropout
3,574
import tensorflow as tf not_eos = tf.cond( # We only check for early stoping if there is at least 1 element ( # otherwise not_eos will crash) tf.not_equal(length, 0), fn_not_eos, lambda: True, )
tensorflow.not_equal
3,575
import tensorflow as tf u = (1.0 - att_score) * u new_h = u * state + (1 - u) * c return new_h, new_h def prelu(_x, scope=''): """parametric ReLU activation""" with tf.variable_scope(name_or_scope=scope, default_name="prelu"): _alpha = tf.get_variable("prelu_"+scope, shape=_x.get_shape()[-1], dtype=_x.dtype, initializer=tf.constant_initializer(0.1)) _zero = tf.constant(0,dtype=_x.dtype) # return tf.maximum(0.0, _x) + _alpha * tf.minimum(0.0, _x) return tf.maximum(_zero, _x) + _alpha * tf.minimum(_zero, _x) def calc_auc(raw_arr): """Summary
tensorflow.constant_initializer
3,576
import tensorflow as tf IMAGE_SIZE = 28 def get_conv_dimension(filter_list): with tf.Graph().as_default(): with tf.Session() as sess: """Model function for CNN.""" features = tf.placeholder( tf.float32, shape=[None, IMAGE_SIZE * IMAGE_SIZE], name='features') labels = tf.placeholder(tf.int64, shape=[None], name='labels') input_layer = tf.reshape(features, [-1, IMAGE_SIZE, IMAGE_SIZE, 1]) conv1 = tf.layers.conv2d( inputs=input_layer, filters=filter_list[0], kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) conv2 = tf.layers.conv2d(
tensorflow.reshape
3,577
from tensorflow.python.ops import random_ops # Benchmarking code def parameterized_vs_naive(shape, num_iters, use_gpu=False): np.random.seed(1618) # Make it reproducible. # No CSE/CF. optimizer_options = tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0) config = tf.ConfigProto( graph_options=tf.GraphOptions(optimizer_options=optimizer_options)) with tf.Session(config=config) as sess: with tf.device("/cpu:0" if not use_gpu else None): param_op = tf.group(random_ops.parameterized_truncated_normal(shape)) naive_op = tf.group(random_ops.truncated_normal(shape)) # Burn-in to avoid session setup costs in the timing. sess.run(param_op) sess.run(param_op) param_dt = timeit.timeit(lambda: sess.run(param_op), number=num_iters) sess.run(naive_op) sess.run(naive_op) naive_dt = timeit.timeit(lambda: sess.run(naive_op), number=num_iters) return param_dt, naive_dt class TruncatedNormalBenchmark(tf.test.Benchmark):
tensorflow.python.ops.random_ops.truncated_normal
3,578
import tensorflow as tf use_synthetic_gpu_images = (self.dataset is None) with tf.device(self.global_step_device): global_step = tf.contrib.framework.get_or_create_global_step()
tensorflow.device
3,579
import tensorflow as tf saver = tf.train.import_meta_graph(filename) # Exports the graph as text format. saver.export_meta_graph(filename, as_text=True) with self.test_session(graph=tf.Graph()): # Imports the text format graph. tf.train.import_meta_graph(filename)
tensorflow.Graph
3,580
import tensorflow as tf name='logits_rl_w', initializer=tf.initializers.zeros(),
tensorflow.initializers.zeros
3,581
import tensorflow as tf src_path, dst_path = sess.run(dequeue_op) except tf.errors.OutOfRangeError: coord.request_stop() break process(src_path, dst_path) complete() # init epoch counter for the queue local_init_op = tf.local_variables_initializer() with tf.Session() as sess: sess.run(local_init_op) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(a.workers): t = threading.Thread(target=worker, args=(coord,)) t.start() threads.append(t)
tensorflow.Session
3,582
import tensorflow as tf summary = self.image_summaries['orig'].eval(feed_dict={self.input: blurred_batch}) self.summary_writer.add_summary(summary, global_step=self.get_past_epochs()) self._eval_image_summary('midd', average) # self._eval_image_summary('reco', actual) self._eval_image_summary('pred', expected) self._eval_image_summary('nois', noisy) def _eval_image_summary(self, name, encdoding_batch): summary = self.image_summaries[name].eval(feed_dict={self.encoding: encdoding_batch}) self.summary_writer.add_summary(summary, global_step=self.get_past_epochs()) def _add_decoding_summary(self, name, var, collection='train'): var = var[:FLAGS.visualiza_max] var = tf.concat(tf.unstack(var), axis=0) var = tf.expand_dims(var, dim=0) color_s = tf.summary.image(name, var[..., :3], max_outputs=FLAGS.visualiza_max) var = tf.expand_dims(var[..., 3], dim=3) bw_s = tf.summary.image('depth_' + name, var, max_outputs=FLAGS.visualiza_max) return tf.summary.merge([color_s, bw_s]) # TRAINING PROGRESS EVENTS def _on_training_start(self, sess): # Writers and savers self.summary_writer = tf.summary.FileWriter(FLAGS.logdir, sess.graph) self.saver = tf.train.Saver()
tensorflow.unstack
3,583
import tensorflow as tf candidate_start_sentence_indices = tf.gather(flattened_sentence_indices, candidate_starts) # [num_words, max_span_width] candidate_end_sentence_indices = tf.gather(flattened_sentence_indices, tf.minimum(candidate_ends, num_words - 1)) # [num_words, max_span_width]
tensorflow.minimum
3,584
import tensorflow as tf "input_mask": tf.FixedLenFeature([seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([seq_length], tf.int64), "label_ids": tf.FixedLenFeature([seq_length], tf.int64), } def _decode_record(record, name_to_features): example = tf.parse_single_example(record, name_to_features) for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.to_int32(t) example[name] = t
tensorflow.parse_single_example
3,585
import tensorflow as tf return new_h, new_h def prelu(_x, scope=''): """parametric ReLU activation""" with tf.variable_scope(name_or_scope=scope, default_name="prelu"): _alpha = tf.get_variable("prelu_"+scope, shape=_x.get_shape()[-1], dtype=_x.dtype, initializer=tf.constant_initializer(0.1)) return tf.maximum(0.0, _x) + _alpha * tf.minimum(0.0, _x) def calc_auc(raw_arr): """Summary
tensorflow.constant_initializer
3,586
import tensorflow as tf return list_from_batch[-1], {'targets': list_from_batch[:-1], 'decode_fn': lambda pred : anchor_encoder_decoder.decode_all_anchors([pred])[0], 'num_anchors_list': num_anchors_list} return input_fn def modified_smooth_l1(bbox_pred, bbox_targets, bbox_inside_weights = 1., bbox_outside_weights = 1., sigma = 1.): """ ResultLoss = outside_weights * SmoothL1(inside_weights * (bbox_pred - bbox_targets)) SmoothL1(x) = 0.5 * (sigma * x)^2, if |x| < 1 / sigma^2 |x| - 0.5 / sigma^2, otherwise """ sigma2 = sigma * sigma inside_mul = tf.multiply(bbox_inside_weights, tf.subtract(bbox_pred, bbox_targets)) smooth_l1_sign = tf.cast(tf.less(tf.abs(inside_mul), 1.0 / sigma2), tf.float32) smooth_l1_option1 = tf.multiply(tf.multiply(inside_mul, inside_mul), 0.5 * sigma2) smooth_l1_option2 = tf.subtract(tf.abs(inside_mul), 0.5 / sigma2) smooth_l1_result = tf.add(tf.multiply(smooth_l1_option1, smooth_l1_sign), tf.multiply(smooth_l1_option2, tf.abs(tf.subtract(smooth_l1_sign, 1.0)))) outside_mul = tf.multiply(bbox_outside_weights, smooth_l1_result) return outside_mul def xdet_model_fn(features, labels, mode, params): """Our model_fn for ResNet to be used with our Estimator."""
tensorflow.subtract
3,587
import tensorflow as tf os.makedirs(eval_plot_dir, exist_ok=True) os.makedirs(eval_wav_dir, exist_ok=True) os.makedirs(tensorboard_dir, exist_ok=True) os.makedirs(meta_folder, exist_ok=True) checkpoint_fpath = os.path.join(save_dir, "tacotron_model.ckpt") metadat_fpath = os.path.join(args.synthesizer_root, "train.txt") log("Checkpoint path: {}".format(checkpoint_fpath)) log("Loading training data from: {}".format(metadat_fpath)) log("Using model: Tacotron") log(hparams_debug_string()) # Start by setting a seed for repeatability tf.set_random_seed(hparams.tacotron_random_seed) # Set up data feeder coord = tf.train.Coordinator() with tf.variable_scope("datafeeder") as scope: feeder = Feeder(coord, metadat_fpath, hparams) # Set up model: global_step = tf.Variable(0, name="global_step", trainable=False) model, stats = model_train_mode(args, feeder, hparams, global_step) eval_model = model_test_mode(args, feeder, hparams, global_step) # Embeddings metadata char_embedding_meta = os.path.join(meta_folder, "CharacterEmbeddings.tsv") if not os.path.isfile(char_embedding_meta):
tensorflow.set_random_seed
3,588
import tensorflow as tf tflite_model = converter.convert() with open(f"{target_dir}/tflite_model.tflite", "wb") as f: f.write(tflite_model) def validation(): (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() images = tf.convert_to_tensor(np.expand_dims(x_test/255.0, -1),dtype=tf.float32) # Load the TFLite model in TFLite Interpreter interpreter = tf.lite.Interpreter(f"{target_dir}/tflite_model.tflite") # Model has single input. in_node = interpreter.get_input_details()[0] in_shape = in_node['shape'] # Model has single output. out_node = interpreter.get_output_details()[0] out_shape = out_node['shape'] # Resize Tensor (batch size) interpreter.resize_tensor_input(in_node['index'],[len(images), in_shape[1], in_shape[2], in_shape[3]])
tensorflow.lite.Interpreter
3,589
import tensorflow as tf if tf_output1_dtype == tf.string: cast1 = tf.dtypes.as_string(sub if not swap else add, name="TOSTR1") else: cast1 = tf.cast(sub if not swap else add, tf_output1_dtype, "CAST1") out0 = tf.identity(cast0, "OUTPUT0") out1 = tf.identity(cast1, "OUTPUT1") # Use a different model name for the non-batching variant model_name = tu.get_model_name( "graphdef_nobatch" if max_batch == 0 else "graphdef", input_dtype, output0_dtype, output1_dtype)
tensorflow.identity
3,590
import tensorflow as tf def get_regression_loss( FLAGS, features, is_training): """Loss for downstream regression tasks.""" bsz_per_core = tf.shape(features["input_ids"])[0] inp = tf.transpose(features["input_ids"], [1, 0]) seg_id = tf.transpose(features["segment_ids"], [1, 0]) inp_mask = tf.transpose(features["input_mask"], [1, 0]) label = tf.reshape(features["label_ids"], [bsz_per_core]) xlnet_config = xlnet.XLNetConfig(json_path=FLAGS.model_config_path) run_config = xlnet.create_run_config(is_training, True, FLAGS)
tensorflow.transpose
3,591
import tensorflow as tf scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names:
tensorflow.logging.info
3,592
from tensorflow.contrib.learn.python.learn.graph_actions import train self._check_inputs(features, targets) train_op, loss_op = self._get_train_ops(features, targets) return train( graph=g,
tensorflow.contrib.learn.python.learn.graph_actions.train
3,593
import tensorflow as tf # -1 otherwise. For instance, candidate[3] = id(token[3] + token[4]). # First, split into basic UTF-8 characters (letters). chars = tf.strings.unicode_split(word, 'UTF-8') tokens = self._StringToToken(chars)
tensorflow.strings.unicode_split
3,594
import tensorflow as tf # Note that each grad_and_vars looks like the following: # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] for g, _ in grad_and_vars: # Add 0 dimension to the gradients to represent the tower. expanded_g = tf.expand_dims(g, 0) # Append on a 'tower' dimension which we will average over below. grads.append(expanded_g) # Average over the 'tower' dimension. grad = tf.concat(axis=0, values=grads) grad = tf.reduce_mean(grad, 0) # Keep in mind that the Variables are redundant because they are shared # across towers. So .. we will just return the first tower's pointer to # the Variable. v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads def train():
tensorflow.reduce_mean
3,595
import tensorflow as tf last_c = loop_outputs[-7] last_h = loop_outputs[-6] return arc_seq, entropy, log_prob, last_c, last_h def build_trainer(self, child_model): child_model.build_valid_rl() self.valid_acc = (tf.to_float(child_model.valid_shuffle_acc) / tf.to_float(child_model.batch_size)) self.reward = self.valid_acc if self.entropy_weight is not None: self.reward += self.entropy_weight * self.sample_entropy self.sample_log_prob = tf.reduce_sum(self.sample_log_prob) self.baseline = tf.Variable(0.0, dtype=tf.float32, trainable=False) baseline_update = tf.assign_sub( self.baseline, (1 - self.bl_dec) * (self.baseline - self.reward)) with tf.control_dependencies([baseline_update]): self.reward = tf.identity(self.reward) self.loss = self.sample_log_prob * (self.reward - self.baseline) self.train_step = tf.Variable(0, dtype=tf.int32, trainable=False, name="train_step") tf_variables = [var for var in tf.trainable_variables() if var.name.startswith(self.name)] print("-" * 80) for var in tf_variables: print(var)
tensorflow.Variable
3,596
from tensorflow import keras dataset = dataset.repeat(num_epochs).batch(batch_size) iterator = dataset.make_one_shot_iterator() batch_features, batch_labels = iterator.get_next() return batch_features, batch_labels return _input_fn # Create inference model using Keras # The model here is a dnn regressor def make_keras_estimator(output_dir): from tensorflow import keras model = keras.models.Sequential() model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER)) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(1)) model.compile(loss = 'mean_squared_error', optimizer = 'adam', metrics = ['mae', 'mape']) # mean absolute [percentage] error return keras.estimator.model_to_estimator(model, model_dir=output_dir) # Create the inference model def simple_rnn(features, labels, mode): # 0. Reformat input shape to become a sequence x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1) # 1. Configure the RNN
tensorflow.keras.layers.Activation
3,597
from tensorflow.core.framework import op_def_pb2 as _op_def_pb2 def _InitOpDefLibrary(): op_list = _op_def_pb2.OpList() _text_format.Merge(_InitOpDefLibrary.op_list_ascii, op_list) _op_def_registry.register_op_list(op_list)
tensorflow.core.framework.op_def_pb2.OpList
3,598
from tensorflow.python.framework import ops @ops.RegisterShape("Max") @ops.RegisterShape("Mean")
tensorflow.python.framework.ops.RegisterShape
3,599