seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf result_file = f"results/{args.problem}_test_{time.strftime('%Y%m%d-%H%M%S')}" result_file = result_file + '.csv' os.makedirs('results', exist_ok=True) ### TENSORFLOW SETUP ### if args.gpu == -1: os.environ['CUDA_VISIBLE_DEVICES'] = '' else: os.environ['CUDA_VISIBLE_DEVICES'] = f'{args.gpu}' config = tf.ConfigProto() config.gpu_options.allow_growth = True tf.enable_eager_execution(config) tf.executing_eagerly() test_files = list(pathlib.Path(f"data/samples/{problem_folder}/test").glob('sample_*.pkl')) test_files = [str(x) for x in test_files] print(f"{len(test_files)} test samples") evaluated_policies = [['gcnn', model] for model in gcnn_models] + \ [['ml-competitor', model] for model in other_models] fieldnames = [ 'policy', 'seed', ] + [
tensorflow.executing_eagerly
1,700
import tensorflow as tf This lower bound on the number of true positives given `logits` and `labels` is the same one used in the global objectives loss functions. Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` of shape [batch_size, num_labels] or [batch_size, num_labels, num_anchors]. If the third dimension is present, the lower bound is computed on each slice [:, :, k] independently. weights: Per-example loss coefficients, with shape broadcast-compatible with that of `labels`. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. Returns: A `Tensor` of shape [num_labels] or [num_labels, num_anchors]. """ maybe_log2 = tf.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = tf.cast(maybe_log2, logits.dtype.base_dtype) if logits.get_shape().ndims == 3 and labels.get_shape().ndims < 3: labels = tf.expand_dims(labels, 2) loss_on_positives = losses_utils.weighted_surrogate_loss( labels, logits, surrogate_type, negative_weights=0.0) / maybe_log2 return tf.reduce_sum(weights * (labels - loss_on_positives), 0) def false_positives_upper_bound(labels, logits, weights, surrogate_type): """Calculate an upper bound on the number of false positives. This upper bound on the number of false positives given `logits` and `labels` is the same one used in the global objectives loss functions. Args: labels: A `Tensor` of shape [batch_size, num_labels] logits: A `Tensor` of shape [batch_size, num_labels] or
tensorflow.cast
1,701
import tensorflow as tf return output_spec return model_fn def get_masked_lm_output( bert_config, input_tensor, output_weights, positions, label_ids, label_weights ): """Get loss and log probs for the masked LM.""" input_tensor = gather_indexes(input_tensor, positions) with tf.variable_scope("cls/predictions"): # We apply one more non-linear transformation before the output layer. # This matrix is not used after pre-training. with tf.variable_scope("transform"): input_tensor = tf.layers.dense( input_tensor, units=bert_config.hidden_size, activation=modeling.get_activation(bert_config.hidden_act), kernel_initializer=modeling.create_initializer( bert_config.initializer_range ), )
tensorflow.variable_scope
1,702
import tensorflow as tf output_z_ = lrelu(linear(trans_z, self.gf_dim*8*s_h16*s_w16, 'd_h0_lin')) output_h0 = tf.reshape(output_z_, [-1, s_h16, s_w16, self.gf_dim * 8]) output_h1 = lrelu(deconv2d(tf.concat([output_h0, tgtctx_h3], 3), [self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1')) output_h2 = lrelu(deconv2d(tf.concat([output_h1, tgtctx_h2], 3), [self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2')) output_h3 = lrelu(deconv2d(tf.concat([output_h2, tgtctx_h1], 3), [self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3')) output_h4 = deconv2d(tf.concat([output_h3, tgtctx_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4') scope.reuse_variables()
tensorflow.concat
1,703
from tensorflow.python.training import moving_averages Returns ------- The same Numpy array, cast to its new type. """ return np.asarray(x, dtype=tf.float32) def moving_average_update(variable, value, momentum): try: return moving_averages.assign_moving_average( variable, value, momentum, zero_debias=False) except TypeError: return moving_averages.assign_moving_average(variable, value, momentum) def int_shape(x): """Returns the shape of a Keras tensor or a Keras variable as a tuple of integers or None entries. Arguments --------- x: Tensor or variable. Returns -------
tensorflow.python.training.moving_averages.assign_moving_average
1,704
import tensorflow as tf 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"): ch_emb = tf.reshape(tf.nn.embedding_lookup( self.char_mat, self.ch), [N * PL * self.max_p_num, CL, dc]) qh_emb = tf.reshape(tf.nn.embedding_lookup( self.char_mat, self.qh), [N * QL * self.max_p_num, CL, dc]) ch_emb = tf.nn.dropout(ch_emb, 1.0 - 0.5 * self.dropout) qh_emb = tf.nn.dropout(qh_emb, 1.0 - 0.5 * self.dropout) ch_emb = conv(ch_emb, d, bias=True, activation=tf.nn.relu, kernel_size=5, name="char_conv", reuse=None)
tensorflow.nn.embedding_lookup
1,705
import tensorflow as tf bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) tvars = tf.trainable_variables() initialized_variable_names = {} scaffold_fn = None
tensorflow.trainable_variables
1,706
from tensorflow.python.framework import tensor_util normal = dists.Normal(mu, sigma, validate_args=True) self.assertTrue(tensor_util.constant_value(normal.is_scalar_event)) self.assertTrue(tensor_util.constant_value(normal.is_scalar_batch)) normal = dists.Normal([mu], [sigma],
tensorflow.python.framework.tensor_util.constant_value
1,707
import tensorflow as tf name: A string used as the name for this variable scope. Returns: (tf.Tensor) A single value tensor containing the loss. """ loss = None with tf.name_scope(name, "click_weighted_log_loss",[output]): click_prob = tf.sigmoid(output) loss = tf.losses.log_loss(labels, click_prob, propensity_weights) return loss
tensorflow.sigmoid
1,708
import tensorflow as tf raise ValueError('anchors must be an BoxList') if not isinstance(groundtruth_boxes, box_list.BoxList): raise ValueError('groundtruth_boxes must be an BoxList') if groundtruth_labels is None: groundtruth_labels = tf.ones(tf.expand_dims(groundtruth_boxes.num_boxes(), 0)) groundtruth_labels = tf.expand_dims(groundtruth_labels, -1) shape_assert = tf.assert_equal(tf.shape(groundtruth_labels)[1:], tf.shape(self._unmatched_cls_target)) with tf.control_dependencies([shape_assert]): match_quality_matrix = self._similarity_calc.compare(groundtruth_boxes, anchors) match = self._matcher.match(match_quality_matrix, **params) reg_targets = self._create_regression_targets(anchors, groundtruth_boxes, match)
tensorflow.shape
1,709
import tensorflow as tf epsilon = 1e-5 mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable('scale',[x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02)) offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0)) out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset return out
tensorflow.constant_initializer
1,710
from tensorflow.contrib.boosted_trees.proto import learner_pb2 classifier.evaluate(input_fn=_eval_input_fn, steps=1) classifier.export(self._export_dir_base) def testThatLeafIndexIsInPredictions(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp()
tensorflow.contrib.boosted_trees.proto.learner_pb2.LearnerConfig
1,711
import tensorflow as tf def viz3(name, a, b, c): with tf.name_scope(name): im = tf.concat([a, b, c], axis=3) im = tf.transpose(im, [0, 2, 3, 1]) im = (im + 1.0) * 128 im = tf.clip_by_value(im, 0, 255) im = tf.cast(im, tf.uint8, name='viz')
tensorflow.transpose
1,712
import tensorflow as tf rank_assertions = [] for i in range(len(image_list)): image_rank = tf.rank(image_list[i]) rank_assert = tf.Assert(
tensorflow.rank
1,713
import tensorflow as tf #cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=glabels, logits=cls_pred) # Create a tensor named cross_entropy for logging purposes. tf.identity(cross_entropy, name='cross_entropy_loss') tf.summary.scalar('cross_entropy_loss', cross_entropy) loc_loss = tf.cond(n_positives > 0., lambda: modified_smooth_l1(location_pred, tf.stop_gradient(gtargets), sigma=1.), lambda: tf.zeros_like(location_pred)) #loc_loss = modified_smooth_l1(location_pred, tf.stop_gradient(gtargets)) loc_loss = tf.reduce_mean(tf.reduce_sum(loc_loss, axis=-1)) loc_loss = tf.identity(loc_loss, name='location_loss') tf.summary.scalar('location_loss', loc_loss) tf.losses.add_loss(loc_loss) # Add weight decay to the loss. We exclude the batch norm variables because # doing so leads to a small improvement in accuracy. loss = cross_entropy + loc_loss + params['weight_decay'] * tf.add_n( [tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name]) total_loss = tf.identity(loss, name='total_loss') if mode == tf.estimator.ModeKeys.TRAIN: global_step = tf.train.get_or_create_global_step()
tensorflow.losses.add_loss
1,714
from tensorflow.python.framework import ops # Now, we have the implicit threshold, so compute the sensitivity: return math_ops.div(tp[tf_index], tp[tf_index] + fn[tf_index] + kepsilon, name) sensitivity = compute_sensitivity_at_specificity('value') with ops.control_dependencies( [tp_update_op, fn_update_op, tn_update_op, fp_update_op]): update_op = compute_sensitivity_at_specificity('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, sensitivity)
tensorflow.python.framework.ops.control_dependencies
1,715
import tensorflow as tf # for both the shortcut and non-shortcut paths as part of the first # block's projection. Cf. Appendix of [2]. if self.resnet_version == 1: inputs = batch_norm(inputs, training, self.data_format) inputs = tf.nn.relu(inputs) if self.first_pool_size: inputs = tf.layers.max_pooling2d( inputs=inputs, pool_size=self.first_pool_size, strides=self.first_pool_stride, padding='SAME', data_format=self.data_format) inputs = tf.identity(inputs, 'initial_max_pool') for i, num_blocks in enumerate(self.block_sizes): num_filters = self.num_filters * (2**i) inputs = block_layer( inputs=inputs, filters=num_filters, bottleneck=self.bottleneck, block_fn=self.block_fn, blocks=num_blocks, strides=self.block_strides[i], training=training, name='block_layer{}'.format(i + 1), data_format=self.data_format) # Only apply the BN and ReLU for model that does pre_activation in each
tensorflow.identity
1,716
import tensorflow as tf ) # Before and after flux. before_flux = batch_win_shaped(band_features["before_flux"]) after_flux = batch_win_shaped(band_features["after_flux"]) before_time = batch_win_shaped(band_features["before_time"]) after_time = batch_win_shaped(band_features["after_time"]) self.dtime = batch_2win_shaped( tf.concat([before_time, after_time], axis=1) - tile_to_2win(closest_time), ) self.dflux = batch_2win_shaped( tf.concat([before_flux, after_flux], axis=1) - tile_to_2win(closest_flux), ) # Masking tensor. left_mask = _left_mask( batch_shaped( band_features["before_padding"]), window_size) right_mask = _right_mask( batch_shaped(band_features["after_padding"]), window_size )
tensorflow.concat
1,717
import tensorflow as tf [size_assertion], tf.slice(image, offsets, cropped_shape)) return tf.reshape(image, cropped_shape)
tensorflow.reshape
1,718
import tensorflow as tf _,h,w,c = input_var.shape.as_list() _t = tf.image.resize_nearest_neighbor(input_var, [h*2, w*2]) _t = tf.pad(_t,self.padding, mode='SYMMETRIC') return tf.nn.bias_add(
tensorflow.pad
1,719
import tensorflow as tf data_format_ = 'NHWC' if data_format=='channels_last' else 'NCHW' if data_format_ == 'NHWC': inputs = tf.transpose(inputs, [0, 2, 3, 1]) ksize = int(6 * sigma + 1.) x = tf.expand_dims(tf.range(ksize, delta=1, dtype=tf.float32), axis=1) y = tf.transpose(x, [1, 0]) kernel_matrix = tf.exp(- ((x - ksize/2.) ** 2 + (y - ksize/2.) ** 2) / (2 * sigma ** 2)) #print(kernel_matrix)
tensorflow.range
1,720
import tensorflow as tf anchors_w_1, arc_seq, tf.constant([0.0], dtype=tf.float32, name="entropy"), tf.constant([0.0], dtype=tf.float32, name="log_prob"), ] loop_outputs = tf.while_loop(_condition, _body, loop_vars, parallel_iterations=1) arc_seq = loop_outputs[-3].stack() arc_seq = tf.reshape(arc_seq, [-1]) entropy = tf.reduce_sum(loop_outputs[-2]) log_prob = tf.reduce_sum(loop_outputs[-1]) 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):
tensorflow.reshape
1,721
import tensorflow as tf truthoutput_h1 = lrelu(deconv2d(tf.concat([truthoutput_h0, tgtctx_h3], 3), [self.batch_size, s_h8, s_w8, self.gf_dim*4], name='d_h1')) truthoutput_h2 = lrelu(deconv2d(tf.concat([truthoutput_h1, tgtctx_h2], 3), [self.batch_size, s_h4, s_w4, self.gf_dim*2], name='d_h2')) truthoutput_h3 = lrelu(deconv2d(tf.concat([truthoutput_h2, tgtctx_h1], 3), [self.batch_size, s_h2, s_w2, self.gf_dim*1], name='d_h3')) truthoutput_h4 = deconv2d(tf.concat([truthoutput_h3, tgtctx_h0], 3), [self.batch_size, s_h, s_w, self.c_dim], name='d_h4') self.simloss = tf.reduce_mean((trans_z - tgtimg_z) ** 2) * 1e3 mean, var = tf.nn.moments(tgtimg_z, axes=[0]) print(var.get_shape()) # self.simloss /= tf.reduce_mean(var) print(tgtimg_z.get_shape()) self.out = output_h4# + contextimg#tf.nn.tanh(h4) self.out2 = truthoutput_h4 self.recon1 = tf.nn.l2_loss(tgtimg - self.out) self.recon2 = tf.nn.l2_loss(tgtimg - self.out2)
tensorflow.reduce_mean
1,722
import tensorflow as tf logits = tf.reduce_mean(logits, axis=1) if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze')
tensorflow.squeeze
1,723
import tensorflow as tf values = [] bleu = 100 * bleu_hook.bleu_wrapper( decode_hparams.decode_reference, decode_hparams.decode_to_file) values.append(tf.Summary.Value(tag="BLEU", simple_value=bleu)) tf.logging.info("%s: BLEU = %6.2f" % (decode_hparams.decode_to_file, bleu)) if hook_args.hparams.mlperf_mode: current_step = decode_hparams.mlperf_decode_step mlperf_log.transformer_print(
tensorflow.logging.info
1,724
import tensorflow as tf loss = loss_pg + loss_vf + loss_entropy opt = tf.train.AdamOptimizer(self.LR) self.train_op = opt.minimize(loss, global_step=self.global_step, var_list=pi_params + vf_params) self.pi_new_params = [oldp.assign(p) for p, oldp in zip(pi_params, pi_old_params)] self.vf_new_params = [oldp.assign(p) for p, oldp in zip(vf_params, vf_old_params)] self.sess.run(tf.global_variables_initializer()) # Tensorboard if summary_dir is not None: self.writer = tf.summary.FileWriter(summary_dir) tf.summary.scalar('Loss/Policy', loss_pg) tf.summary.scalar('Loss/Value', loss_vf) tf.summary.scalar('Loss/Entropy', loss_entropy) tf.summary.scalar('Loss/Total', loss) tf.summary.scalar('Var/Epsilon', epsilon_decay) tf.summary.scalar('Var/Policy Mode', tf.reduce_mean(pi.mode())) tf.summary.scalar('Var/Policy Sigma', tf.reduce_mean(pi.stddev())) tf.summary.scalar('Var/Value', tf.reduce_mean(self.vf)) self.summarise = tf.summary.merge(tf.get_collection(tf.GraphKeys.SUMMARIES)) # AC net def build_anet(self, state_in, name, reuse=False, batch_size=64): reg = None with tf.variable_scope(name, reuse=reuse): layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg)
tensorflow.summary.scalar
1,725
import tensorflow as tf "char_mat", initializer=tf.constant(char_mat, dtype=tf.float32)) self.c_mask = tf.cast(self.c, tf.bool) self.q_mask = tf.cast(self.q, tf.bool) self.c_len = tf.reduce_sum(tf.cast(self.c_mask, tf.int32), axis=1) self.q_len = tf.reduce_sum(tf.cast(self.q_mask, tf.int32), axis=1) if opt: # we have to hardcode the max batch size here! use the batch size from the generator as this will be used for PG N, CL = config.batch_size if not self.demo else config.batch_size, config.char_limit self.c_maxlen = tf.reduce_max(self.c_len) self.q_maxlen = tf.reduce_max(self.q_len) self.c = tf.slice(self.c, [0, 0], [N, self.c_maxlen]) self.q = tf.slice(self.q, [0, 0], [N, self.q_maxlen]) self.c_mask = tf.slice(self.c_mask, [0, 0], [N, self.c_maxlen]) self.q_mask = tf.slice(self.q_mask, [0, 0], [N, self.q_maxlen]) self.ch = tf.slice(self.ch, [0, 0, 0], [N, self.c_maxlen, CL]) self.qh = tf.slice(self.qh, [0, 0, 0], [N, self.q_maxlen, CL]) self.y1 = tf.argmax(tf.slice(self.y1, [0, 0], [N, self.c_maxlen]),axis=-1) self.y2 = tf.argmax(tf.slice(self.y2, [0, 0], [N, self.c_maxlen]),axis=-1) else: self.c_maxlen, self.q_maxlen = config.para_limit, config.ques_limit 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])
tensorflow.slice
1,726
import tensorflow as tf if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = tf.concat(facts, 2) print ("querry_size mismatch") query = tf.concat(values = [ query, query, ], axis=1)
tensorflow.concat
1,727
import tensorflow as tf 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()
tensorflow.train.start_queue_runners
1,728
import tensorflow as tf pi_eval, _ = self.build_anet(self.state, 'pi', reuse=True) vf_old, vf_old_params = self.build_cnet(batch['state'], 'oldvf') self.vf, vf_params = self.build_cnet(batch['state'], 'vf') self.vf_eval, _ = self.build_cnet(self.state, 'vf', reuse=True) self.sample_action = tf.squeeze(pi_eval.sample(1), axis=0) self.eval_action = pi_eval.mode() self.global_step = tf.train.get_or_create_global_step() self.saver = tf.train.Saver() # Loss functions and training epsilon_decay = tf.train.polynomial_decay(self.EPSILON, self.global_step, self.EPS_LEN, 0.1, power=0) ratio = tf.maximum(pi.prob(batch['actions']), 1e-6) / tf.maximum(pi_old.prob(batch['actions']), 1e-6) ratio = tf.clip_by_value(ratio, 0, 10) surr1 = batch['advantage'] * ratio surr2 = batch['advantage'] * tf.clip_by_value(ratio, 1 - epsilon_decay, 1 + epsilon_decay) loss_pg = - 2.0 * tf.reduce_mean(tf.minimum(surr1, surr2)) loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf))
tensorflow.train.Saver
1,729
import tensorflow as tf else: self.embedding_W = tf.Variable(tf.random_uniform([num_quantized_chars, embedding_size], -1.0, 1.0),name="embedding_W") self.embedded_characters = tf.nn.embedding_lookup(self.embedding_W, self.input_x) embedded_text_expand = tf.expand_dims(self.embedded_characters, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_tags"): W_tags = tf.get_variable("embed_W_tags", [tags_vocab_size, embedding_size], initializer=initializer) embedded_tags = tf.nn.embedding_lookup(W_tags, self.input_tags) embedded_tags_expanded = tf.expand_dims(embedded_tags, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_deps"): W_deps = tf.get_variable("embed_W_deps", [deps_vocab_size, embedding_size], initializer=initializer) embedded_deps = tf.nn.embedding_lookup(W_deps, self.input_deps) embedded_deps_expanded = tf.expand_dims(embedded_deps, -1) with tf.device('/cpu:0'), tf.name_scope("embedding_head"):
tensorflow.expand_dims
1,730
from tensorflow.python.platform import tf_logging as logging self._save(step, session) if self._save_secs is not None: if time.time() >= self._last_saved_time + self._save_secs: self._save(step, session) def end(self, session=None): super(CheckpointSaver, self).end(session) self._save(self._last_begin_step, session) def _save(self, step, session): """Saves the latest checkpoint.""" if step == self._last_saved_step: return logging.info("Saving checkpoints for %d into %s.", step, self._save_path) self._last_saved_time = time.time() self._last_saved_step = step if self._saver is None: self._scaffold.saver.save(session, self._save_path, global_step=step) else: self._saver.save(session, self._save_path, global_step=step) self._summary_writer.add_session_log( SessionLog( status=SessionLog.CHECKPOINT, checkpoint_path=self._save_path), step) class StepCounter(EveryN):
tensorflow.python.platform.tf_logging.info
1,731
import tensorflow as tf # The two terms 'term1' and 'term2' which come from normalizers of the # 1. Original policy distribution # 2. The distribution after completing the square sigma = tf.matrix_inverse(prec) term1 = -0.5 * param_eta * tf.log(tf.matrix_determinant(2 * np.pi * sigma)) if self.beta == 0: term2 = 0.5 * param_eta * tf.log(tf.matrix_determinant(2 * np.pi * param_eta * HaaInv))
tensorflow.matrix_inverse
1,732
from tensorflow.python.framework import ops ops.RegisterShape("Neg")(common_shapes.unchanged_shape) ops.RegisterShape("Real")(common_shapes.unchanged_shape) ops.RegisterShape("Rsqrt")(common_shapes.unchanged_shape) ops.RegisterShape("Sign")(common_shapes.unchanged_shape)
tensorflow.python.framework.ops.RegisterShape
1,733
import tensorflow as tf Returns: a `float` decov loss """ with tf.name_scope(name): x = tf.reshape(xs, [int(xs.get_shape()[0]), -1]) m = tf.reduce_mean(x, 0, True) z = tf.expand_dims(x - m, 2) corr = tf.reduce_mean(tf.matmul(z, tf.transpose(z, perm=[0, 2, 1])), 0) corr_frob_sqr = tf.reduce_sum(tf.square(corr)) corr_diag_sqr = tf.reduce_sum(tf.square(tf.diag_part(corr))) loss = 0.5 * (corr_frob_sqr - corr_diag_sqr) return loss def center_loss(features, label, alpha, num_classes, name='center_loss'): """Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf)
tensorflow.diag_part
1,734
import tensorflow as tf 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), tf.expand_dims(candidate_ends, 0), tf.expand_dims(k, 0), util.shape(context_outputs, 0), True) # [1, k] top_span_indices.set_shape([1, None]) top_span_indices = tf.squeeze(top_span_indices, 0) # [k] top_span_starts = tf.gather(candidate_starts, top_span_indices) # [k] top_span_ends = tf.gather(candidate_ends, top_span_indices) # [k] top_span_emb = tf.gather(candidate_span_emb, top_span_indices) # [k, emb] top_span_cluster_ids = tf.gather(candidate_cluster_ids, top_span_indices) # [k] top_span_mention_scores = tf.gather(candidate_mention_scores, top_span_indices) # [k] top_span_sentence_indices = tf.gather(candidate_sentence_indices, top_span_indices) # [k] top_span_speaker_ids = tf.gather(speaker_ids, top_span_starts) # [k]
tensorflow.squeeze
1,735
import tensorflow as tf self._label_file = label_file self._num_classes = num_classes self._score_threshold = score_threshold self._image_sz = image_sz[0:2] self._config = ConfigProto() self._config.gpu_options.allow_growth = True self._graph = tf.Graph() with self._graph.as_default(): self._sess = tf.Session(config=self._config) tf.saved_model.load( self._sess, [tag_constants.SERVING], self._model_path) self._image_tensor = self._sess.graph.get_tensor_by_name( 'serving_default_input_1:0') self._output_tensor = self._sess.graph.get_tensor_by_name( 'StatefulPartitionedCall:0') self._boxes = tf.placeholder(
tensorflow.Session
1,736
import tensorflow as tf 'foo': tf.convert_to_tensor([0, 1, 2, 3], dtype=tf.int64), 'bar': tf.convert_to_tensor([0, 2, 0, 2], dtype=tf.int64), } # Annotate an arbitrary proto at the schema level (not sure what global # schema boundaries would mean, but hey I'm just a test). boundaries = tf.constant([[1.0]]) message_type = annotations_pb2.BucketBoundaries.DESCRIPTOR.full_name sizes = tf.expand_dims([tf.size(boundaries)], axis=0) message_proto = tf.raw_ops.EncodeProto( sizes=sizes, values=[tf.cast(boundaries, tf.float32)], field_names=['boundaries'], message_type=message_type)[0] type_url = os.path.join('type.googleapis.com', message_type) schema_inference.annotate(type_url, message_proto) with tf.compat.v1.Session(graph=graph) as session: schema = schema_inference.infer_feature_schema(outputs, graph, session) self.assertLen(schema.annotation.extra_metadata, 1) for annotation in schema.annotation.extra_metadata: # Extract the annotated message and validate its contents message = annotations_pb2.BucketBoundaries() annotation.Unpack(message) self.assertAllClose(list(message.boundaries), [1]) def test_infer_feature_schema_with_ragged_tensor(self): with tf.compat.v1.Graph().as_default() as graph: outputs = { 'foo': tf.RaggedTensor.from_row_splits( values=tf.constant([3, 1, 4, 1, 5, 9, 2, 6], tf.int64), row_splits=[0, 4, 4, 7, 8, 8]),
tensorflow.compat.v1.Session
1,737
import tensorflow as tf def _proposal_layer(self, rpn_cls_prob, rpn_bbox_pred, name): with tf.variable_scope(name):
tensorflow.variable_scope
1,738
import tensorflow as tf moving_averages.assign_moving_average( self.ema_means, dw, self.hparams.decay, zero_debias=False) n = tf.reduce_sum(updated_ema_count, axis=-1, keep_dims=True) updated_ema_count = ((updated_ema_count + self.hparams.epsilon) / ( n + 2**self.hparams.z_size * self.hparams.epsilon) * n) updated_ema_means = updated_ema_means / tf.expand_dims( updated_ema_count, axis=-1) with tf.control_dependencies([e_loss]): update_means = tf.assign(self.means, updated_ema_means) with tf.control_dependencies([update_means]): loss += self.hparams.beta * e_loss else: # Use a gradient based loss for learning the cluster centers loss += q_loss + self.hparams.beta * e_loss # Get the discrete latent representation
tensorflow.control_dependencies
1,739
import tensorflow as tf ## End new version if self._normalize_cols: logits_vec = logits_vec - tf.math.reduce_logsumexp( logits_vec, axis=0)[None] relabel_indices = tf.random.categorical(logits=logits_vec, num_samples=1) ### Metrics global_step = tf.compat.v1.train.get_or_create_global_step()
tensorflow.random.categorical
1,740
import tensorflow as tf class CommonImageAttentionTest(parameterized.TestCase, tf.test.TestCase): @parameterized.parameters( (common_image_attention.DistributionType.DMOL, 5, 50), (common_image_attention.DistributionType.CAT, None, 256), ) def testPostProcessImageTrainMode(self, likelihood, num_mixtures, depth): batch = 1 rows = 8 cols = 24 hparams = tf.contrib.training.HParams( hidden_size=2, likelihood=likelihood, mode=tf.estimator.ModeKeys.TRAIN, num_mixtures=num_mixtures, ) inputs = tf.random_uniform([batch, rows, cols, hparams.hidden_size], minval=-1., maxval=1.) outputs = common_image_attention.postprocess_image( inputs, rows, cols, hparams)
tensorflow.contrib.training.HParams
1,741
import tensorflow as tf (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids, num_labels, use_one_hot_embeddings) 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(): 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,
tensorflow.train.init_from_checkpoint
1,742
from tensorflow.python.framework import random_seed 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, loss_op=loss_op,
tensorflow.python.framework.random_seed.set_random_seed
1,743
import tensorflow as tf stddev=0.02, data_format='NCHW',padding='SAME') : with tf.variable_scope(name) : assert(data_format == 'NCHW' or data_format == 'NHWC') self.w = tf.get_variable('w', [k_h, k_w, input_dim, output_dim], initializer=tf.truncated_normal_initializer(stddev=stddev)) self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(0.0)) if( data_format == 'NCHW' ) : self.strides = [1, 1, d_h, d_w]
tensorflow.truncated_normal_initializer
1,744
import tensorflow as tf save.restore(sess, save_path) # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0.eval()) self.assertEqual(20.0, v1.eval()) # Build another graph with 2 nodes, initialized # differently, and a Restore node for them. with self.test_session(graph=tf.Graph()) as sess: v0_2 = tf.Variable(1000.0, name="v0") v1_2 = tf.Variable(2000.0, name="v1") save2 = tf.train.Saver([v0_2, v1_2]) tf.initialize_all_variables().run() # Check that the parameter nodes have been initialized.
tensorflow.Graph
1,745
from tensorflow.python.framework import ops pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = layers.fully_connected(data, 1)
tensorflow.python.framework.ops.device
1,746
import tensorflow as tf normalizer_fn=None, data_format='NDHWC', scope='Conv2d_0c_1x1') # Temporal average pooling. logits = tf.reduce_mean(logits, axis=1) if spatial_squeeze: logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze')
tensorflow.reduce_mean
1,747
import tensorflow as tf sdf = sdf * -1.0 # inside positive, outside zero samples_object = centernet_utils.transform_pointcloud( tf.reshape(samples_world, [1, 1, -1, 3]), tf.reshape(poses[2][i], [1, 1, 3]), tf.reshape(poses[0][i], [1, 1, 3, 3]), tf.reshape(poses[1][i], [1, 1, 3]), inverse=True) * 2.0 samples_object = (samples_object * (29.0/32.0) / 2.0 + 0.5) * 32.0 - 0.5 samples = tf.squeeze(samples_object) interpolated = trilinear.interpolate(sdf, samples) occupancy_value = tf.math.sign(tf.nn.relu(interpolated + self.tol))
tensorflow.reshape
1,748
import tensorflow as tf def dense_maxnorm(var_matrix, maxnorm=1.0): '''Similar to dense_maxnorm_update(), except this returns a new Tensor instead of an operation that modifies var_matrix. Args: var_matrix: 2D tensor (Variable) maxnorm: the maximum Euclidean norm Returns: A new tensor where all rows have been scaled as necessary ''' axis_norms = tf.sqrt(tf.reduce_sum(tf.square(var_matrix), 1)) scaling = maxnorm / tf.maximum(axis_norms, maxnorm) return var_matrix * tf.expand_dims(scaling, 1) class BaseModel(object): ''' Base class for embedding-based relational learning models that use maxnorm regularization. Subclasses must implement _create_model() and populate self.train_step, and can optionally populate self.post_step for post-processing. Note: When model_type is 'ranking_margin', the mini-batch provider returned by _create_batch_provider() must provide instances in alternating pos/neg pairs: [pos, neg, pos, neg, ...]. This is satisfied when using ContrastiveTrainingProvider; be careful if you use a different one. Args:
tensorflow.expand_dims
1,749
import tensorflow as tf return output else: activation = non_linear_fn(output) return activation def batch_norm(x, b_train, scope, reuse=False): with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): n_out = x.get_shape().as_list()[-1] beta = tf.get_variable('beta', initializer=tf.constant(0.0, shape=[n_out])) gamma = tf.get_variable('gamma', initializer=tf.constant(1.0, shape=[n_out])) batch_mean, batch_var = tf.nn.moments(x, [0], name='moments') ema = tf.train.ExponentialMovingAverage(decay=0.9) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(b_train, mean_var_with_update, lambda: (ema.average(batch_mean), ema.average(batch_var))) normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3) return normed
tensorflow.nn.moments
1,750
import tensorflow as tf # hardware related configuration tf.app.flags.DEFINE_integer( 'num_readers', 16,#16 'The number of parallel readers that read data from the dataset.') tf.app.flags.DEFINE_integer( 'num_preprocessing_threads', 48,#48 'The number of threads used to create the batches.') tf.app.flags.DEFINE_integer( 'num_cpu_threads', 0, 'The number of cpu cores used to train.') tf.app.flags.DEFINE_float( 'gpu_memory_fraction', 1., 'GPU memory fraction to use.') # scaffold related configuration tf.app.flags.DEFINE_string( 'data_dir', '../Datasets/tfrecords',#'/media/rs/0E06CD1706CD0127/Kapok/Chi/Datasets/tfrecords', 'The directory where the dataset input data is stored.') tf.app.flags.DEFINE_string( 'dataset_name', '{}_????', 'The pattern of the dataset name to load.') tf.app.flags.DEFINE_string( 'model_dir', './logs_sext_cpn/', 'The parent directory where the model will be stored.') tf.app.flags.DEFINE_integer( 'log_every_n_steps', 10, 'The frequency with which logs are print.') tf.app.flags.DEFINE_integer( 'save_summary_steps', 100,
tensorflow.app.flags.DEFINE_string
1,751
import tensorflow as tf #Construct graph images, labels = input_name.build_input( FLAGS.dataset, FLAGS.eval_data_path, hps.batch_size, FLAGS.mode)#FLAGS.mode='attack', batch_size=200 Res = model_name.ResNet(hps, images, FLAGS.mode, Reuse=False) Res.build_graph() saver = tf.train.Saver() #Open session and restore checkpoint sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) tf.train.start_queue_runners(sess) ckpt_state = tf.train.get_checkpoint_state(FLAGS.log_root) # Choose dir according to rt tf.logging.info('Loading checkpoint %s', ckpt_state.model_checkpoint_path) num_sample = hps.batch_size*FLAGS.eval_batch_count # Initialize results to save entropy_test_adv_all = np.array([]) confidence_test_adv_all = np.array([]) entropy_test_nor_all = np.array([]) confidence_test_nor_all = np.array([]) logits_adv_all = np.reshape(np.array([]), (0, 64))
tensorflow.train.get_checkpoint_state
1,752
import tensorflow as tf target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_q_func') # construct optimization op (with gradient clipping) self.learning_rate = tf.placeholder(tf.float32, (), name="learning_rate") optimizer = self.optimizer_spec.constructor(learning_rate=self.learning_rate, **self.optimizer_spec.kwargs) self.train_fn = minimize_and_clip(optimizer, self.total_error, var_list=q_func_vars, clip_val=grad_norm_clipping) # update_target_fn will be called periodically to copy Q network to target Q network update_target_fn = [] for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name), sorted(target_q_func_vars, key=lambda v: v.name)): update_target_fn.append(var_target.assign(var)) self.update_target_fn = tf.group(*update_target_fn) # construct the replay buffer self.replay_buffer = ReplayBuffer(replay_buffer_size, frame_history_len, lander=lander) self.replay_buffer_idx = None ############### # RUN ENV # ############### self.model_initialized = False self.num_param_updates = 0 self.mean_episode_reward = -float('nan') self.best_mean_episode_reward = -float('inf') self.last_obs = self.env.reset()
tensorflow.group
1,753
import tensorflow as tf self.ch = tf.placeholder(tf.int32, [None, config.test_para_limit, config.char_limit],"context_char") self.qh = tf.placeholder(tf.int32, [None, config.test_ques_limit, config.char_limit],"question_char") self.y1 = tf.placeholder(tf.int32, [None, config.test_para_limit],"answer_index1") self.y2 = tf.placeholder(tf.int32, [None, config.test_para_limit],"answer_index2")
tensorflow.placeholder
1,754
import tensorflow as tf def inference(self, forward_only=None): embed_inputs = tf.nn.embedding_lookup(self.embedding_init, self.x) ## (batch_size, seq_len, 100) with tf.variable_scope('hidden', reuse=forward_only): with tf.variable_scope('lstm_cell'): lstm_cell = tf.nn.rnn_cell.LSTMCell(num_units=self.num_hidden, use_peepholes=False, # forget_bias=0.0, activation=tf.nn.relu, # initializer=tf.truncated_normal_initializer(stddev=0.1), # initializer=tf.random_uniform_initializer(-0.003, 0.003), initializer=tf.contrib.layers.xavier_initializer(), state_is_tuple=True) if not forward_only: lstm_cell = tf.nn.rnn_cell.DropoutWrapper(cell=lstm_cell, output_keep_prob=self.dropout_output) # lstm_cell = tf.nn.rnn_cell.MultiRNNCell(cells=[lstm_cell] * 4, state_is_tuple=True) if not forward_only: embed_inputs = tf.nn.dropout(embed_inputs, keep_prob=self.dropout_input) rnn_outputs, output_states = tf.nn.dynamic_rnn( cell=lstm_cell,
tensorflow.contrib.layers.xavier_initializer
1,755
import tensorflow as tf annotation = tf.placeholder(tf.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="annotation") z = tf.placeholder(tf.float32, shape=[None, 4, 4, 128], name="z") # pred_annotation, logits = inference(image, keep_probability,z) # tf.summary.image("input_image", image, max_outputs=2) # tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2) # tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2) # loss = tf.reduce_mean((tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, # labels=tf.squeeze(annotation, squeeze_dims=[3]), # name="entropy"))) mask_ = tf.ones([FLAGS.batch_size,64,64,3]) mask = tf.pad(mask_, [[0,0],[32,32],[32,32],[0,0]]) mask2__ = tf.ones([FLAGS.batch_size,78,78,3]) mask2_ = tf.pad(mask2__, [[0,0],[25,25],[25,25],[0,0]]) mask2 = mask2_ - mask pred_annotation, logits = inference((1-mask)*image + mask*255, keep_probability,z) tf.summary.image("input_image", image, max_outputs=2) tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2) tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2) # loss0 = tf.reduce_mean(tf.abs(z)) loss = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square((image - logits)),[1,2,3]))) # loss2 = tf.reduce_mean(tf.square((image - logits)*mask2)) # loss = loss1 + loss2 + loss0 # loss = tf.reduce_mean(tf.squared_difference(logits ,annotation ))
tensorflow.ones
1,756
from tensorflow.python.framework import ops # models/layers made in tf.compat.v1.Graph.as_default() with models/layers # created outside of it. Converting a model to an estimator (via # model_to_estimator) invalidates all models/layers made before the # conversion (even if they were not the model converted to an estimator). # Similarly, making a layer or a model inside a a tf.compat.v1.Graph # invalidates all layers/models you previously made outside of the graph. self._originally_built_as_v1 = True @property def _saved_model_loader(self) -> saved_transform_io_v2.SavedModelLoader: """A `saved_transform_io_v2.SavedModelLoader`.""" if self._saved_model_loader_value is None: self._saved_model_loader_value = saved_transform_io_v2.SavedModelLoader( self._tft_output.transform_savedmodel_dir) self._loaded_saved_model_graph = ops.get_default_graph() # TODO(b/160294509): Use tf.compat.v1 when we stop supporting TF 1.15. if ops.executing_eagerly_outside_functions(): return self._saved_model_loader_value else: assert not self._exported_as_v1 # TODO(b/149997088): Raise an exception once we no longer support using # the Keras layer with estimator based Trainer. tf.compat.v1.logging.warning('Loading a TF2 SavedModel but eager mode ' 'seems disabled.') # If exported as TF2 SavedModel but not invoked in eager mode, # re-initialize the saved_model_loader_value as __init__ could have been # called in a different graph context.
tensorflow.python.framework.ops.get_default_graph
1,757
import tensorflow as tf if res_increase == 1: # already in the target shape return input_tensor # resize y-z squeeze_b_x = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx') resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align) resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx') # Reorient
tensorflow.reshape
1,758
import tensorflow as tf else: ones_like_x = tf.ones_like(x, dtype=tf.int64)
tensorflow.ones_like
1,759
import tensorflow as tf """ box1 = box1.numpy() if isinstance(box1, tf.Tensor) else box1 box2 = box2.numpy() if isinstance(box2, tf.Tensor) else box2 box1 = box1.astype(np.float32) box2 = box2.astype(np.float32) # rotates around z, while we rotate around y so need to swap center_1 = tf.reshape(box1[0:3][[0, 2, 1]], [1, 3]) center_2 = tf.reshape(box2[0:3][[0, 2, 1]], [1, 3]) rotation_z_1 = tf.reshape(box1[-1], [1]) rotation_z_2 = tf.reshape(box2[-1], [1]) length_1 = tf.reshape(box1[3 + 0], [1]) height_1 = tf.reshape(box1[3 + 2], [1]) width_1 = tf.reshape(box1[3 + 1], [1]) length_2 = tf.reshape(box2[3 + 0], [1]) height_2 = tf.reshape(box2[3 + 2], [1]) width_2 = tf.reshape(box2[3 + 1], [1]) iou = np.squeeze(np_box_ops.iou3d_7dof_box( length_1, height_1, width_1, center_1, rotation_z_1,
tensorflow.reshape
1,760
import tensorflow as tf log_cdf_plus = plus_in - tf.nn.softplus(plus_in) log_one_minus_cdf_min = -tf.nn.softplus(min_in) cdf_delta = cdf_plus - cdf_min mid_in = inv_stdv * centered_inputs log_pdf_mid = mid_in - log_scales - 2. * tf.nn.softplus(mid_in) log_probs = tf.select( inputs < -0.999, log_cdf_plus, tf.select(
tensorflow.nn.softplus
1,761
import tensorflow as tf rnorm_var = tf.random_normal([row_dim, col_dim], mean=0.0, stddev=1.0) runif_var = tf.random_uniform([row_dim, col_dim], minval=0, maxval=4) print(sess.run(rnorm_var))
tensorflow.random_uniform
1,762
import tensorflow as tf return tf.squeeze(z,axis=0) zs = tf.map_fn(loop_hyper_encoder, ys, dtype=tf.float32, parallel_iterations=1, back_prop=False) print("Hyper Encoder") z_hats, _ = entropy_bottleneck(zs, False) print("Quantize hyperprior") def loop_hyper_deocder(z): z = tf.expand_dims(z, 0) loc, scale = hyper_decoder(z) return tf.squeeze(loc, [0]), tf.squeeze(scale, [0]) locs, scales = tf.map_fn(loop_hyper_deocder, z_hats, dtype=(tf.float32, tf.float32), parallel_iterations=1, back_prop=False) lower_bound = 1e-9# TODO scales = tf.maximum(scales, lower_bound) print("Hyper Decoder") z_strings, z_min_v, z_max_v = entropy_bottleneck.compress(zs) z_shape = tf.shape(zs)[:] print("Entropy Encode (Hyper)")
tensorflow.squeeze
1,763
import tensorflow as tf self.assertAllClose( self.evaluate(log_prob), self._scipy_pareto(concentration_v, scale_v).logpdf(x)) pdf = pareto.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose( self.evaluate(pdf), self._scipy_pareto(concentration_v, scale_v).pdf(x)) def testParetoLogPdfValidateArgs(self): batch_size = 3 scale = tf.constant([2., 3., 4.]) concentration = tf.constant([2.] * batch_size) pareto = tfd.Pareto(concentration, scale, validate_args=True) with self.assertRaisesOpError("not in the support"): x = tf.placeholder_with_default(input=[2., 3., 3.], 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=[2., 2., 5.], shape=[3]) log_prob = pareto.log_prob(x) self.evaluate(log_prob)
tensorflow.constant
1,764
import tensorflow as tf layer_last = feats_audio nfilt_last = audio_nchannels for i, ((ntime, nband, nfilt), (ptime, pband)) in enumerate(zip(cnn_filter_shapes, cnn_pool)): layer_name = 'cnn_{}'.format(i) with tf.variable_scope(layer_name): filters = tf.get_variable('filters', [ntime, nband, nfilt_last, nfilt], initializer=cnn_init, dtype=dtype) biases = tf.get_variable('biases', [nfilt], initializer=tf.constant_initializer(0.1), dtype=dtype) if cnn_rnn_zack: padding = 'SAME' else: padding = 'VALID' conv = tf.nn.conv2d(layer_last, filters, [1, 1, 1, 1], padding=padding) biased = tf.nn.bias_add(conv, biases) convolved = tf.nn.relu(biased) pool_shape = [1, ptime, pband, 1] pooled = tf.nn.max_pool(convolved, ksize=pool_shape, strides=pool_shape, padding='SAME') print('{}: {}'.format(layer_name, pooled.get_shape())) export_feat_tensors[layer_name] = pooled # TODO: CNN dropout?
tensorflow.nn.conv2d
1,765
import tensorflow as tf def do_cls(avg_pool, num_classes, name='dense'): """Applies classification.""" with tf.variable_scope('target_CLS', reuse=tf.AUTO_REUSE): logits = tf.layers.dense( inputs=avg_pool,
tensorflow.variable_scope
1,766
from tensorflow.python.ops import state_ops train_ops = self._get_linear_training_ops( linear_grads, linear_vars) + self._get_dnn_training_ops(dnn_grads, dnn_vars) train_step = control_flow_ops.group(*train_ops, name="combined_training_op") with ops.control_dependencies([train_step]): with ops.get_default_graph().colocate_with(global_step): return state_ops.assign_add(global_step, 1).op, loss def _run_metrics(self, predictions, targets, metrics, weights): result = {} targets = math_ops.cast(targets, predictions.dtype) for name, metric in six.iteritems(metrics or {}): if "weights" in inspect.getargspec(metric)[0]:
tensorflow.python.ops.state_ops.assign_add
1,767
import tensorflow as tf sess.run(tf.global_variables_initializer()) print(f'\nl1={sess.run(l1)} l2={sess.run(l2)}') a = np.array([1, 2, 3], dtype=np.float32) tf_v = tf.Variable(5, dtype=tf.float32) sess.run(tf.global_variables_initializer()) print(f'a * tf_v = {sess.run(a * tf_v)}') weights = tf.constant([[1.0, -2], [-3, 4]]); regular_l1 = tf.contrib.layers.l1_regularizer(0.5)(weights) regular_l2 = tf.contrib.layers.l2_regularizer(0.5)(weights) print(f'\nregular_l1={sess.run(regular_l1)} regular_l2={sess.run(regular_l2)}') val_val = sess.run(val) print('\nval=' + str(val_val)) print(f'\nargmax_0={val_val.argmax(0)} argmax_1={val_val.argmax(1)}') print('\ntf.argmax(val, 0)=' + str(sess.run(tf.argmax(val, 0)))) print('tf.argmax(val, 1)=' + str(sess.run(tf.argmax(val, 1))))
tensorflow.constant
1,768
import tensorflow as tf # input shape, so we confuse it about the input shape. initial_output = tf.slice(initial_output, [0, 0, 0, 0], common_layers.shape_list(initial_output)) target_modality = self._problem_hparams.target_modality if target_modality.is_class_modality: decode_length = 1 else: decode_length = common_layers.shape_list( features["inputs"])[1] + decode_length # Initial values of result, logits and loss. result = initial_output # tensor of shape [batch_size, time, 1, 1, vocab_size] logits = tf.zeros((batch_size, 0, 1, 1, target_modality.top_dimensionality)) if not context.in_eager_mode(): logits.set_shape([None, None, None, None, None]) loss = 0.0 def while_exit_cond(result, logits, loss): # pylint: disable=unused-argument """Exit the loop either if reach decode_length or EOS.""" length = common_layers.shape_list(result)[1] not_overflow = length < decode_length if self._problem_hparams.stop_at_eos:
tensorflow.zeros
1,769
from tensorflow.python.platform import tf_logging as logging try: self._last_export_dir = self._estimator.export( self.export_dir, exports_to_keep=self.exports_to_keep, signature_fn=self.signature_fn, input_fn=self._input_fn, default_batch_size=self._default_batch_size, input_feature_key=self._input_feature_key, use_deprecated_input_fn=self._use_deprecated_input_fn) except RuntimeError: logging.info("Skipping exporting for the same step.") class CheckpointSaver(BaseMonitor): """Saves checkpoints every N steps.""" def __init__(self, checkpoint_dir, save_secs=None, save_steps=None,
tensorflow.python.platform.tf_logging.info
1,770
import tensorflow as tf key_vocabulary_filename=key_vocabulary_filename) if key_vocabulary_filename is not None: return numeric_combine_result keys, counts = numeric_combine_result if key_dtype is not tf.string: keys = tf.strings.to_number(keys, key_dtype) return keys, counts @common.log_api_use(common.ANALYZER_COLLECTION) def mean(x: common_types.TensorType,
tensorflow.strings.to_number
1,771
import tensorflow as tf tf.split(1, max_sequence_len, embeddings)] # Need to prepare a mask to zero out the padding symbols. # Make a batch_size x max_sequence_len matrix where each # row contains the length repeated max_sequence_len times. lengths_transposed = tf.expand_dims(tf.to_int32(self.seq_lens), 1) lengths_tiled = tf.tile(lengths_transposed, [1, max_sequence_len]) # Make a matrix where each row contains [0, 1, ..., max_sequence_len] r = tf.range(0, max_sequence_len, 1) range_row = tf.expand_dims(r, 0) range_tiled = tf.tile(range_row, [batch_size, 1]) self.lengths_transposed = lengths_transposed self.lengths_tiled = lengths_tiled self.range_row = range_row self.range_tiled = range_tiled # Use the logical operations to create a mask indicator = tf.less(range_tiled, lengths_tiled+1) #i.e. where seq len is less than index trim = np.ones(indicator.get_shape())
tensorflow.expand_dims
1,772
import tensorflow as tf dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testAttentionDecoder2(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): cell = tf.nn.rnn_cell.GRUCell(2) inp = [tf.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = tf.nn.rnn(cell, inp, dtype=tf.float32) attn_states = tf.concat(1, [tf.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs]) dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 dec, mem = tf.nn.seq2seq.attention_decoder( dec_inp, enc_state, attn_states, cell, output_size=4, num_heads=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape)
tensorflow.nn.rnn_cell.GRUCell
1,773
import tensorflow as tf update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops):
tensorflow.control_dependencies
1,774
import tensorflow.contrib.rnn as rnn # 0. Reformat input shape to become a sequence x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1) # 1. Configure the RNN lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0) outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = tf.float32) # Slice to keep only the last cell of the RNN
tensorflow.contrib.rnn.BasicLSTMCell
1,775
import tensorflow as tf return out_img def build_discriminator(self,image,reuse=False,name='discriminator'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False def lrelu(x, alpha,name='lrelu'): with tf.variable_scope(name): if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False
tensorflow.get_variable_scope
1,776
import tensorflow as tf # check that we have some nodes to checkpoint if not checkpoints: raise Exception('no checkpoints nodes found or given as input! ') # disconnect dependencies between checkpointed tensors checkpoints_disconnected = {} for x in checkpoints: if x.op and x.op.name is not None: grad_node = tf.stop_gradient(x, name=x.op.name+"_sg") else: grad_node = tf.stop_gradient(x) grad_node.op._set_device(x.op.node_def.device) checkpoints_disconnected[x] = grad_node # partial derivatives to the checkpointed tensors and xs ops_to_copy = fast_backward_ops(seed_ops=[y.op for y in ys], stop_at_ts=checkpoints, within_ops=fwd_ops) debug_print("Found %s ops to copy within fwd_ops %s, seed %s, stop_at %s", len(ops_to_copy), fwd_ops, [r.op for r in ys], checkpoints) debug_print("ops_to_copy = %s", ops_to_copy)
tensorflow.stop_gradient
1,777
import tensorflow as tf mask2 = mask2_ - mask pred_annotation, logits = inference((1-mask)*image + mask*255, keep_probability,z) tf.summary.image("input_image", image, max_outputs=2) tf.summary.image("ground_truth", tf.cast(annotation, tf.uint8), max_outputs=2) tf.summary.image("pred_annotation", tf.cast(pred_annotation, tf.uint8), max_outputs=2) # loss0 = tf.reduce_mean(tf.abs(z)) loss = tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square((image - logits)),[1,2,3]))) # loss2 = tf.reduce_mean(tf.square((image - logits)*mask2)) # loss = loss1 + loss2 + loss0 # loss = tf.reduce_mean(tf.squared_difference(logits ,annotation )) loss_summary = tf.summary.scalar("entropy", loss) grads = train_z(loss,z) trainable_var = tf.trainable_variables() if FLAGS.debug: for var in trainable_var: utils.add_to_regularization_and_summary(var) train_op = train(loss, trainable_var) print("Setting up summary op...") summary_op = tf.summary.merge_all()
tensorflow.summary.scalar
1,778
import tensorflow as tf tf.float32) h = tf.zeros([config.num_layers, self.batch_size, config.hidden_size], tf.float32) self._initial_state = (tf.contrib.rnn.LSTMStateTuple(h=h, c=c),) outputs, h, c = self._cell(inputs, h, c, self._rnn_params, is_training) outputs = tf.transpose(outputs, [1, 0, 2]) outputs = tf.reshape(outputs, [-1, config.hidden_size]) return outputs, (tf.contrib.rnn.LSTMStateTuple(h=h, c=c),) def _get_lstm_cell(self, config, is_training):
tensorflow.transpose
1,779
import tensorflow as tf squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz') resize_b_z = tf.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align) resume_b_z = tf.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz')
tensorflow.reshape
1,780
import tensorflow as tf self.weight_initializer = tf.contrib.layers.xavier_initializer()
tensorflow.contrib.layers.xavier_initializer
1,781
import tensorflow as tf )(self.rgb_images_placeholder, is_training) init = tf.global_variables_initializer() config = tf.ConfigProto(log_device_placement=False) if self.on_gpu: config.gpu_options.allow_growth = True
tensorflow.ConfigProto
1,782
import tensorflow as tf Wsa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="Wsa") wa = tf.placeholder(dtype=tf.float32, shape=[None, None], name="wa")
tensorflow.placeholder
1,783
import tensorflow as tf logits = tf.reduce_sum(tf.multiply(output_layer,output_weights),-1)
tensorflow.multiply
1,784
import tensorflow as tf x_discrete = self.bit_to_int( tf.to_int32(x_means_bits), num_bits=self.hparams.z_size, base=2) # Reshape x_discrete shape_x = common_layers.shape_list(x) shape_discrete = shape_x[:-1] x_discrete = tf.reshape(x_discrete, shape_discrete) x_means = tf.reshape(x_means, shape=shape_x) h1 = x + tf.stop_gradient(x_means - x) h2 = tf.layers.dense(tf.nn.relu(h1), self.hparams.filter_size, name="vch2") res = tf.layers.dense( tf.nn.relu(h2), self.hparams.hidden_size, name="vcfin") embed_fn = partial(self.embed) return { "dense": res, "discrete": x_discrete, "loss": loss, "embed": embed_fn }
tensorflow.nn.relu
1,785
import tensorflow as tf logits = tf.layers.dense( x, self.hparams.problem.num_actions, name="dense2" ) logits = clip_logits(logits, self.hparams) logits = tf.expand_dims(logits, axis=1) value = tf.layers.dense(x, self.distributional_value_size) return {"target_policy": logits, "target_value": value}
tensorflow.expand_dims
1,786
import tensorflow as tf dims_in = [dim_in] + dim_hid[:-1] dims_out = dim_hid res = input_ bias = (not use_batch_norm) with tf.variable_scope(name): for layer_idx in xrange(len(dim_hid)): res = conv_layer( input_=res, filter_size=filter_sizes[layer_idx],
tensorflow.variable_scope
1,787
import tensorflow as tf # Input weight matrix: # (uniform initialization as in pycog) self.W_in = \ tf.get_variable('W_in', [N_rec, N_in], initializer=W_in_initializer, trainable=self.W_in_train)
tensorflow.get_variable
1,788
import tensorflow as tf 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()) self.assertGreaterEqual(1.5, duration.total_seconds())
tensorflow.train.start_queue_runners
1,789
import tensorflow as tf ops.reset_default_graph() sess = tf.Session() my_var = tf.Variable(tf.zeros([1,20])) merged = tf.summary.merge_all()
tensorflow.zeros
1,790
import tensorflow as tf import anchors import learning_rates 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( learning_rate, momentum=params['momentum']) elif params['optimizer'] == 'lars': optimizer = tf.contrib.opt.LARSOptimizer( learning_rate, momentum=params['momentum'], weight_decay=params['lars_weight_decay'], skip_list=['batch_normalization', 'bias']) else:
tensorflow.train.AdamOptimizer
1,791
import tensorflow as tf fake_loss = tf.reduce_sum(tf.square(logits)) grad_norms = [ _get_grad_norm( fake_loss, tf.trainable_variables('.*/progressive_gan_block_1/.*')), _get_grad_norm( fake_loss, tf.trainable_variables('.*/progressive_gan_block_2/.*')), _get_grad_norm( fake_loss, tf.trainable_variables('.*/progressive_gan_block_3/.*')) ] grad_norms_output = None with self.test_session(use_gpu=True) as sess: sess.run(tf.global_variables_initializer()) grad_norms_output = np.array([
tensorflow.trainable_variables
1,792
import tensorflow as tf ) ) ''' with tf.train.MonitoredTrainingSession( checkpoint_dir=params.output, hooks=train_hooks, save_checkpoint_secs=None, config=config) as sess: while not sess.should_stop():
tensorflow.train.MonitoredTrainingSession
1,793
import tensorflow as tf vsize = input_shape[1] passage_length = tf.shape(passage_word_idx)[1] with tf.variable_scope('final_distribution'): vocab_dist = p_gen * vocab_dist attn_dist = (1.0-p_gen) * attn_dist # Concatenate some zeros to each vocabulary dist, to hold the probabilities for phrases extended_vsize = vsize if self.max_phrase_size is not None: extended_vsize += self.max_phrase_size extra_zeros = tf.zeros((batch_size, self.max_phrase_size)) vocab_dist = tf.concat(values=[vocab_dist, extra_zeros], axis=1) # [batch_size, extended_vsize] if self.options.add_first_word_prob_for_phrase: # add prob of the first word to each phrase attn_dist = add_first_word_prob_to_atten_dists(self.in_passage_words, self.phrase_starts, vocab_dist, attn_dist) # match attn_dist[batch_size, passage_length] to sparse one-hot representation [batch_size, passage_length, extended_vsize] batch_nums = tf.range(0, limit=batch_size) # shape (batch_size) batch_nums = tf.expand_dims(batch_nums, axis=1) # shape (batch_size, 1) batch_nums = tf.tile(batch_nums, [1, passage_length]) # shape (batch_size, passage_length) 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)
tensorflow.concat
1,794
import tensorflow as tf .AvgPooling('downsample', 2) .Conv2D('conv0', 20, 5, padding='VALID') .MaxPooling('pool0', 2) .Conv2D('conv1', 20, 5, padding='VALID') .FullyConnected('fc1', out_dim=32) .FullyConnected('fct', out_dim=6, nl=tf.identity, W_init=tf.constant_initializer(), b_init=tf.constant_initializer([1, 0, HALF_DIFF, 0, 1, HALF_DIFF]))()) # output 6 parameters for affine transformation stn = tf.reshape(stn, [-1, 2, 3], name='affine') # bx2x3 stn = tf.reshape(tf.transpose(stn, [2, 0, 1]), [3, -1]) # 3 x (bx2) coor = tf.reshape(tf.matmul(xys, stn), [WARP_TARGET_SIZE, WARP_TARGET_SIZE, -1, 2]) coor = tf.transpose(coor, [2, 0, 1, 3], 'sampled_coords') # b h w 2 sampled = ImageSample('warp', [image, coor], borderMode='constant') return sampled with argscope([Conv2D, FullyConnected], nl=tf.nn.relu): with tf.variable_scope('STN1'): sampled1 = get_stn(image)
tensorflow.transpose
1,795
import tensorflow as tf def get_params(self): """See base class.""" return {}, {} def encode(self, x, encode_params): """See base class.""" del encode_params # Unused. signs = tf.sign(x) abs_vals = tf.abs(x) ints = tf.floor(abs_vals) floats = abs_vals - ints return { self.ENCODED_SIGNS_KEY: signs, self.ENCODED_INTS_KEY: ints, self.ENCODED_FLOATS_KEY: floats }
tensorflow.abs
1,796
import tensorflow as tf with tf.variable_scope(name) as scope:
tensorflow.variable_scope
1,797
import tensorflow as tf 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)
tensorflow.reduce_mean
1,798
import tensorflow as tf if self.dale_ratio: reg += self.L1_out * tf.reduce_mean(tf.matmul(tf.abs(self.W_out) * self.output_Connectivity, self.Dale_out)) else: reg += self.L1_out * tf.reduce_mean(tf.abs(self.W_out) * self.output_Connectivity) # L2 weight regularization reg += self.L2_in * tf.reduce_mean(tf.square(tf.abs(self.W_in) * self.input_Connectivity)) reg += self.L2_rec * tf.reduce_mean(tf.square(tf.abs(self.W_rec) * self.rec_Connectivity)) if self.dale_ratio: reg += self.L2_out * tf.reduce_mean(tf.square( tf.matmul(tf.abs(self.W_out) * self.output_Connectivity, self.Dale_out))) else: reg += self.L2_out * tf.reduce_mean(tf.square(tf.abs(self.W_out) * self.output_Connectivity)) # L2 firing rate regularization reg += self.L2_firing_rate * tf.reduce_mean(tf.square(tf.nn.relu(self.states))) # susillo regularization reg += self.sussillo_constant * self.sussillo_reg() return reg # implement one step of the RNN def rnn_step(self, rnn_in, state):
tensorflow.abs
1,799