seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) accuracy = tf.metrics.accuracy(label_ids, predictions) loss = tf.metrics.mean(per_example_loss) return { "eval_accuracy": accuracy, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits]) 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( mode=mode, predictions=probabilities, scaffold_fn=scaffold_fn) return output_spec return model_fn # This function is not used by this file but is still used by the Colab and # people who depend on it. def input_fn_builder(features, seq_length, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" all_input_ids = [] all_input_mask = [] all_segment_ids = []
tensorflow.contrib.tpu.TPUEstimatorSpec
14,500
import tensorflow as tf return_dict = {} # invalid position mask such as query and special symbols (PAD, SEP, CLS) p_mask = features["p_mask"] # logit of the start position with tf.variable_scope("start_logits"): start_logits = tf.layers.dense( output, 1, kernel_initializer=initializer) start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0]) start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask start_log_probs = tf.nn.log_softmax(start_logits_masked, -1) # logit of the end position with tf.variable_scope("end_logits"): 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,
tensorflow.squeeze
14,501
import tensorflow as tf if decoder.context_mapping: with tf.variable_scope(scope_name): activation = tf.nn.tanh if decoder.context_mapping_activation == 'tanh' else None use_bias = not decoder.context_mapping_no_bias context = dense(context, decoder.context_mapping, use_bias=use_bias, activation=activation, name='context_mapping') return context, new_weights[align_encoder_id] def update(state, input_, context=None, symbol=None): if context is not None and decoder.rnn_feed_attn: input_ = tf.concat([input_, context], axis=1) input_size = input_.get_shape()[1].value initializer = CellInitializer(decoder.cell_size) if decoder.orthogonal_init else None with tf.variable_scope(tf.get_variable_scope(), initializer=initializer): try: output, new_state = get_cell(input_size)(input_, state) except ValueError: # auto_reuse doesn't work with LSTM cells output, new_state = get_cell(input_size, reuse=True)(input_, state) if decoder.skip_update and decoder.pred_edits and symbol is not None: is_del = tf.equal(symbol, utils.DEL_ID)
tensorflow.concat
14,502
import tensorflow as tf Returns: float logits Tensor. """ input_shape = get_shape_list(input_tensor) num_attention_heads= input_shape[2] with tf.variable_scope(name): w = tf.get_variable( name="kernel", shape=[num_attention_heads * head_size, hidden_size], initializer=initializer) w = tf.reshape(w, [num_attention_heads, head_size, hidden_size]) b = tf.get_variable( name="bias", shape=[hidden_size], initializer=tf.zeros_initializer) ret = tf.einsum("BFND,NDH->BFH", input_tensor, w) ret += b if activation is not None: return activation(ret) else: return ret def dense_layer_2d(input_tensor, output_size, initializer, activation, num_attention_heads=1, name=None):
tensorflow.einsum
14,503
import tensorflow as tf rel_init = tf.truncated_normal(rel_var_shape, stddev=init_sd) # Ensure maxnorm constraints are initially satisfied entity_init = dense_maxnorm(entity_init, self.maxnorm) self.entity_embedding_vars = tf.Variable(entity_init) self.rel_embedding_vars = tf.Variable(rel_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input) tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input)
tensorflow.Variable
14,504
import tensorflow as tf with tf.variable_scope('wordrnn'): with tf.variable_scope('fw'):
tensorflow.variable_scope
14,505
import tensorflow as tf net : :class:`Layer` Previous layer with output shape of (batch, width, r). """ # with tf.name_scope(name): # self.outputs = self._apply_activation(self._PS(self.inputs, r=scale)) outputs = self.act(self._PS(inputs, r=self.scale)) return outputs @private_method def _PS(self, I, r): X = tf.transpose(I, [2, 1, 0]) # (r, w, b) X = tf.batch_to_space_nd(X, [r], [[0, 0]]) # (1, r*w, b) X = tf.transpose(X, [2, 1, 0]) return X
tensorflow.batch_to_space_nd
14,506
import tensorflow as tf w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1)) b = tf.Variable(tf.random_normal([attention_size], stddev=0.1)) v = tf.Variable(tf.random_normal([attention_size], stddev=0.1))
tensorflow.random_normal
14,507
import tensorflow as tf in_dim = int(tensor.get_shape()[-1]) rank = _rank(tensor) if rank > 2: # -- time distributed dense tensor = tf.reshape(tensor, shape=(-1, in_dim)) name = opts.get("name", "") if weight is None: initializer = tf.contrib.layers.xavier_initializer(uniform=True) weight = tf.get_variable("{}_dense_W".format(name), initializer=initializer(shape=(in_dim, hidden_dims))) if bias is None: bias = tf.get_variable("{}_dense_b".format(name), initializer=tf.zeros(shape=hidden_dims)) out = tf.add(tf.matmul(tensor, weight), bias) if rank > 2: # reshape back to time dimension out = tf.reshape(out, shape=original_tensor_shape) return out @layer def dropout_layer(tensor, keep_prob=1.0, **opts): keep_prob = _global_keep_prob(keep_prob) out = tf.nn.dropout(tensor, keep_prob=keep_prob) return out
tensorflow.matmul
14,508
import tensorflow as tf with tf.name_scope(name): tt_cores = num_dims * [None] for i in range(num_dims): curr_core_shape = (1, shape[i], 1) tt_cores[i] = tf.ones(curr_core_shape, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank)
tensorflow.ones
14,509
import tensorflow as tf """Concatenate all `datasets` and save to `filename`.""" filename = os.path.join(tmp_dir, filename) # lang1_fname = filename + ".lang1" # lang2_fname = filename + ".lang2" lang1_fname = filename + ".source" lang2_fname = filename + ".target" if tf.gfile.Exists(lang1_fname) and tf.gfile.Exists(lang2_fname): tf.logging.info("Skipping compile data, found files:\n%s\n%s", lang1_fname, lang2_fname) return filename with tf.gfile.GFile(lang1_fname, mode="w") as lang1_resfile: with tf.gfile.GFile(lang2_fname, mode="w") as lang2_resfile:
tensorflow.gfile.Exists
14,510
import tensorflow as tf scale=True, is_training=tftrain, scope=self.name) def linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False): shape = input_.get_shape().as_list() with tf.variable_scope(scope or "Linear"): matrix = tf.get_variable("Matrix", [shape[1], output_size], tf.float32, tf.random_normal_initializer(stddev=stddev)) bias = tf.get_variable("bias", [output_size], initializer=tf.constant_initializer(bias_start)) if with_w: return tf.matmul(input_, matrix) + bias, matrix, bias else: return tf.matmul(input_, matrix) + bias
tensorflow.random_normal_initializer
14,511
import tensorflow as tf mask_pos_b = tf.broadcast_to(mask_pos, tf.shape(loc_true)) loss_loc = _smooth_l1_loss(tf.boolean_mask(loc_true, mask_pos_b),
tensorflow.boolean_mask
14,512
import tensorflow as tf return tf_agent, global_step def cleanup_checkpoints(checkpoint_dir): checkpoint_state = tf.train.get_checkpoint_state(checkpoint_dir) if checkpoint_state is None: return for checkpoint_path in checkpoint_state.all_model_checkpoint_paths:
tensorflow.train.get_checkpoint_state
14,513
from tensorflow.contrib import slim init = tf.global_variables_initializer() if FLAGS.pretrained_model_path is not None: variable_restore_op = slim.assign_from_checkpoint_fn(FLAGS.pretrained_model_path, slim.get_trainable_variables(), ignore_missing_vars=True)
tensorflow.contrib.slim.get_trainable_variables
14,514
from tensorflow.python.framework import ops Dimensions typically: batch, out_units. """ with ops.op_scope([x, weights, biases], name, "xw_plus_b_v1") as name: x = ops.convert_to_tensor(x, name="x") weights = ops.convert_to_tensor(weights, name="weights") biases = ops.convert_to_tensor(biases, name="biases")
tensorflow.python.framework.ops.convert_to_tensor
14,515
import tensorflow as tf with tf.variable_scope(tf.get_variable_scope()): encoder_output_label_, _ = encoder(x_input_l, reuse=True, supervised=True) # Generate output images with tf.variable_scope(tf.get_variable_scope()): decoder_image = decoder(manual_decoder_input, reuse=True) # Classification accuracy of encoder
tensorflow.get_variable_scope
14,516
import tensorflow as tf def _serialize_dataset(self, tasks, is_training, split): """Write out the dataset as tfrecords.""" dataset_name = "_".join(sorted([task.name for task in tasks])) dataset_name += "_" + split dataset_prefix = os.path.join(self._config.preprocessed_data_dir, dataset_name) tfrecords_path = dataset_prefix + ".tfrecord" metadata_path = dataset_prefix + ".metadata" batch_size = self._config.train_batch_size if is_training else self._config.eval_batch_size utils.log("Loading dataset", dataset_name) n_examples = None if self._config.use_tfrecords_if_existing and tf.gfile.Exists(metadata_path): n_examples = utils.load_json(metadata_path)["n_examples"] if n_examples is None: utils.log("Existing tfrecords not found so creating") examples = [] for task in tasks: task_examples = task.get_examples(split) examples += task_examples
tensorflow.gfile.Exists
14,517
import tensorflow as tf update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name="update_param_noise_threshold") update_param_noise_scale_ph = tf.placeholder(tf.bool, (), name="update_param_noise_scale") reset_ph = tf.placeholder(tf.bool, (), name="reset") eps = tf.get_variable("eps", (), initializer=tf.constant_initializer(0)) param_noise_scale = tf.get_variable("param_noise_scale", (), initializer=tf.constant_initializer(0.01), trainable=False) param_noise_threshold = tf.get_variable("param_noise_threshold", (), initializer=tf.constant_initializer(0.05), trainable=False)
tensorflow.constant_initializer
14,518
from tensorflow.contrib.learn.python.learn.summary_writer_cache import SummaryWriterCache Raises: ValueError: If both `save_steps` and `save_secs` are not `None`. ValueError: If both `save_steps` and `save_secs` are `None`. """ logging.info("Create CheckpointSaver.") super(CheckpointSaver, self).__init__() self._saver = saver self._summary_writer = SummaryWriterCache.get(checkpoint_dir) self._save_path = os.path.join(checkpoint_dir, checkpoint_basename) self._scaffold = scaffold self._save_secs = save_secs self._save_steps = save_steps self._last_saved_time = None self._last_begin_step = None
tensorflow.contrib.learn.python.learn.summary_writer_cache.SummaryWriterCache.get
14,519
from tensorflow.python.ops import array_ops num_thresholds = len(thresholds) # Reshape predictions and labels. predictions_2d = array_ops.reshape(predictions, [-1, 1]) labels_2d = array_ops.reshape( math_ops.cast(labels, dtype=dtypes.bool), [1, -1]) # Use static shape if known. num_predictions = predictions_2d.get_shape().as_list()[0] # Otherwise use dynamic shape. if num_predictions is None: num_predictions = array_ops.shape(predictions_2d)[0] thresh_tiled = array_ops.tile( array_ops.expand_dims(array_ops.constant(thresholds), [1]), array_ops.pack([1, num_predictions])) # Tile the predictions after thresholding them across different thresholds. pred_is_pos = math_ops.greater( array_ops.tile(array_ops.transpose(predictions_2d), [num_thresholds, 1]), thresh_tiled) pred_is_neg = math_ops.logical_not(pred_is_pos) # Tile labels by number of thresholds
tensorflow.python.ops.array_ops.shape
14,520
import tensorflow as tf [1, stride_h, stride_w, 1], padding=padding) biases = _variable_on_cpu('biases', [num_output_channels], tf.constant_initializer(0.0)) outputs = tf.nn.bias_add(outputs, biases) if bn: outputs = tf.layers.batch_normalization(outputs, momentum=0.99, epsilon=1e-6, training=is_training)
tensorflow.nn.bias_add
14,521
import tensorflow as tf with tf.Session() as sess: """Model function for CNN.""" features = tf.placeholder( tf.float32, shape=[None, IMAGE_SIZE * IMAGE_SIZE], name='features')
tensorflow.placeholder
14,522
import tensorflow as tf conv2 = tf.layers.conv2d(pool1, filters=64*amp_factor, kernel_size=[5, 1], data_format='channels_last', padding= "same", strides=(2, 1), activation=tf.nn.relu) pool2 = conv2 conv3 = tf.layers.conv2d(pool2, filters=128*amp_factor, kernel_size=[5, 1], data_format='channels_last', padding= "same", strides=(2, 1), activation=tf.nn.relu) pool3 = conv3 conv4 = tf.layers.conv2d(pool3, filters=256*amp_factor, kernel_size=[5, 1], data_format='channels_last', padding= "same", strides=(2, 1), activation=tf.nn.relu) pool4 = conv4 conv5 = tf.layers.conv2d(pool4, filters=256*amp_factor, kernel_size=[5, 1], data_format='channels_last', padding= "same", strides=(2, 1), activation=tf.nn.relu) pool5 = conv5 pool5 = tf.transpose(pool5, [0, 3, 1, 2]) size = pool5.shape[-1] * pool5.shape[-2] * pool5.shape[-3]
tensorflow.layers.conv2d
14,523
import tensorflow as tf pi = act_limit * mlp_dropout(x, list(hidden_sizes)+[act_dim], activation, output_activation) with tf.variable_scope('q'): q = tf.squeeze(mlp_dropout(tf.concat([x,a], axis=-1), list(hidden_sizes)+[1], activation, None, dropout_rate), axis=1) with tf.variable_scope('q', reuse=True): q_pi = tf.squeeze(mlp_dropout(tf.concat([x,pi], axis=-1), list(hidden_sizes)+[1], activation, None, dropout_rate), axis=1) elif nn_type == 'mlp_variational': with tf.variable_scope('pi'): pi_in_dim = x.shape.as_list()[1] pi_dropout_mask_generator = DropoutMaskGenerator(pi_in_dim, hidden_sizes, model_prob=1.0 - dropout_rate) pi_dropout_mask_phs = pi_dropout_mask_generator.generate_dropout_mask_placeholders() pi, pi_reg = mlp_variational(x, pi_dropout_mask_phs, list(hidden_sizes) + [act_dim], activation, output_activation, dropout_rate)
tensorflow.variable_scope
14,524
import tensorflow as tf if reuse: tf.get_variable_scope().reuse_variables() else: assert tf.get_variable_scope().reuse is False epsilon = 1e-5
tensorflow.get_variable_scope
14,525
import tensorflow as tf
tensorflow.split
14,526
from tensorflow.contrib.layers.python.layers import feature_column_ops features = self._get_feature_dict(features) logits = self._logits(features) return self._target_column.logits_to_predictions(logits, proba=True) def _get_feature_ops_from_example(self, examples_batch): column_types = layers.create_feature_spec_for_parsing(( self._get_linear_feature_columns() or []) + ( self._get_dnn_feature_columns() or [])) features = parsing_ops.parse_example(examples_batch, column_types) return features def _get_linear_feature_columns(self): if not self._linear_feature_columns: return None feature_column_ops.check_feature_columns(self._linear_feature_columns) return sorted(set(self._linear_feature_columns), key=lambda x: x.key) def _get_dnn_feature_columns(self): if not self._dnn_feature_columns: return None feature_column_ops.check_feature_columns(self._dnn_feature_columns) return sorted(set(self._dnn_feature_columns), key=lambda x: x.key) def _dnn_logits(self, features, is_training): return self._dnn_model.build_model( features, self._dnn_feature_columns, is_training) def _linear_logits(self, features, is_training):
tensorflow.contrib.layers.python.layers.feature_column_ops.check_feature_columns
14,527
from tensorflow.python.framework import ops non_zero_count = math_ops.maximum(count, array_ops.ones_like(count), name=name) return math_ops.truediv(total, non_zero_count, name=name) mean = compute_mean(total, count, 'value') with ops.control_dependencies([total_compute_op, count_compute_op]): update_op = compute_mean(total, count, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, mean) if updates_collections: ops.add_to_collections(updates_collections, update_op) return mean, update_op def streaming_accuracy(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Calculates how often `predictions` matches `labels`. The `streaming_accuracy` function creates two local variables, `total` and `count` that are used to compute the frequency with which `predictions` matches `labels`. This frequency is ultimately returned as `accuracy`: an
tensorflow.python.framework.ops.add_to_collections
14,528
import tensorflow as tf """ raise NotImplementedError def __init__(self, data={}, n_gpus=1, data_shape=None, **config): self.datasets = data self.data_shape = data_shape self.n_gpus = n_gpus self.graph = tf.get_default_graph() self.name = self.__class__.__name__.lower() # get child name # Update config self.config = self._default_config self.config.update(getattr(self, 'default_config', {})) self.config.update(config)
tensorflow.get_default_graph
14,529
from tensorflow.python.ops import state_ops def _prepare(self): self._lr_t = ops.convert_to_tensor(self._lr, name="learning_rate") self._lambda_t = ops.convert_to_tensor(self._lambda, name="lambda") def _apply_dense(self, grad, var): lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) lambda_t = math_ops.cast(self._lambda_t, var.dtype.base_dtype) g_t = grad var_update = state_ops.assign_sub(var, lr_t * (g_t - lambda_t * var) ) return control_flow_ops.group(*[var_update]) def _apply_sparse(self, grad, var): raise NotImplementedError("Sparse gradient updates are not supported.")
tensorflow.python.ops.state_ops.assign_sub
14,530
import tensorflow as tf return { 0: self._add_separable_conv_3x3_op, 1: self._add_separable_conv_5x5_op, 2: self._add_avg_pool_3x3_op, 3: self._add_max_pool_3x3_op, 4: self._add_identity_op, 5: self._add_separable_conv_7x7_op } def _add_avg_pool_3x3_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): filter_size = 3 stride = 2 if is_reduction else 1 with tf.variable_scope('avg_pool_3x3_op'): X = tf.nn.avg_pool(X, ksize=(1, filter_size, filter_size, 1), strides=[1, stride, stride, 1], padding='SAME') X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X def _add_identity_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): stride = 2 if is_reduction else 1 with tf.variable_scope('identity_op'): # If stride > 1, calibrate, else, just return itself if stride > 1: X = self._calibrate(X, w, h, ch, w // stride, h // stride, ch, is_train=is_train) X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X def _add_max_pool_3x3_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): filter_size = 3
tensorflow.reshape
14,531
import tensorflow.contrib.layers as layers with tf.variable_scope("convnet"): # original architecture out = layers.convolution2d(out, num_outputs=32, kernel_size=8, stride=4, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=4, stride=2, activation_fn=tf.nn.relu) out = layers.convolution2d(out, num_outputs=64, kernel_size=3, stride=1, activation_fn=tf.nn.relu) out = layers.flatten(out) with tf.variable_scope("action_value"): out = layers.fully_connected(out, num_outputs=512, activation_fn=tf.nn.relu) out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None) return out def simple_model(img_in, num_actions, scope, reuse=False, num_filters=64): with tf.variable_scope(scope, reuse=reuse): out = img_in
tensorflow.contrib.layers.fully_connected
14,532
import tensorflow as tf with tf.name_scope("Valid"): valid_input = PTBInput(config=config, data=valid_data, name="ValidInput") with tf.variable_scope("Model", reuse=True, initializer=initializer): mvalid = PTBModel(is_training=False, config=config, input_=valid_input) tf.summary.scalar("Validation Loss", mvalid.cost) with tf.name_scope("Test"): test_input = PTBInput( config=eval_config, data=test_data, name="TestInput")
tensorflow.summary.scalar
14,533
import tensorflow as tf def testScaleGradientsInf(self): FLAGS.enable_check_numerics = False p = self.TestParams() p.input = base_input_generator.BaseSequenceInputGenerator.Params() task = p.cls(p) task.CreateVariable( 'a', py_utils.WeightParams(shape=[], init=py_utils.WeightInit.Constant(0))) var_a = task.theta.a # Infinite gradient. var_grads = py_utils.NestedMap(a=(var_a, tf.log(0.))) has_nan_or_inf, grad_scale, final_var_grads = task.ScaleGradients(var_grads) with self.session(): tf.global_variables_initializer().run() self.assertTrue(has_nan_or_inf.eval()) self.assertEqual(0., grad_scale.eval()) # The final gradient must be finite. self.assertFalse(tf.is_nan(final_var_grads.a[1]).eval()) self.assertTrue(tf.is_finite(final_var_grads.a[1]).eval()) def testScaleGradientsNaN(self): FLAGS.enable_check_numerics = False p = self.TestParams() p.input = base_input_generator.BaseSequenceInputGenerator.Params() task = p.cls(p) task.CreateVariable( 'a', py_utils.WeightParams(shape=[], init=py_utils.WeightInit.Constant(0)))
tensorflow.global_variables_initializer
14,534
import tensorflow as tf # update variables if train: with tf.name_scope(name, "AssignMovingAvg", [mean, cur_mean, decay]): with ops.colocate_with(mean): new_mean = tf.assign_sub( mean, tf.check_numerics(decay * (mean - cur_mean), "NaN in moving mean.")) with tf.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]): with ops.colocate_with(var): new_var = tf.assign_sub( var, tf.check_numerics(decay * (var - cur_var), "NaN in moving variance.")) with tf.name_scope(name, "IncrementTime", [step]): with ops.colocate_with(step): new_step = tf.assign_add(step, 1.) res += 0. * new_mean * new_var * new_step return res # batch normalization taking into account the volume transformation def batch_norm_log_diff(input_,
tensorflow.check_numerics
14,535
import tensorflow as tf def setUp(self): super(LinearRegressionTest, self).setUp() self._tmp_logdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self._tmp_logdir) super(LinearRegressionTest, self).tearDown() def testSyntheticDataset(self): true_w = tf.random_uniform([3, 1]) true_b = [1.0] batch_size = 10 num_batches = 2 noise_level = 0. dataset = linear_regression.synthetic_dataset(true_w, true_b, noise_level, batch_size, num_batches) it = tfe.Iterator(dataset)
tensorflow.random_uniform
14,536
import tensorflow as tf tf.flags.DEFINE_float('rmsprop_decay', 0.9, """Decay term for RMSProp.""") tf.flags.DEFINE_float('rmsprop_momentum', 0.9, """Momentum in RMSProp.""") tf.flags.DEFINE_float('rmsprop_epsilon', 1.0, """Epsilon term for RMSProp.""") tf.flags.DEFINE_float('gradient_clip', None, """Gradient clipping magnitude. Disabled by default.""") tf.flags.DEFINE_float('weight_decay', 0.00004, """Weight decay factor for training.""") # Performance tuning flags. tf.flags.DEFINE_boolean('winograd_nonfused', True, """Enable/disable using the Winograd non-fused algorithms.""") tf.flags.DEFINE_boolean('sync_on_finish', False, """Enable/disable whether the devices are synced after each step.""") tf.flags.DEFINE_boolean('staged_vars', False, """whether the variables are staged from the main computation""") tf.flags.DEFINE_boolean('force_gpu_compatible', True, """whether to enable force_gpu_compatible in GPU_Options""") # The method for managing variables: # parameter_server: variables are stored on a parameter server that holds # the master copy of the variable. In local execution, a local device # acts as the parameter server for each variable; in distributed # execution, the parameter servers are separate processes in the cluster. # For each step, each tower gets a copy of the variables from the # parameter server, and sends its gradients to the param server. # replicated: each GPU has its own copy of the variables. To apply gradients, # nccl all-reduce or regular cross-device aggregation is used to replicate
tensorflow.flags.DEFINE_boolean
14,537
import tensorflow as tf if t.dtype == tf.int64: t = tf.to_int32(t)
tensorflow.to_int32
14,538
import tensorflow as tf # state and target self.state = tf.placeholder(tf.float32, [None,num_state], "state") self.target = tf.placeholder(tf.float32, [None,1], name="target")
tensorflow.placeholder
14,539
import tensorflow as tf # Use the logical operations to create a mask indicator = tf.less(range_tiled, lengths_tiled) sz = [batch_size, max_sequence_len]
tensorflow.less
14,540
import tensorflow as tf ip = p.input ip.frame_size = 80 ip.append_eos_frame = True ip.pad_to_max_seq_length = False p.is_eval = True return p with self.session(use_gpu=False, graph=tf.Graph()) as sess: p = _CreateModelParamsForTest() mdl = p.Instantiate() subgraphs = mdl.Inference() self.assertTrue('default' in subgraphs) fetches, feeds = subgraphs['default'] self.assertTrue('wav' in feeds)
tensorflow.Graph
14,541
import tensorflow as tf # Build a graph with 2 parameter nodes on different devices. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(10, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(20, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True) tf.initialize_all_variables().run() val = save.save(sess, save_path) self.assertEqual(save_path + "-?????-of-00002", val) meta_graph_filename = save._MetaGraphFilename(val) self.assertEqual(save_path + ".meta", meta_graph_filename)
tensorflow.Variable
14,542
import tensorflow as tf pi = tf.constant(np.pi, dtype=tf.float64, name="pi") sqrt2pi = tf.constant(np.sqrt(2 * np.pi), dtype=tf.float64, name="sqrt2pi") two = tf.constant(2, dtype=tf.float64, name="two") one = tf.constant(1, dtype=tf.float64, name="one") zero = tf.constant(0, dtype=tf.float64, name="zero") def gradsafe_sqrt(x, clip_low=1e-18, name=None): with tf.name_scope(name, "gradsafe_sqrt"):
tensorflow.constant
14,543
import tensorflow as tf @under_name_scope() def pairwise_intersection(boxlist1, boxlist2): """Compute pairwise intersection areas between boxes. Args: boxlist1: Nx4 floatbox boxlist2: Mx4 Returns: a tensor with shape [N, M] representing pairwise intersections """ x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=1) x_min2, y_min2, x_max2, y_max2 = tf.split(boxlist2, 4, axis=1) all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2)) all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2)) intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin) all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2)) all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2)) intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin) return intersect_heights * intersect_widths @under_name_scope() def pairwise_iou(boxlist1, boxlist2): """Computes pairwise intersection-over-union between box collections. Args: boxlist1: Nx4 floatbox
tensorflow.transpose
14,544
import tensorflow as tf (loss, num_active_triplets, negative_distances, mining_loss, num_active_mining_triplets, negative_mining_distances) = ( compute_hard_negative_triplet_loss( anchor_positive_distances, anchor_match_distance_matrix, anchor_match_negative_indicator_matrix, margin=margin, use_semi_hard=use_semi_hard, anchor_positive_mining_distances=anchor_positive_mining_distances, anchor_match_mining_distance_matrix=( anchor_match_mining_distance_matrix))) negative_distances = tf.boolean_mask( negative_distances, mask=negative_distances < negative_distances.dtype.max) negative_mining_distances = tf.boolean_mask( negative_mining_distances, mask=negative_distances < negative_distances.dtype.max) active_triplet_ratio = ( tf.cast(num_active_triplets, dtype=tf.float32) / num_total_triplets) active_mining_triplet_ratio = ( tf.cast(num_active_mining_triplets, dtype=tf.float32) /
tensorflow.boolean_mask
14,545
import tensorflow as tf def _testParams(self): input_shape = [2, 16, 8, 3] p = model.AsrModel.Params() p.decoder.target_seq_len = 5 p.encoder.input_shape = input_shape p.input = tig.TestInputGenerator.Params() p.input.target_max_length = 5 p.input.source_shape = input_shape p.input.target_shape = [2, 5] p.name = 'test_mdl' return p def testMakeDecoderTheta(self): # Test that decoder theta returns a copy of theta.decoder without changes. with self.session(use_gpu=False, graph=tf.Graph()): tf.set_random_seed(93820985) p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() decoder_theta = mdl._MakeDecoderTheta(theta=mdl.theta, input_batch=None) mdl.BProp() self.assertEqual(decoder_theta, mdl.theta.decoder) def testFProp(self): with self.session(use_gpu=False): tf.set_random_seed(93820985) p = self._testParams() mdl = p.Instantiate()
tensorflow.Graph
14,546
import tensorflow as tf if init_stddev <= 0.0: init = tf.contrib.layers.variance_scaling_initializer(dtype=tf.float32) else: init = tf.truncated_normal_initializer(stddev=init_stddev) return tf.layers.conv2d_transpose(input, channels, kernel_size=size, strides=[stride, stride], padding=padding, kernel_initializer=init, name='tr_conv' + id, use_bias=use_bias)
tensorflow.truncated_normal_initializer
14,547
import tensorflow as tf # ac_validation_regularizers = tf.get_collection(get_ac_collection_name("validation")) # ac_test_regularizers = tf.get_collection(get_ac_collection_name("test")) # self.regularizer["train"] = tf.add_n(wb_regularizers + ac_train_regularizers, name="regularization_train") # self.regularizer["validation"] = tf.add_n(wb_regularizers + ac_validation_regularizers, name="regularization_validation") # self.regularizer["test"] = tf.add_n(wb_regularizers + ac_test_regularizers, name="regularization_test") def create_global_steps(self, n_points_train_set): self.n_batches_per_epoch = np.ceil(n_points_train_set/self.batch_size["train"]) self.global_step = tf.train.get_or_create_global_step() self.global_epoch = tf.cast(tf.floor(tf.cast(self.global_step, tf.float32) / self.n_batches_per_epoch), tf.int64, "global_epoch") tf.add_to_collection("global_epoch", self.global_epoch) # this creates an operation to add to all trainable variables a white noise of param # std = tf.sqrt(variance)/10 def create_random_update_op(self):
tensorflow.train.get_or_create_global_step
14,548
import tensorflow as tf # horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon) pred_flat1, pred_flat2 = tf.reshape(horizon_pred, [-1, 1]), tf.reshape(horizon_pred, [1, -1]) tgt_flat1, tgt_flat2 = tf.reshape(horizon_tgt, [-1, 1]), tf.reshape(horizon_tgt, [1, -1]) tgt_dif = tgt_flat1 - tgt_flat2 pred_dif = pred_flat1 - pred_flat2 geq = tf.cast(tgt_dif > 0, tf.bool) tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif) pred_posi_dif = tf.where(geq, pred_dif, -pred_dif) loss = tf.maximum(0., tgt_posi_dif - pred_posi_dif) cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32) final_loss = tf.reduce_mean(loss) return final_loss, cstr_pct def contra_traj_lossV7(pred, tgt, horizon=12, temp=100): horizon_pred, horizon_tgt = horizon_sumV1(pred, horizon), horizon_sumV1(tgt, horizon) # horizon_pred, horizon_tgt = horizon_sumV2(pred, tgt, horizon)
tensorflow.maximum
14,549
import tensorflow as tf def squared_loss(y_pred,labels): return tf.reduce_mean((y_pred - labels)**2)
tensorflow.reduce_mean
14,550
import tensorflow as tf W1 = self.xavier_init(size=[layers[l], layers[l+1]]) W2 = self.xavier_init(size=[layers[l], layers[l+1]]) b = tf.Variable(tf.zeros([1,layers[l+1]], dtype=tf.float32), dtype=tf.float32) weights.append((W1, W2)) biases.append(b) return weights, biases def xavier_init(self, size): in_dim = size[0] out_dim = size[1] xavier_stddev = np.sqrt(2/(in_dim + out_dim)) return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32) def neural_net(self, X, weights, biases): num_layers = len(weights) + 1 H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0 for l in range(0,num_layers-2): W1, W2 = weights[l] b = biases[l] H1 = tf.add(tf.matmul(H, W1), b) H2 = tf.matmul(H, W2)
tensorflow.truncated_normal
14,551
import tensorflow as tf def conv3d(layer_name, x, out_channels, kernel_size=[1,3,3], strides=[1,1,1,1,1], data_format='NDHWC', is_pretrain=True): ''' Convolution 3D op wrapper, use RELU activation after convolution ''' in_channels = x.get_shape()[-1].value with tf.variable_scope(layer_name): w = tf.get_variable(name='weight', trainable=is_pretrain, shape=[kernel_size[0],kernel_size[1],kernel_size[2],in_channels,out_channels], initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable(name='bias', trainable=is_pretrain, shape=[out_channels], initializer=tf.contrib.layers.xavier_initializer()) x = tf.nn.conv3d(x, w, strides=strides, padding='SAME', data_format=data_format, name='conv3d') x = tf.nn.bias_add(x, b, name='bias_add') x = tf.nn.relu(x, name='relu') return x def conv(layer_name, x, out_channels, kernel_size=[3,3], strides=[1,1,1,1], is_pretrain=True): ''' Convolution op wrapper, use RELU activation after convolution Args: layer_name: x: input tensor Returns: 4D tensor '''
tensorflow.nn.conv3d
14,552
import tensorflow as tf scope='initial_state_layer_norm') else: initial_state = dense(initial_state, cell_state_size, use_bias=True, name='initial_state_projection', activation=activation_fn) if decoder.cell_type.lower() == 'lstm' and decoder.use_lstm_full_state: initial_output = initial_state else: # Last layer's state is the right-most part. Output is the left-most part of an LSTM's state. initial_output = initial_state[:, -cell_output_size:] time = tf.constant(0, dtype=tf.int32, name='time') outputs = tf.TensorArray(dtype=tf.float32, size=time_steps) samples = tf.TensorArray(dtype=tf.int64, size=time_steps) inputs = tf.TensorArray(dtype=tf.int64, size=time_steps).unstack(tf.to_int64(tf.transpose(decoder_inputs))) states = tf.TensorArray(dtype=tf.float32, size=time_steps) weights = tf.TensorArray(dtype=tf.float32, size=time_steps) attns = tf.TensorArray(dtype=tf.float32, size=time_steps) initial_symbol = inputs.read(0) # first symbol is BOS initial_input = embed(initial_symbol) initial_pos = tf.zeros([batch_size], tf.float32) initial_weights = tf.zeros(tf.shape(attention_states[align_encoder_id])[:2]) zero_context = tf.zeros(shape=tf.shape(attention_states[align_encoder_id][:,0])) # FIXME with tf.variable_scope('decoder_{}'.format(decoder.name)): initial_context, _ = look(0, initial_output, initial_input, pos=initial_pos, prev_weights=initial_weights,
tensorflow.TensorArray
14,553
import tensorflow as tf def euclidean_loss_layer(a, b, multiplier=100.0, use_l1=False, eps=0.01): """ Math: out = (action - mlp_out)'*precision*(action-mlp_out) = (u-uhat)'*A*(u-uhat)""" multiplier = tf.constant(multiplier, dtype='float') #for bc #10000 uP =a*multiplier-b*multiplier if use_l1: return tf.reduce_mean(eps*tf.square(uP) + tf.abs(uP)) return tf.reduce_mean(tf.square(uP)) def conv2d(img, w, b, strides=[1, 1, 1, 1], is_dilated=False): if is_dilated: layer = tf.nn.atrous_conv2d(img, w, rate=2, padding='SAME') + b else: layer = tf.nn.conv2d(img, w, strides=strides, padding='SAME') + b return layer def dropout(layer, keep_prob=0.9, is_training=True, name=None, selu=False): if selu: return dropout_selu(layer, 1.0 - keep_prob, name=name, training=is_training) if is_training: return tf.nn.dropout(layer, keep_prob=keep_prob, name=name) else:
tensorflow.nn.atrous_conv2d
14,554
import tensorflow as tf nbatch, nin = [v.value for v in xs[0].get_shape()] with tf.variable_scope(scope): wx = tf.get_variable("wx", [nin, nh*4], initializer=ortho_init(init_scale)) gx = tf.get_variable("gx", [nh*4], initializer=tf.constant_initializer(1.0)) bx = tf.get_variable("bx", [nh*4], initializer=tf.constant_initializer(0.0)) wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale)) gh = tf.get_variable("gh", [nh*4], initializer=tf.constant_initializer(1.0)) bh = tf.get_variable("bh", [nh*4], initializer=tf.constant_initializer(0.0)) b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0)) gc = tf.get_variable("gc", [nh], initializer=tf.constant_initializer(1.0)) bc = tf.get_variable("bc", [nh], initializer=tf.constant_initializer(0.0)) c, h = tf.split(axis=1, num_or_size_splits=2, value=s)
tensorflow.constant_initializer
14,555
import tensorflow as tf os.path.join(path, 'lib', 'hdrnet_ops.so')) _hdrnet = tf.load_op_library(path)
tensorflow.load_op_library
14,556
import tensorflow as tf m2 = tf.reshape(means[:, :, :, 1, :] + coeffs[:, :, :, 0, :] * inputs[:, :, :, 0, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]) m3 = tf.reshape( means[:, :, :, 2, :] + coeffs[:, :, :, 1, :] * inputs[:, :, :, 0, :] + coeffs[:, :, :, 2, :] * inputs[:, :, :, 1, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]) means = tf.concat([ tf.reshape(means[:, :, :, 0, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]), m2, m3 ], axis=3) centered_inputs = inputs - means inv_stdv = tf.exp(-log_scales) plus_in = inv_stdv * (centered_inputs + 1. / 255.) cdf_plus = tf.nn.sigmoid(plus_in) min_in = inv_stdv * (centered_inputs - 1. / 255.) cdf_min = tf.nn.sigmoid(min_in) 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( inputs > 0.999, log_one_minus_cdf_min, tf.select(cdf_delta > 1e-5, tf.log(tf.maximum(cdf_delta, 1e-12)), log_pdf_mid - np.log(127.5))))
tensorflow.nn.sigmoid
14,557
import tensorflow as tf embeddings=model.embeddings, latent_inters=model.latent_inters, latent_varies=model.latent_varies, degrees=degrees, edge_types=edge_types, edge_type2dim=edge_type2dim, placeholders=placeholders, batch_size=FLAGS.batch_size, margin=FLAGS.max_margin ) print("Initialize session") sess = tf.Session() sess.run(tf.global_variables_initializer()) feed_dict = {} ########################################################### # # Train model # ########################################################### print("Train model") for epoch in range(FLAGS.epochs):
tensorflow.Session
14,558
import tensorflow as tf with tf.variable_scope(tf.get_variable_scope()): decoder_image = decoder(manual_decoder_input, reuse=True) # Classification accuracy of encoder correct_pred = tf.equal(tf.argmax(encoder_output_label_, 1), tf.argmax(y_input, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # Autoencoder loss autoencoder_loss = tf.reduce_mean(tf.square(x_target - decoder_output))
tensorflow.cast
14,559
import tensorflow as tf batch_iter_idx = 1 n_iters_per_epoch = len(dataset.training_X) // self.training_iterator.batch_size self.lr_policy.n_iters_per_epoch = n_iters_per_epoch for epoch in range(start_epoch, self.cnf.get('mum_epochs', 550) + 1): np.random.seed(epoch + seed_delta) tf.set_random_seed(epoch + seed_delta) tic = time.time() d_train_losses = [] g_train_losses = [] batch_train_sizes = []
tensorflow.set_random_seed
14,560
import tensorflow as tf pred_indices_ = tf.squeeze(pred_indices) image_ = tf.squeeze(image) * 255. pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32)
tensorflow.one_hot
14,561
import tensorflow as tf q_loss = tf.reduce_mean( tf.squared_difference(tf.stop_gradient(x), x_means))
tensorflow.stop_gradient
14,562
import tensorflow as tf with self.test_session() as sess: zeros_t = tf.fill([1024, 1024], 0.0) ones_t = tf.fill([1024, 1024], 1.0) p = tf.Variable(zeros_t)
tensorflow.fill
14,563
import tensorflow as tf Variable tensor Note: conv2d(conv2d_transpose(a, num_out, ksize, stride), a.shape[-1], ksize, stride) == a """ with tf.variable_scope(scope) as sc: kernel_h, kernel_w = kernel_size num_in_channels = inputs.get_shape()[-1].value kernel_shape = [kernel_h, kernel_w,
tensorflow.variable_scope
14,564
import tensorflow as tf targets_encoded = base.encode_all(targets, self.data_encoder) self.targets_encoded_ta = base.ta_for_tensor(targets_encoded, clear_after_read=False) if self.rev_rnn_cell: reverse_targets_encoded = tf.reverse_sequence( targets_encoded, seq_lengths, seq_axis=0, batch_axis=1) # Compute the reverse rnn over the targets. reverse_rnn_out, _ = tf.nn.dynamic_rnn(self.rev_rnn_cell,
tensorflow.reverse_sequence
14,565
from tensorflow.python.ops import variable_scope if options.use_coverage: with variable_scope.variable_scope("coverage"): w_c = variable_scope.get_variable("w_c", [options.attention_vec_size]) w_c = tf.expand_dims(tf.expand_dims(w_c, axis=0), axis=0) # For each step, dec_input => lstm_output => vocab_score wordidx_t = decoder_inputs[0] # [batch_size] int32 for i in range(options.max_answer_len): if mode_gen in ('ce_train', 'loss',): wordidx_t = decoder_inputs[i] # the wordidx_t must from decoder_inputs for phrase model word_t = self.embedding_lookup(wordidx_t) if i > 0: variable_scope.get_variable_scope().reuse_variables() (state_t, context_t, coverage_t, attn_dist_t, p_gen_t, output_t) = self.one_step_decoder( state_t_1, context_t_1, coverage_t_1, word_t, encoder_states, self.encoder_features, passage_word_idx, passage_mask, v, w_c, vocab) coverages.append(coverage_t) attn_dists.append(attn_dist_t) p_gens.append(p_gen_t) vocab_scores.append(output_t) # The vocabulary distributions. state_t_1 = state_t
tensorflow.python.ops.variable_scope.get_variable_scope
14,566
import tensorflow as tf def _DoPredictions(self, in_size, mats, class_weights=None): """Takes in an array of states and calculates predictions. Get the cross-entropy for each example in the vector self._xent. Args: in_size: size of the hidden state vectors mats: list of hidden state vectors """ pred_mat = tf.get_variable('pred_mat', [in_size, self._out_vocab_size]) pred_bias = tf.get_variable('pred_bias', [self._out_vocab_size]) # Make a prediction on every word. def GetWordPred(o_): logits = tf.nn.xw_plus_b(o_, pred_mat, pred_bias) return tf.nn.softmax(logits) #self.preds_by_word1 = tf.pack([GetWordPred(o_) for o_ in mats])
tensorflow.get_variable
14,567
import tensorflow as tf
tensorflow.variable_scope
14,568
import tensorflow as tf conv = tf.nn.leaky_relu(conv, alpha=relu_factor) if activation_function == "elu": conv = tf.nn.elu(conv, name = 'elu') return conv def general_deconv2d(self, input_data, filters = 64, kernel_size = 7, stride = 1, stddev = 0.02, activation_function = "relu", padding = "VALID", do_norm = True, relu_factor = 0, name="deconv2d"): with tf.variable_scope(name): deconv = tf.layers.conv2d_transpose(input_data, filters, kernel_size, (stride, stride), padding, activation = None) if do_norm: deconv = tf.layers.batch_normalization(deconv, momentum = 0.9) if activation_function == "relu": deconv = tf.nn.relu(deconv, name = 'relu') if activation_function == "leakyrelu": deconv = tf.nn.leaky_relu(deconv, alpha=relu_factor) if activation_function == "elu": deconv = tf.nn.elu(deconv, name = 'elu') return deconv
tensorflow.layers.batch_normalization
14,569
import tensorflow as tf weights_list += [weights] weights_tensors = tf.stack([tf.convert_to_tensor(weights, dtype=tf.float32) for weights in weights_list]) rand_horizon = tf.random_uniform((), 0, horizon, dtype=tf.int32) new_w = epi_len - rand_horizon cur_weights = tf.slice(weights_tensors[tf.cast(rand_horizon, tf.int32)], [0, 0], [epi_len, new_w]) # cur_weights = tf.slice(weights_tensors, [tf.cast(rand_horizon, tf.int32), 0, 0], [1, epi_len, new_w]) horizon_pred = tf.matmul(pred, cur_weights) horizon_tgt = tf.matmul(tgt, cur_weights) return horizon_pred, horizon_tgt def contra_traj_lossV2(pred, tgt, horizon=9): # Step-wise contrastive loss
tensorflow.matmul
14,570
import tensorflow as tf save._add_collection_def(meta_graph_def, "int_collection") self.assertEqual(len(meta_graph_def.collection_def), 0) def _testMultiSaverCollectionSave(self): test_dir = self._TestDir("saver_collection") filename = os.path.join(test_dir, "metafile") saver0_ckpt = os.path.join(test_dir, "saver0.ckpt") saver1_ckpt = os.path.join(test_dir, "saver1.ckpt") with self.test_session(graph=tf.Graph()) as sess: # Creates a graph. v0 = tf.Variable(10.0, name="v0") v1 = tf.Variable(11.0, name="v1") # Creates 2 savers. saver0 = tf.train.Saver({"v0": v0}, name="saver0") saver1 = tf.train.Saver({"v1": v1}, name="saver1") tf.add_to_collection("savers", saver0) tf.add_to_collection("savers", saver1) tf.initialize_all_variables().run() # Saves to different checkpoints. saver0.save(sess, saver0_ckpt) saver1.save(sess, saver1_ckpt) # Generates MetaGraphDef. meta_graph_def = tf.train.export_meta_graph(filename) meta_graph_def0 = saver0.export_meta_graph() meta_graph_def1 = saver1.export_meta_graph()
tensorflow.train.Saver
14,571
import tensorflow as tf num = (1 - self.alpha) * dxt + tf.tensordot(self.alpha * dxt , tf.transpose( tf.matmul(tf.abs(self.W_rec) * self.rec_Connectivity,self.Dale_rec)), axes=1) * \ tf.where(tf.greater(xt, 0), tf.ones_like(xt), tf.zeros_like(xt)) denom = dxt # sum over hidden units num = tf.reduce_sum(tf.square(num), axis=2) denom = tf.reduce_sum(tf.square(denom), axis=2) bounded = tf.where(tf.greater(denom, 1e-20), tf.div(num, 1.0 * denom), tf.ones_like(num)) nelems = tf.reduce_mean(tf.where(tf.greater(denom, 1e-20), 1.0 * tf.ones_like(num), 1.0 * tf.zeros_like(num)), axis=1) # sum mean over each batch by time steps Omega = tf.square(bounded - 1.0) Omega = tf.reduce_sum(tf.reduce_mean(Omega, axis=1)) / (1.0 * tf.reduce_sum(nelems)) out = tf.gradients(Omega, self.W_rec) out[0] = tf.Print(out[0], [out[0], self.W_rec, Omega], "omega grads") out[0] = tf.verify_tensor_all_finite(out[0], "dead omega grad") return out, test def sussillo_reg(self): states = self.states reg = 0
tensorflow.square
14,572
import tensorflow as tf if FLAGS.do_train: train_file = os.path.join(FLAGS.output_dir, "train.tf_record") file_based_convert_examples_to_features( train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file) tf.logging.info("***** Running training *****") tf.logging.info(" Num examples = %d", len(train_examples)) tf.logging.info(" Batch size = %d", FLAGS.train_batch_size) tf.logging.info(" Num steps = %d", num_train_steps) train_input_fn = file_based_input_fn_builder( input_file=train_file, seq_length=FLAGS.max_seq_length, is_training=True,
tensorflow.logging.info
14,573
import tensorflow as tf vocab_size: a `int`, vocabular size of the problem num_power_iteration: a `int`, the number of power iteration small_constant_for_finite_diff: a `float`, Small constant for finite difference method perturb_norm_length: a `float`, Norm length of adversarial perturbation to be optimized with validatio Returns: a `float` `scalar`, KL divergence. """ logits = tf.stop_gradient(logits) weights = _end_of_seq_mask(labels, vocab_size) perturbs = [_mask_by_length(tf.random_normal(shape=tf.shape(emb)), length) for emb in embedded] for _ in range(num_power_iteration): perturbs = [_scale_l2(d, small_constant_for_finite_diff) for d in perturbs] d_logits = logits_from_embedding_fn([emb + d for (emb, d) in zip(embedded, perturbs)]) kl = _kl_divergence_with_logits(logits, d_logits, weights, num_classes) perturbs = tf.gradients( kl, perturbs, aggregation_method=tf.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) perturbs = [tf.stop_gradient(d) for d in perturbs] perturbs = [_scale_l2(_mask_by_length(d, length), perturb_norm_length) for d in perturbs] vadv_logits = logits_from_embedding_fn([emb + d for (emb, d) in zip(embedded, perturbs)]) return _kl_divergence_with_logits(logits, vadv_logits, weights, num_classes)
tensorflow.shape
14,574
import tensorflow as tf print("eval/loss: %.6f\n" % avg_loss.result()) with tf.contrib.summary.always_record_summaries(): tf.contrib.summary.scalar("loss", avg_loss.result()) def train_one_epoch(model, optimizer, train_data, log_interval=10): """Trains model on train_data using optimizer.""" tf.train.get_or_create_global_step() def model_loss(labels, chars, sequence_length): predictions = model((chars, sequence_length), training=True) loss_value = loss(labels, predictions) tf.contrib.summary.scalar("loss", loss_value) return loss_value
tensorflow.train.get_or_create_global_step
14,575
import tensorflow as tf # pred1, pred2 = tf.split(horizon_pred, 2, axis=0) # tgt1, tgt2 = tf.split(horizon_tgt, 2, axis=0) even = [2 * i for i in range(25)] odd = [2 * i + 1 for i in range(25)] pred1 = tf.gather(horizon_pred, even) pred2 = tf.gather(horizon_pred, odd) tgt1 = tf.gather(horizon_tgt, even) tgt2 = tf.gather(horizon_tgt, odd) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool)
tensorflow.gather
14,576
import tensorflow as tf import datetime import BatchDatsetReader as dataset from six.moves import xrange import os.path as osp FLAGS = tf.flags.FLAGS tf.flags.DEFINE_integer("batch_size", "2", "batch size for training") tf.flags.DEFINE_string("logs_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\logs", "path to logs directory") tf.flags.DEFINE_string("data_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\Data_zoo\STEM", "path to dataset") tf.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer") tf.flags.DEFINE_string("model_dir", r"E:\work\01-Myproject\imag_division\FCN.tensorflow-master\Model_zoo", "Path to vgg model mat") tf.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False") tf.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize") MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat' MAX_ITERATION = 100 #最大步数 NUM_OF_CLASSESS = 3 #分类数目 IMAGE_SIZE = 2048 #图像大小 def vgg_net(weights, image): layers = (
tensorflow.flags.DEFINE_bool
14,577
from tensorflow.python.ops import gradients """See base class.""" global_step = variables.get_global_step() assert global_step loss = self._loss( self._logits(features), targets, self._get_weight_tensor(features)) logging_ops.scalar_summary("loss", loss) linear_vars = self._get_linear_vars() dnn_vars = self._get_dnn_vars() grads = gradients.gradients(loss, dnn_vars + linear_vars) dnn_grads = grads[0:len(dnn_vars)] linear_grads = grads[len(dnn_vars):] 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")
tensorflow.python.ops.gradients.gradients
14,578
from tensorflow.contrib.learn.python.learn.io import data_feeder def input_fn(): return x.create_graph() return input_fn, None df = data_feeder.setup_train_data_feeder(x, None, n_classes=None, batch_size=batch_size) return df.input_builder, df.get_feed_dict_fn()
tensorflow.contrib.learn.python.learn.io.data_feeder.setup_train_data_feeder
14,579
import tensorflow as tf cell_inputs = [layers[-2][0] if len(layers) > 1 else layers[-1][0], layers[-1][0]] blocks = [] for bi in range(b): with tf.variable_scope('block_{}'.format(bi)): idx1 = cell_arch[bi][0] op1 = cell_arch[bi][1] idx2 = cell_arch[bi][2] op2 = cell_arch[bi][3] with tf.variable_scope('X1'): X1 = self._add_op_dynamic(cell_inputs, blocks, idx1, op1, w, h, block_ch, is_train=is_train) X1 = self._add_drop_path(X1, drop_path_keep_prob) with tf.variable_scope('X2'): X2 = self._add_op_dynamic(cell_inputs, blocks, idx2, op2, w, h, block_ch, is_train=is_train) X2 = self._add_drop_path(X2, drop_path_keep_prob) X = tf.add_n([X1, X2]) blocks.append(X) (X, comb_ch) = self._combine_cell_blocks_dynamic(cell_inputs, blocks, cell_arch, w, h, block_ch, is_train) X = tf.reshape(X, (-1, w, h, comb_ch)) # Sanity shape check layers.append((X, w, h, comb_ch))
tensorflow.variable_scope
14,580
import tensorflow as tf action_templates_embedding_size = 8 num_actions_arguments = data.batch_actions_arguments.shape[2] actions_arguments_vocabulary_length = len(data.idx2word_action_arguments) with tf.name_scope('data'): batch_histories = tf.Variable(data.batch_histories, name='histories', trainable=False) batch_actions_template = tf.Variable(data.batch_actions_template, name='actions', trainable=False) batch_action_arguments = tf.Variable(data.batch_actions_arguments, name='actions_arguments', trainable=False) histories = tf.gather(batch_histories, self.batch_idx) actions_template = tf.gather(batch_actions_template, self.batch_idx) actions_arguments = tf.gather(batch_action_arguments, self.batch_idx) with tf.name_scope('model'): encoder_embedding = embedding( input=histories, length=histories_vocabulary_length, size=histories_embedding_size, name='encoder_embedding' ) with tf.name_scope("UtterancesEncoder"):
tensorflow.gather
14,581
from tensorflow.python.framework import ops transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name) else: return gen_math_ops._mat_mul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) sparse_matmul = gen_math_ops._sparse_mat_mul batch_matmul = gen_math_ops._batch_mat_mul ops.RegisterShape("MatMul")(common_shapes.matmul_shape) ops.RegisterShape("SparseMatMul")(common_shapes.matmul_shape) def _as_indexed_slices(x): """Convert 'x' to IndexedSlices. Convert a dense Tensor to a block-sparse IndexedSlices. Args: x: Either a Tensor object, or an IndexedSlices object. Returns: An IndexedSlices object.
tensorflow.python.framework.ops.RegisterShape
14,582
import tensorflow as tf g_loss = tf.reduce_mean(tf.squared_difference(fake, 1), name='g_loss')
tensorflow.squared_difference
14,583
import tensorflow as tf ) outputs = tf.layers.dense(outputs, units=num_units[1], activation=tf.nn.relu, name="dense2") outputs = tf.layers.dropout( outputs, rate=dropout_rate, training=is_training, name="dropout2"
tensorflow.layers.dropout
14,584
import tensorflow as tf with tf.device('/gpu:%d' % i): with tf.name_scope('tower_%d' % i):
tensorflow.name_scope
14,585
from tensorflow.python.ops import gen_state_ops container: An optional string. Defaults to "". If non-empty, this variable is placed in the given container. Otherwise, a default container is used. shared_name: An optional string. Defaults to "". If non-empty, this variable is named in the given bucket with this shared_name. Otherwise, the node name is used instead. Returns: A variable tensor. """ ret = gen_state_ops._variable(shape=shape, dtype=dtype, name=name, container=container, shared_name=shared_name) # TODO(mrry): Move this to where it is used, so we can get rid of this op # wrapper? if set_shape: ret.set_shape(shape) return ret # NOTE(mrry): Shapes are conditionally set in the Python wrapper.
tensorflow.python.ops.gen_state_ops._variable
14,586
import tensorflow as tf 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)))
tensorflow.identity
14,587
import tensorflow as tf "lookup_table", dtype=tf.float32, shape=[len(vocab), size_layers], initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.01), ) lookup_table = tf.concat((tf.zeros(shape=[1, size_layers]), lookup_table[1:, :]), 0) forward = tf.nn.embedding_lookup(lookup_table, self.X) self.Y = tf.placeholder(tf.float32, (None, None, n_mels * resampled)) self.decoder_inputs = tf.concat((tf.zeros_like(self.Y[:, :1, :]), self.Y[:, :-1, :]), 1) self.decoder_inputs = self.decoder_inputs[:, :, -n_mels:] self.Z = tf.placeholder(tf.float32, (None, None, fourier_window_size // 2 + 1))
tensorflow.nn.embedding_lookup
14,588
from tensorflow.contrib.eager.python.examples.spinn import data vocab = data.load_vocabulary(self._temp_data_dir) word2index, embed = data.load_word_vectors(self._temp_data_dir, vocab) train_data = data.SnliData(fake_train_file, word2index) dev_data = data.SnliData(fake_train_file, word2index) test_data = data.SnliData(fake_train_file, word2index)
tensorflow.contrib.eager.python.examples.spinn.data.SnliData
14,589
import tensorflow as tf 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', - 0.01 * tf.reduce_mean(pi.entropy())) 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): 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 def build_cnet(self, state_in, name, reuse=False): reg = tf.contrib.layers.l2_regularizer(1e-3) with tf.variable_scope(name, reuse=reuse): layer_c1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg) layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg)
tensorflow.layers.dense
14,590
import tensorflow as tf res1 = sess.run(outputs_dict1["0"]) res2 = sess.run(outputs_dict2["0"]) res3 = sess.run(outputs_dict3["0"]) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testSequenceLoss(self): with self.test_session() as sess: logits = [tf.constant(i + 0.5, shape=[2, 5]) for i in range(3)] targets = [tf.constant(i, tf.int32, shape=[2]) for i in range(3)] weights = [tf.constant(1.0, shape=[2]) for i in range(3)] average_loss_per_example = tf.nn.seq2seq.sequence_loss( logits, targets, weights, average_across_timesteps=True, average_across_batch=True) res = sess.run(average_loss_per_example) self.assertAllClose(1.60944, res)
tensorflow.constant
14,591
from tensorflow.python.platform import gfile class KeepCheckpointEveryNHoursTest(tf.test.TestCase): def testNonSharded(self): save_dir = os.path.join(self.get_temp_dir(), "keep_checkpoint_every_n_hours") try: gfile.DeleteRecursively(save_dir) except OSError: pass # Ignore gfile.MakeDirs(save_dir) with self.test_session() as sess: v = tf.Variable([10.0], name="v") # Run the initializer NOW to avoid the 0.5s overhead of the first Run() # call, which throws the test timing off in fastbuild mode. tf.initialize_all_variables().run() # Create a saver that will keep the last 2 checkpoints plus one every 0.7 # seconds. start_time = time.time()
tensorflow.python.platform.gfile.MakeDirs
14,592
import tensorflow as tf layers_to_output = {'rois': rois} layers_to_output.update(self._predictions) for var in tf.trainable_variables(): self._train_summaries.append(var)
tensorflow.trainable_variables
14,593
import tensorflow as tf return output_tensor def input_fn_builder( input_files, max_seq_length, max_predictions_per_seq, is_training, num_cpu_threads=4 ): """Creates an `input_fn` closure to be passed to TPUEstimator.""" def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] name_to_features = { "input_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "input_mask": tf.FixedLenFeature([max_seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([max_seq_length], tf.int64), "masked_lm_positions": tf.FixedLenFeature( [max_predictions_per_seq], tf.int64 ), "masked_lm_ids": tf.FixedLenFeature([max_predictions_per_seq], tf.int64), "masked_lm_weights": tf.FixedLenFeature( [max_predictions_per_seq], tf.float32 ), "next_sentence_labels": tf.FixedLenFeature([1], tf.int64), } # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. if is_training: d = tf.data.Dataset.from_tensor_slices(tf.constant(input_files))
tensorflow.FixedLenFeature
14,594
import tensorflow as tf bert_config, model.get_sequence_output(), model.get_embedding_table(), masked_lm_positions, masked_lm_ids, masked_lm_weights, clip) (next_sentence_loss, next_sentence_example_loss, next_sentence_log_probs) = get_next_sentence_output( bert_config, model.get_pooled_output(), next_sentence_labels, clip) total_loss = masked_lm_loss + next_sentence_loss 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:
tensorflow.trainable_variables
14,595
import tensorflow as tf entity_init = tf.truncated_normal(entity_embedding_shape, stddev=init_sd) rel_init = tf.truncated_normal(rel_embedding_shape, stddev=init_sd) if self.maxnorm is not None: # Ensure maxnorm constraints are initially satisfied entity_init = dense_maxnorm(entity_init, self.maxnorm) rel_init = dense_maxnorm(rel_init, self.maxnorm) self.entity_embedding_vars = tf.Variable(entity_init) self.rel_embedding_vars = tf.Variable(rel_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input) tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input) rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input) # Reshape rel_embed into square D x D matrices rel_embed_square = tf.reshape(rel_embed, (-1, self.embedding_size, self.embedding_size)) # Reshape head_embed and tail_embed to be suitable for the matrix multiplication head_embed_row = tf.expand_dims(head_embed, 1) # embeddings as row vectors tail_embed_col = tf.expand_dims(tail_embed, 2) # embeddings as column vectors head_rel_mult = tf.batch_matmul(head_embed_row, rel_embed_square) # Output needs a squeeze into a 1d vector raw_output = tf.squeeze(tf.batch_matmul(head_rel_mult, tail_embed_col)) self.output, self.loss = self._create_output_and_loss(raw_output) # Optimization self.train_step = self.opt.minimize(self.loss) if self.maxnorm is not None: # Post-processing to limit embedding vars to L2 ball rel_maxnorm = self.maxnorm * self.rel_maxnorm_mult unique_ent_indices = tf.unique(tf.concat(0, [self.head_input, self.tail_input]))[0] unique_rel_indices = tf.unique(self.rel_input)[0] entity_constraint = self._norm_constraint_op(self.entity_embedding_vars, unique_ent_indices,
tensorflow.expand_dims
14,596
import tensorflow as tf # queue. image, label = read_and_decode(filename_queue) # Shuffle the examples and collect them into batch_size batches. # (Internally uses a RandomShuffleQueue.) # We run this in two threads to avoid being a bottleneck. images, sparse_labels = tf.train.shuffle_batch( [image, label], batch_size=batch_size, num_threads=8, capacity=1000 + 3 * batch_size, # Ensures a minimum amount of shuffling of examples. min_after_dequeue=1000)
tensorflow.train.shuffle_batch
14,597
from tensorflow.python.ops import array_ops weights = math_ops.to_double(weights) average_precision = math_ops.mul(average_precision, weights) # Create accumulation variables and update ops for max average precision and # total average precision. with ops.name_scope(None, 'max', (average_precision,)) as max_scope: # `max` is the max possible precision. Since max for any row is 1.0: # - For the unweighted case, this is just the number of rows. # - For the weighted case, it's the sum of the weights broadcast across # `average_precision` rows. max_var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=max_scope) if weights is None: batch_max = math_ops.to_double( array_ops.size(average_precision, name='batch_max')) else: # TODO(ptucker): More efficient way to broadcast? broadcast_weights = math_ops.mul( weights, array_ops.ones_like(average_precision), name='broadcast_weights') batch_max = math_ops.reduce_sum(broadcast_weights, name='batch_max') max_update = state_ops.assign_add(max_var, batch_max, name='update') with ops.name_scope(None, 'total', (average_precision,)) as total_scope: total_var = contrib_variables.local_variable( array_ops.zeros([], dtype=dtypes.float64), name=total_scope) batch_total = math_ops.reduce_sum(average_precision, name='batch_total') total_update = state_ops.assign_add(total_var, batch_total, name='update')
tensorflow.python.ops.array_ops.size
14,598
import tensorflow as tf lr_values = [params['learning_rate'] * decay for decay in params['lr_decay_factors']] learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32), [int(_) for _ in params['decay_boundaries']], lr_values) truncated_learning_rate = tf.maximum(learning_rate, tf.constant(params['end_learning_rate'], dtype=learning_rate.dtype)) # Create a tensor named learning_rate for logging purposes. tf.identity(truncated_learning_rate, name='learning_rate') 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.
tensorflow.identity
14,599