seed
stringlengths
25
1.88k
seed_api
stringlengths
14
102
index
int64
0
1.05k
from tensorflow.python.ops import array_ops def loss_fn(logits, target): check_shape_op = control_flow_ops.Assert( math_ops.less_equal(array_ops.rank(target), 2), ["target's shape should be either [batch_size, 1] or [batch_size]"]) with ops.control_dependencies([check_shape_op]):
tensorflow.python.ops.array_ops.rank
400
import tensorflow as tf self.mu = self.mu * action_bound[1]; self.sigma = self.sigma + 1e-5 self.normal_dist = tf.contrib.distributions.Normal(self.mu, self.sigma) self.action = tf.squeeze(self.normal_dist.sample(1),axis=0);
tensorflow.contrib.distributions.Normal
401
import tensorflow as tf 'learning_rate_decay_factor': FLAGS.learning_rate_decay_factor, 'decay_steps': FLAGS.decay_steps, 'decay_boundaries': parse_comma_list(FLAGS.decay_boundaries), 'lr_decay_factors': parse_comma_list(FLAGS.lr_decay_factors), }) tensors_to_log = { 'lr': 'learning_rate', 'ce_loss': 'cross_entropy_loss', 'loc_loss': 'location_loss', 'total_loss': 'total_loss', 'cls_acc': 'cls_accuracy', } logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=FLAGS.log_every_n_steps) print('Starting a training cycle.') xdetector.train(input_fn=input_pipeline(), hooks=[logging_hook]) if __name__ == '__main__': tf.logging.set_verbosity(tf.logging.INFO) tf.app.run()
tensorflow.train.LoggingTensorHook
402
import tensorflow as tf def _float_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value.flatten())) def _bytes_feature(value): if isinstance(value, str): value = value.encode('utf-8') return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def make_tf_example(d): feature = { 'bounding_box_samples': _float_feature(d['bounding_box_samples']), 'depth_renders': _float_feature(d['depth_renders']),
tensorflow.train.BytesList
403
from tensorflow.contrib.eager.python.examples.linear_regression import linear_regression def testLinearRegression(self): true_w = [[1.0], [-0.5], [2.0]] true_b = [1.0] model = linear_regression.LinearModel() dataset = linear_regression.synthetic_dataset( true_w, true_b, noise_level=0., batch_size=64, num_batches=40) with tf.device(device()): optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1) linear_regression.fit(model, dataset, optimizer, logdir=self._tmp_logdir)
tensorflow.contrib.eager.python.examples.linear_regression.linear_regression.synthetic_dataset
404
from tensorflow.python.framework import ops return self.read_value() # Register a conversion function which reads the value of the variable, # allowing instances of the class to be used as tensors. def _tensor_conversion(var, dtype=None, name=None, as_ref=False): return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access ops.register_tensor_conversion_function(ReplicatedVariable, _tensor_conversion) if not TF_23: ops.register_dense_tensor_like_type(ReplicatedVariable)
tensorflow.python.framework.ops.register_dense_tensor_like_type
405
from tensorflow.python.ops import control_flow_ops assign_op = state_ops.assign(array, new_value, validate_shape=False) with ops.control_dependencies([assign_op]): copy_op = array[:size].assign(old_value[:size]) # return value needs to be the same dtype as no_op() for cond with ops.control_dependencies([copy_op]): return control_flow_ops.no_op() new_size = size + batch_size array_size = array_ops.shape_internal(array, optimize=False)[0] maybe_reallocate_op = control_flow_ops.cond( new_size > array_size, reallocate, control_flow_ops.no_op) with ops.control_dependencies([maybe_reallocate_op]): append_values_op = array[size:new_size].assign(batch_values) with ops.control_dependencies([append_values_op]): update_op = size.assign(new_size) if metrics_collections: ops.add_to_collections(metrics_collections, value)
tensorflow.python.ops.control_flow_ops.cond
406
import tensorflow as tf model = model_cls(params) # Multi-GPU setting sharded_losses = parallel.parallel_model( model.get_training_func(initializer), features, params.device_list ) loss = tf.add_n(sharded_losses) / len(sharded_losses) # Create global step global_step = tf.train.get_or_create_global_step() # Print parameters all_weights = {v.name: v for v in tf.trainable_variables()} total_size = 0 for v_name in sorted(list(all_weights)): v = all_weights[v_name] tf.logging.info("%s\tshape %s", v.name[:-2].ljust(80), str(v.shape).ljust(20)) v_size = np.prod(np.array(v.shape.as_list())).tolist() # mutiple all dimension size
tensorflow.train.get_or_create_global_step
407
from tensorflow.python.ops import nn # sigmoid_cross_entropy_with_logits requires [batch_size, 1] target. # Check that we got int32/int64 for classification. if (not target.dtype.is_compatible_with(dtypes.int64) and not target.dtype.is_compatible_with(dtypes.int32)): raise ValueError("Target's dtype should be int32, int64 or compatible. " "Instead got %s." % target.dtype) # sparse_softmax_cross_entropy_with_logits requires [batch_size] target. if len(target.get_shape()) == 2: target = array_ops.squeeze(target, squeeze_dims=[1]) loss_vec = nn.sparse_softmax_cross_entropy_with_logits(logits, target) return loss_vec def _run_metrics(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.nn.sparse_softmax_cross_entropy_with_logits
408
import tensorflow as tf alpha=AGENT_ALPHA, dtype=tf.float32) agent_epsgreedy = neural_epsilon_greedy_agent.NeuralEpsilonGreedyAgent( time_step_spec=environment.time_step_spec(), action_spec=environment.action_spec(), reward_network=network, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=LR), emit_policy_info=emit_policy_info, epsilon=EPSILON) agent = exp3_mixture_agent.Exp3MixtureAgent( (agent_linucb, agent_lints, agent_epsgreedy))
tensorflow.compat.v1.train.AdamOptimizer
409
import tensorflow as tf self._dim = None self._p = p def _compute(self, x, y): self._dim = x._rank() kernel = np.zeros((tf.size(x), tf.size(y))) for l in tf.range(start=0, limit=tf.size(x), delta=1, dtype=None, name='l_range'): for m in tf.range(start=0, limit=tf.size(y), delta=1, dtype=None, name='m_range'): vx = tf.contrib.lookup.MutableHashTable(key_dtype=tf.string, value_dtype=tf.int64, default_value=-1) vz = tf.contrib.lookup.MutableHashTable(key_dtype=tf.string, value_dtype=tf.int64, default_value=-1) vx_keys = tf.reshape(tf.Variable([], collections=[], dtype=tf.string), (-1, 1)) vz_keys = tf.reshape(tf.Variable([], collections=[], dtype=tf.string), (-1, 1))
tensorflow.contrib.lookup.MutableHashTable
410
from tensorflow.python.training import training_util self._training_initial_clusters, self._num_clusters, self._random_seed, self._covariance_type, self._params) incr_step = state_ops.assign_add(training_util.get_global_step(), 1) loss = math_ops.reduce_sum(losses) training_op = with_dependencies([training_op, incr_step], loss) training_hooks = [_InitializeClustersHook(
tensorflow.python.training.training_util.get_global_step
411
import tensorflow as tf import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import grid from tensorflow_graphics.math.interpolation import trilinear from tensorflow_graphics.projects.points_to_3Dobjects.models import centernet_utils from tensorflow_graphics.projects.points_to_3Dobjects.utils import tf_utils from google3.pyglib import gfile from google3.third_party.google_research.google_research.tf3d.object_detection.box_utils import np_box_ops class ShapeAccuracyMetric: """Computes the accuracy of shpe prediction.""" def __init__(self, k=1): self.metric = tf.keras.metrics.SparseTopKCategoricalAccuracy(k) def update(self, sparse_labels, predicted_probabilities, sample_weights=None): self.metric.update_state(sparse_labels, predicted_probabilities, sample_weights) def evaluate(self): return self.metric.result().numpy() def reset(self): self.metric.reset_states() def get_2d_bounding_box_iou(box1, box2):
tensorflow.keras.metrics.SparseTopKCategoricalAccuracy
412
import tensorflow as tf def build_batch_stats(): """Builds the batch statistics calculation ops.""" # We use the moving mean as an estimate of the mean in order to perform # a more numerically stable calculation of the batch mean. # Copy for better stability. shift = tf.add(self._moving_mean, 0) counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.sufficient_statistics( input_batch, reduction_indices, keep_dims=True, shift=shift, name="batch_norm_ss") mean, variance = tf.nn.normalize_moments(counts, shifted_sum_x, shifted_sum_x2, shift, name="normalize_moments") return mean, variance def build_moving_stats(): return ( tf.identity(self._moving_mean), tf.identity(self._moving_variance), ) mean, variance = utils.smart_cond(
tensorflow.nn.normalize_moments
413
from tensorflow.python.framework import tensor_shape cannot be inferred. """ if tensor_dtype is None: if not inputs or not isinstance(inputs, (list, tuple)): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs) if not all(isinstance(x, ops.Tensor) for x in inputs): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") if not all(x.dtype == inputs[0].dtype for x in inputs): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") tensor_dtype = inputs[0].dtype if shape is not None: shape = tensor_shape.as_shape(shape) else: shape = tensor_shape.unknown_shape() for input_tensor in inputs: if isinstance(input_tensor, ops.Tensor): shape = shape.merge_with(input_tensor.get_shape()) if not shape.is_fully_defined(): # TODO(pbar): Make a version of assign_add that accepts an uninitialized # lvalue, and takes its shape from that? This would allow accumulate_n to # work in all situations that add_n currently works. raise ValueError("Cannot infer the shape of the accumulator for " "accumulate_n. Pass the shape argument, or set the shape " "of at least one of the inputs.") with ops.op_scope(inputs, name, "AccumulateN") as name: var = gen_state_ops._temporary_variable(shape=shape, dtype=tensor_dtype)
tensorflow.python.framework.tensor_shape.as_shape
414
from tensorflow.python.ops import gen_math_ops name: A name for the operation (optional). Returns: A `Tensor` the same size and type as `x` with absolute values. """ with ops.op_scope([x], name, "Abs") as name: x = ops.convert_to_tensor(x, name="x") if x.dtype == types.complex64: return gen_math_ops.complex_abs(x, name=name) return gen_math_ops._abs(x, name=name) def pow(x, y, name=None): """Computes the power of one value to another. Given a tensor `x` and a tensor `y`, this operation computes \\\\(x^y\\\\) for corresponding elements in `x` and `y`. For example:
tensorflow.python.ops.gen_math_ops._abs
415
from tensorflow.contrib.distributions.python.ops import distribution_util def _batch_shape_tensor(self): return array_ops.shape(self.rate) def _batch_shape(self): return self.rate.get_shape() def _event_shape_tensor(self): return constant_op.constant([], dtype=dtypes.int32) def _event_shape(self): return tensor_shape.scalar() @distribution_util.AppendDocstring(_poisson_sample_note) def _log_prob(self, x): return self._log_unnormalized_prob(x) - self._log_normalization() @distribution_util.AppendDocstring(_poisson_sample_note) def _prob(self, x): return math_ops.exp(self._log_prob(x)) @distribution_util.AppendDocstring(_poisson_sample_note) def _log_cdf(self, x): return math_ops.log(self.cdf(x))
tensorflow.contrib.distributions.python.ops.distribution_util.AppendDocstring
416
import tensorflow as tf num_block_layers = 3 dense_layer_depth = 16 def lstm_network(input, scope='lstm_network'): with tf.variable_scope(scope): # tf.nn.rnn_cell lstm_cell1 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer1, forget_bias=1.0) lstm_cell2 = tf.contrib.rnn.BasicLSTMCell(lstm_hidden_size_layer2, forget_bias=1.0) lstm_cells = tf.contrib.rnn.MultiRNNCell(cells=[lstm_cell1, lstm_cell2], state_is_tuple=True) # tf.nn.rnn_cell # lstm_cell1 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size_layer1, forget_bias=1.0) # lstm_cell2 = tf.nn.rnn_cell.LSTMCell(lstm_hidden_size_layer2, forget_bias=1.0) #lstm_cells = tf.nn.rnn_cell.MultiRNNCell(cells=[lstm_cell1, lstm_cell2], state_is_tuple=True) # initial_state = lstm_cells.zero_state(batch_size, tf.float32) _, states = tf.nn.dynamic_rnn(lstm_cells, input, dtype=tf.float32, initial_state=None)
tensorflow.contrib.rnn.MultiRNNCell
417
import tensorflow as tf pop_mean = tf.get_variable('pop_mean', [shape[-1]], initializer=tf.constant_initializer(0.), trainable=False) pop_var = tf.get_variable('pop_var', [shape[-1]], initializer=tf.constant_initializer(1.), trainable=False) if pop_mean not in tf.moving_average_variables(): tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, pop_mean) tf.add_to_collection(tf.GraphKeys.MOVING_AVERAGE_VARIABLES, pop_var) def func1(): # execute at training time batch_mean, batch_var = tf.nn.moments(x, range(len(shape) - 1)) update_mean = tf.assign_sub(pop_mean, (1 - decay)*(pop_mean - batch_mean)) update_var = tf.assign_sub(pop_var, (1 - decay)*(pop_var - batch_var)) with tf.control_dependencies([update_mean, update_var]): return tf.nn.batch_normalization(x, batch_mean, batch_var, beta, gamma, epsilon) def func2(): # execute at test time return tf.nn.batch_normalization(x, pop_mean, pop_var, beta, gamma, epsilon) return tf.cond(train, func1, func2) def average_gradients(tower_grads):
tensorflow.assign_sub
418
import tensorflow as tf max_seq_length=FLAGS.max_seq_length, max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=True, batch_size=FLAGS.train_batch_size, use_hvd=FLAGS.use_hvd) if FLAGS.auto_recover: hooks.append(tf.data.experimental.CheckpointInputPipelineHook(estimator)) estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps, hooks=hooks) if FLAGS.do_eval: tf.logging.info("***** Running evaluation *****") tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
tensorflow.data.experimental.CheckpointInputPipelineHook
419
import tensorflow as tf """Concat box coordinates in the format of [ymin, xmin, ymax, xmax].""" xmin = parsed_tensors['image/object/bbox/xmin'] xmax = parsed_tensors['image/object/bbox/xmax'] ymin = parsed_tensors['image/object/bbox/ymin'] ymax = parsed_tensors['image/object/bbox/ymax'] return tf.stack([ymin, xmin, ymax, xmax], axis=-1) def _decode_masks(self, parsed_tensors): """Decode a set of PNG masks to the tf.float32 tensors.""" def _decode_png_mask(png_bytes): mask = tf.squeeze( tf.io.decode_png(png_bytes, channels=1, dtype=tf.uint8), axis=-1) mask = tf.cast(mask, dtype=tf.float32) mask.set_shape([None, None]) return mask height = parsed_tensors['image/height'] width = parsed_tensors['image/width'] masks = parsed_tensors['image/object/mask'] return tf.cond( pred=tf.greater(tf.size(input=masks), 0), true_fn=lambda: tf.map_fn(_decode_png_mask, masks, dtype=tf.float32),
tensorflow.io.decode_png
420
import tensorflow as tf 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)])
tensorflow.stop_gradient
421
from tensorflow.python.ops import array_ops if all(tensor.shape == tensor_shape.scalar() for tensor in tensors): with ops.device(tensors[0].device): values = array_ops.stack(tensors) with ops.device(device): return array_ops.unstack(values) else: with ops.device(tensors[0].device): sizes = array_ops.stack( [array_ops.shape(tensor)[0] for tensor in tensors]) values = array_ops.concat(tensors, axis=0) with ops.device(device): sizes = array_ops.unstack(sizes) return list(array_ops.split(values, sizes, axis=0)) def _scheduled_stamp_resource_op_runner(batch, stamp): """Runs a batch operation on a stamped resource.""" if not batch: return arg_keys = set(batch[0].args.keys()) grouped_args = collections.OrderedDict() resource_handles = []
tensorflow.python.ops.array_ops.unstack
422
import tensorflow as tf @gin.configurable(module='trax.data', denylist=['dataset', 'training']) def c4_preprocess(dataset, training, max_target_length=-1, tokenization=None, spm_path=None): """Pre-processing function for C4 dataset.""" del training def unicode_decode_chars(features, targets): targets = tf.strings.unicode_decode(features['text'], 'UTF-8') targets = tf.cast(targets, tf.int64) features['targets'] = targets features['inputs'] = targets return (features, targets) def spc_tokenize(tokenizer, features, targets): del targets tokenized_text = tokenizer.tokenize(features['text']) features['targets'] = tf.cast(tokenized_text, tf.int64)
tensorflow.strings.unicode_decode
423
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
424
from tensorflow.contrib.learn.python.learn.datasets import base train_path = os.path.join(data_dir, 'dbpedia_csv/train.csv') test_path = os.path.join(data_dir, 'dbpedia_csv/test.csv') if not (gfile.Exists(train_path) and gfile.Exists(test_path)): archive_path = base.maybe_download( 'dbpedia_csv.tar.gz', data_dir, DBPEDIA_URL) tfile = tarfile.open(archive_path, 'r:*')
tensorflow.contrib.learn.python.learn.datasets.base.maybe_download
425
import tensorflow as tf 'member/age': tf.io.FixedLenFeature([], tf.int64), 'member/height': tf.io.VarLenFeature(tf.float32), 'member/prefer_prods': tf.io.VarLenFeature(tf.int64)} features = tf.io.parse_single_example(example_proto, features) images = tf.image.decode_png(features['member/encoded'], channels=3) # 注意png原本有4個channel,但執行到下面的處理會出錯,所以前一行先降成3個channel。 images = tf.image.random_brightness(images, 0.1) images = tf.image.random_saturation(images, 0.7, 1.3) images = tf.image.random_contrast(images, 0.6, 1.5) images = tf.image.random_flip_left_right(images) return features, images if __name__ == '__main__': main()
tensorflow.image.random_contrast
426
from tensorflow.python.training import saver as saver_lib # Check that we are not running evaluation on the same checkpoint. latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir)
tensorflow.python.training.saver.latest_checkpoint
427
from tensorflow.python.ops import math_ops if metrics is None and self._n_classes > 1: metrics = {"accuracy": metrics_lib.streaming_accuracy} if self._n_classes == 2: predictions = math_ops.sigmoid(logits) result["eval_auc"] = metrics_lib.streaming_auc(predictions, targets) if metrics:
tensorflow.python.ops.math_ops.sigmoid
428
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib GMM.SCORES: _streaming_sum(loss), } return model_fn_lib.ModelFnOps(mode=mode, predictions=predictions, eval_metric_ops=eval_metric_ops,
tensorflow.contrib.learn.python.learn.estimators.model_fn.ModelFnOps
429
import tensorflow as tf elif params.initializer == "normal_unit_scaling": return tf.variance_scaling_initializer(params.initializer_gain, mode="fan_avg", distribution="normal") elif params.initializer == "uniform_unit_scaling": return tf.variance_scaling_initializer(params.initializer_gain, mode="fan_avg", distribution="uniform") else: raise ValueError("Unrecognized initializer: %s" % params.initializer)
tensorflow.variance_scaling_initializer
430
from tensorflow.contrib.layers.python.layers import feature_column for i in range(4) ] linear_features.append( feature_column.sparse_column_with_hash_bucket( 'dummy_sparse_column', hash_bucket_size=100))
tensorflow.contrib.layers.python.layers.feature_column.sparse_column_with_hash_bucket
431
import tensorflow as tf """ with tf.variable_scope(scope, 'precision_at_recall', [logits, labels, label_priors], reuse=reuse):
tensorflow.variable_scope
432
import tensorflow as tf filter_depths=[128, 128, 512], kernel_size=3) x = self.__identity_block(stage=2, block=5, inputs=x, filter_depths=[128, 128, 512], kernel_size=3) x = self.__conv_block(stage=3, block=0, inputs=x, filter_depths=[256, 256, 1024], kernel_size=3, stride=2) x = self.__identity_block(stage=3, block=1, inputs=x, filter_depths=[256, 256, 1024], kernel_size=3) x = self.__identity_block(stage=3, block=2, inputs=x, filter_depths=[256, 256, 1024], kernel_size=3) x = tf.keras.layers.AveragePooling2D(pool_size=7, strides=1, padding="valid", name="pool")(x) x = tf.reshape(x, shape=(-1, 1024)) self.logits = self.__fully_connected(name="fc_nsfw", inputs=x, num_outputs=2) self.predictions = tf.nn.softmax(self.logits, name="predictions") """Get weights for layer with given name """ def __get_weights(self, layer_name, field_name): if not layer_name in self.weights: raise ValueError("No weights for layer named '{}' found"
tensorflow.keras.layers.AveragePooling2D
433
import tensorflow as tf tf.constant(0, tf.int32, shape=[2]) for _ in range(4)] with tf.variable_scope("other"): outputs_dict3, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() outputs_dict1, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=True) outputs_dict2, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=True) 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):
tensorflow.nn.seq2seq.one2many_rnn_seq2seq
434
import tensorflow as tf out = activation(out) if dropout > 0: out = tf.layers.dropout(out, rate=dropout, training=training) out = conv(out, [2*dim[0], dim[1], dim[2]], scope="%s_conv_out"%scope, training=training, ema=ema, init=init) h_stack1, h_stack2 = tf.split(out, 2, 3) sigmoid_out = tf.sigmoid(h_stack2) out = (h_stack1 * sigmoid_out) out_shp = out.get_shape().as_list() if out_shp[1:-1] < in_shp[1:-1]: x = tf.nn.avg_pool(x, [1, dim[2][0], dim[2][1], 1], strides=[1, dim[2][0], dim[2][1], 1], padding='SAME')
tensorflow.split
435
import tensorflow as tf shapes[rconst.DUPLICATE_MASK] = tf.TensorShape([batch_size]) data_generator = functools.partial( self.data_generator, epochs_between_evals=epochs_between_evals) dataset = tf.data.Dataset.from_generator( generator=data_generator, output_types=types, output_shapes=shapes)
tensorflow.data.Dataset.from_generator
436
from tensorflow.contrib.learn.python.learn.graph_actions import infer random_seed.set_random_seed(self._config.tf_random_seed) contrib_framework.create_global_step(g) features, _ = input_fn() feed_dict = feed_fn() if feed_fn is not None else None predictions = self._get_predict_ops(features) if not isinstance(predictions, dict): predictions = {'predictions': predictions} # TODO(ipolosukhin): Support batching return infer(checkpoint_path, predictions, feed_dict=feed_dict) class Estimator(BaseEstimator): """Estimator class is the basic TensorFlow model trainer/evaluator. Parameters: model_fn: Model function, takes features and targets tensors or dicts of
tensorflow.contrib.learn.python.learn.graph_actions.infer
437
from tensorflow.python.framework import op_def_registry as _op_def_registry result = _op_def_lib.apply_op( "XlaRecv", dtype=dtype, shape=shape, tensor_name=tensor_name, name=name if name else "XlaRecv") return result def _InitOpDefLibrary(): op_list = _op_def_pb2.OpList() _text_format.Merge(_InitOpDefLibrary.op_list_ascii, op_list) _op_def_registry.register_op_list(op_list) op_def_lib = _op_def_library.OpDefLibrary() op_def_lib.add_op_list(op_list) return op_def_lib _InitOpDefLibrary.op_list_ascii = """op { name: "_Recv" output_arg { name: "tensor" type_attr: "tensor_type" }
tensorflow.python.framework.op_def_registry.register_op_list
438
from tensorflow.python.ops import math_ops def _predictions_streaming_mean(predictions, unused_labels, weights=None): return metric_ops.streaming_mean(predictions, weights=weights) def _streaming_auc(predictions, labels, weights=None): return metric_ops.streaming_auc( predictions, labels, weights=_float_weights_or_none(weights)) def _accuracy_at_threshold(threshold): def _accuracy_metric(predictions, labels, weights=None): threshold_predictions = math_ops.to_float( math_ops.greater_equal(predictions, threshold)) return metric_ops.streaming_accuracy( predictions=threshold_predictions, labels=labels, weights=weights) return _accuracy_metric def _streaming_at_threshold(streaming_metrics_fn, threshold): def _streaming_metrics(predictions, labels, weights=None): precision_tensor, update_op = streaming_metrics_fn( predictions, labels=labels, thresholds=[threshold], weights=_float_weights_or_none(weights))
tensorflow.python.ops.math_ops.greater_equal
439
import tensorflow as tf inputs_ = encoder_inputs_ inputs_ = tf.nn.convolution(inputs_, filter=filter_, padding='VALID') inputs.append(inputs_) encoder_inputs_ = tf.concat(inputs, axis=2) # if encoder.convolution_activation.lower() == 'relu': encoder_inputs_ = tf.nn.relu(encoder_inputs_) if encoder.maxout_stride: if encoder.binary: raise NotImplementedError stride = encoder.maxout_stride k = tf.to_int32(tf.ceil(time_steps / stride) * stride) - time_steps # TODO: simpler pad = tf.zeros([batch_size, k, tf.shape(encoder_inputs_)[2]]) encoder_inputs_ = tf.concat([encoder_inputs_, pad], axis=1) encoder_inputs_ = tf.nn.pool(encoder_inputs_, window_shape=[stride], pooling_type='MAX', padding='VALID', strides=[stride]) encoder_input_length_ = tf.to_int32(tf.ceil(encoder_input_length_ / stride)) if encoder.highway_layers: x = encoder_inputs_ for j in range(encoder.highway_layers): size = x.shape[2].value with tf.variable_scope('highway_{}'.format(j + 1)): g = tf.layers.dense(x, size, activation=tf.nn.sigmoid, use_bias=True, name='g')
tensorflow.ceil
440
from tensorflow.python.ops import common_shapes """Shape function for LRNGrad op.""" in_grads_shape = op.inputs[0].get_shape().with_rank(4) in_image_shape = op.inputs[1].get_shape().with_rank(4) out_image_shape = op.inputs[2].get_shape().with_rank(4) return [in_grads_shape.merge_with(in_image_shape).merge_with(out_image_shape)] ops.RegisterShape("Softmax")( common_shapes.unchanged_shape_with_rank(2)) @ops.RegisterShape("InTopK") def _InTopKShape(op): """Shape function for InTopK op.""" predictions_shape = op.inputs[0].get_shape().with_rank(2) targets_shape = op.inputs[1].get_shape().with_rank(1)
tensorflow.python.ops.common_shapes.unchanged_shape_with_rank
441
import tensorflow.contrib.graph_editor as ge fwd_ops = [op for op in fwd_ops if not '/Assign' in op.name] fwd_ops = [op for op in fwd_ops if not '/read' in op.name] ts_all = ge.filter_ts(fwd_ops, True) # get the tensors ts_all = [t for t in ts_all if '/read' not in t.name]
tensorflow.contrib.graph_editor.filter_ts
442
import tensorflow as tf self.assertEqual(save_path + "-?????-of-00002", val) meta_graph_filename = save._MetaGraphFilename(val) self.assertEqual(save_path + ".meta", meta_graph_filename) # Restore a different "v0" from shard 0 of the saved files. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") save = tf.train.Saver({"v0": v0}, sharded=True) tf.initialize_all_variables().run() self.assertEqual(111, v0.eval()) save.restore(sess, save_path + "-00000-of-00002") self.assertEqual(10, v0.eval()) # Restore a different "v1" from shard 1 of the saved files. with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v1 = tf.Variable(222)
tensorflow.initialize_all_variables
443
import tensorflow as tf if pairwise_reduction == common.DISTANCE_REDUCTION_NEG_LOG_MEAN: return lambda x: -tf.math.log(tf.math.reduce_mean(x, axis=[-2, -1])) if pairwise_reduction == common.DISTANCE_REDUCTION_LOWER_HALF_NEG_LOG_MEAN: def compute_lower_half_negative_log_mean(x): return -tf.math.log( data_utils.compute_lower_percentile_means(x, axis=[-2, -1], q=50)) return compute_lower_half_negative_log_mean if pairwise_reduction == common.DISTANCE_REDUCTION_ONE_MINUS_MEAN: return lambda x: 1.0 - tf.math.reduce_mean(x, axis=[-2, -1]) return pairwise_reduction def get_componentwise_distance_reduction_fn(): """Selects component-wise distance reduction function.""" if componentwise_reduction == common.DISTANCE_REDUCTION_MEAN: return functools.partial(tf.math.reduce_mean, axis=[-1]) return componentwise_reduction def sample_distance_fn(lhs, rhs):
tensorflow.math.reduce_mean
444
import tensorflow as tf logits = logits[:, current_output_position, :, :] return tf.squeeze(logits, axis=[1, 2]) initial_ids = tf.zeros([batch_size], dtype=tf.int32) if self.has_input: inputs_old = features["inputs"] features["inputs"] = tf.expand_dims(features["inputs"], 1) if len(features["inputs"].shape) < 5: features["inputs"] = tf.expand_dims(features["inputs"], 4) # Expand the inputs in to the beam size. features["inputs"] = tf.tile(features["inputs"], [1, beam_size, 1, 1, 1]) s = common_layers.shape_list(features["inputs"]) features["inputs"] = tf.reshape(features["inputs"], [s[0] * s[1], s[2], s[3], s[4]]) target_modality = self._problem_hparams.target_modality vocab_size = target_modality.top_dimensionality # Setting decode length to input length + decode_length decode_length = tf.constant(decode_length) if "partial_targets" not in features: decode_length += common_layers.shape_list(features["inputs"])[1]
tensorflow.tile
445
import tensorflow as tf return z, ldj else: scales = tf.math.exp(-log_sigmas) log_x = tf.math.log(x) ldj = -log_x log_y = (log_x - mus)*scales
tensorflow.math.log
446
from tensorflow.python.ops import variable_scope as vs # hoisted upward to the outer most graph. with self._outer_graph.as_default(): # pylint: disable=protected-access var = self._vscope.get_variable( vs._get_default_variable_store(), name, shape=shape, dtype=dtype,
tensorflow.python.ops.variable_scope._get_default_variable_store
447
import tensorflow as tf for grad, var in itertools.chain(*tower_gradvars): if grad is not None: all_grads.setdefault(var, []).append(grad) for var, grads in all_grads.items(): if len(grads) == 1: avg_grad = grads[0] else: avg_grad = tf.multiply(tf.add_n(grads), 1. / len(grads)) gradvars.append((avg_grad, var)) self.loss = tf.reduce_mean(tower_losses) tf.summary.scalar('loss', self.loss) # Create optimizer ops self.global_step = tf.Variable(0, trainable=False, name='global_step') opt = tf.train.RMSPropOptimizer(self.config['learning_rate']) with tf.control_dependencies(update_ops): self.trainer = opt.apply_gradients( gradvars, global_step=self.global_step) def _eval_graph(self, data): tower_metrics = self._gpu_tower(data, Mode.EVAL) with tf.device('/cpu:0'): self.metrics = {m: tf.reduce_mean(tf.stack([t[m] for t in tower_metrics])) for m in tower_metrics[0]} def _pred_graph(self, data): with tf.name_scope('pred'): with tf.device('/gpu:0'):
tensorflow.train.RMSPropOptimizer
448
import tensorflow as tf def _get_placeholder_shape(self, name): if name == "input_0": return self.a.shape if name == "input_1": return self.b.shape if name == "input_2": return self.c.shape def test_tensor_rearrange(): tensor_rearrange = TensorRearrange(seed=713) in_node_a = tensor_rearrange.get_placeholder("input_0") in_node_b = tensor_rearrange.get_placeholder("input_1") in_node_c = tensor_rearrange.get_placeholder("input_2") stitched = tf.dynamic_stitch([[1, 10], [[0, 7, 9], [5, 8, 3]], [[6], [4], [2]]], [in_node_a, in_node_b, in_node_c]) # should be 11,5,4 list_of_parts = tf.dynamic_partition(tf.transpose(stitched, perm=[1, 2, 0]), [[0, 1, 2, 3], [1, 0, 2, 3], [2, 3, 1, 0], [2, 1, 0, 3], [0, 1, 2, 3]], num_partitions=4) # after permute becomes 5,4,11, return all partitions 5,11 node_a = tf.div(list_of_parts[0], list_of_parts[1]) node_b = tf.divide(list_of_parts[2], list_of_parts[3]) trace_node = tf.trace(node_a) + node_b # there is a broadcast here out_node = tf.cast(tf.count_nonzero(trace_node), dtype=tf.float32) + tf.Variable(tf.random_normal(shape=(2, 3))) placeholders = [in_node_a, in_node_b, in_node_c] predictions = [out_node] # Run and persist
tensorflow.dynamic_stitch
449
import tensorflow as tf # products of decays isn't ideal numerically, in particular if any of the # decays are zero it results in NaNs. with tf.name_scope(name, values=[sequence, decay, initial_value]): if sequence_lengths is not None: # Zero out sequence and decay beyond sequence_lengths. with tf.control_dependencies( [tf.assert_equal(sequence.shape[0], decay.shape[0])]): mask = tf.sequence_mask(sequence_lengths, maxlen=sequence.shape[0], dtype=sequence.dtype) mask = tf.transpose(mask) # Adding trailing dimensions to mask to allow for broadcasting.
tensorflow.assert_equal
450
import tensorflow as tf logging.warn('The following variables in the checkpoint were not loaded:') for varname_not_loaded in not_loaded: logging.info('%s', varname_not_loaded) else: # just get model vars. for v in model_vars: mapping[v.op.name] = v return mapping def get_imagenet_vars_to_restore(imagenet_ckpt): """Returns dict of variables to restore from ImageNet-checkpoint.""" vars_to_restore_imagenet = {} ckpt_var_names = tf.contrib.framework.list_variables(imagenet_ckpt) ckpt_var_names = [name for (name, unused_shape) in ckpt_var_names] model_vars = tf.global_variables() for v in model_vars: if 'global_step' in v.op.name: continue mvname_noprefix = v.op.name.replace('depth_prediction/', '') mvname_noprefix = mvname_noprefix.replace('moving_mean', 'mu') mvname_noprefix = mvname_noprefix.replace('moving_variance', 'sigma') if mvname_noprefix in ckpt_var_names: vars_to_restore_imagenet[mvname_noprefix] = v else: logging.info('The following variable will not be restored from '
tensorflow.contrib.framework.list_variables
451
import tensorflow as tf 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),
tensorflow.FixedLenFeature
452
from tensorflow.contrib.opt.python.training import variable_clipping_optimizer def _setupDense(self, is_distributed, dtype): with self._maybeWithDevice("/job:ps" if is_distributed else None): var0 = variables.Variable([[0.0, 1.0], [2.0, 3.0]], dtype=dtype) var1 = variables.Variable([4.0, 5.0], dtype=dtype) with self._maybeWithDevice("/job:worker" if is_distributed else None): grads0 = constant_op.constant([[0.1, 0.1], [0.1, 0.1]], dtype=dtype) grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) sgd = gradient_descent.GradientDescentOptimizer(3.0) clip_opt = variable_clipping_optimizer.VariableClippingOptimizer( sgd, {var0: [1]}, 2.0) update_op = clip_opt.apply_gradients( list(zip([grads0, grads1], [var0, var1]))) variables.global_variables_initializer().run() return var0, var1, update_op def _assertDenseCorrect(self, var0, var1, update_op):
tensorflow.contrib.opt.python.training.variable_clipping_optimizer.VariableClippingOptimizer
453
import tensorflow as tf def __init__(self,name,input_dim,output_dim,k_t=2,k_h=3,k_w=3,d_t=2,d_h=1,d_w=1, stddev=0.02, data_format='NDHWC') : with tf.variable_scope(name) : assert(data_format == 'NDHWC') self.w = tf.get_variable('w', [k_t, 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)) self.strides = [1,1,1] self.dilates = [d_t, d_h, d_w] def __call__(self,input_var,name=None) : k_t,k_h,k_w,_,_ = self.w.get_shape().as_list() _t = tf.pad(input_var, [[0,0],[0,0],[k_h//2,k_h//2],[k_w//2,k_w//2],[0,0]], "SYMMETRIC") return tf.nn.bias_add( tf.nn.convolution(_t, self.w, strides=self.strides, dilation_rate=self.dilates, padding='VALID'), self.b,name=name) class Linear(object) : def __init__(self,name,input_dim,output_dim,stddev=0.02) : with tf.variable_scope(name) : self.w = tf.get_variable('w',[input_dim, output_dim], initializer=tf.random_normal_initializer(stddev=stddev)) self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(0.0))
tensorflow.nn.convolution
454
import tensorflow as tf def testSharded(self): save_dir = os.path.join(self.get_temp_dir(), "max_to_keep_sharded") try: gfile.DeleteRecursively(save_dir) except OSError: pass # Ignore gfile.MakeDirs(save_dir) with tf.Session( target="", config=tf.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): v0 = tf.Variable(111, name="v0") with sess.graph.device("/cpu:1"): v1 = tf.Variable(222, name="v1") save = tf.train.Saver({"v0": v0, "v1": v1}, sharded=True, max_to_keep=2) tf.initialize_all_variables().run() self.assertEqual([], save.last_checkpoints) s1 = save.save(sess, os.path.join(save_dir, "s1"))
tensorflow.ConfigProto
455
import tensorflow as tf tf_sparse_demo = TFDemo(vocabulary_size=args.max_vocabulary_size_per_gpu * args.gpu_num, embedding_vec_size=args.embedding_vec_size, combiner=args.combiner, slot_num=args.slot_num, max_nnz=args.max_nnz, use_hashtable=args.use_hashtable, num_of_dense_layers=0) optimizer = utils.get_dense_optimizer(args.optimizer)(learning_rate=0.1) loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True) def _train_step(inputs, labels, training): logit, embedding_vector = tf_sparse_demo(inputs, training=training) loss = loss_fn(labels, logit) grads = tf.gradients(loss, tf_sparse_demo.trainable_variables, colocate_gradients_with_ops=True, unconnected_gradients=tf.UnconnectedGradients.NONE) train_op = optimizer.apply_gradients(zip(grads, tf_sparse_demo.trainable_variables)) with tf.control_dependencies([train_op]): loss = tf.identity(loss)
tensorflow.keras.losses.BinaryCrossentropy
456
from tensorflow.python.ops import math_ops n = math_ops.cast(global_step, dtypes.float32) decay = math_ops.minimum(decay, n / (n + 1.)) # update averages mean = moving_average("mean", log_norm, decay) sq_mean = moving_average("sq_mean", math_ops.square(log_norm), decay) variance = sq_mean - math_ops.square(mean) std = math_ops.sqrt(math_ops.maximum(epsilon, variance)) max_norms = math_ops.exp(mean + std_factor * std) return max_norms, mean def adaptive_clipping_fn(std_factor=2., decay=0.95, static_max_norm=None, global_step=None, report_summary=False,
tensorflow.python.ops.math_ops.exp
457
import tensorflow.contrib.slim as slim bboxes = tf.stop_gradient(tf.concat([y1, x1, y2, x2], axis=1)) # 'roi_pooling_size', 7 pre_pool_size = cfg.FLAGS.roi_pooling_size * 2 # 把rois对于的特征图上的部分crop出来,然后resize打破14*14的大小 crops = tf.image.crop_and_resize(bottom, bboxes, tf.to_int32(batch_ids), [pre_pool_size, pre_pool_size], name="crops") return slim.max_pool2d(crops, [2, 2], padding='SAME') def _dropout_layer(self, bottom, name, ratio=0.5): return tf.nn.dropout(bottom, ratio, name=name) def _anchor_target_layer(self, rpn_cls_score, name):
tensorflow.contrib.slim.max_pool2d
458
from tensorflow.contrib.learn.python.learn.datasets import base train_path = os.path.join(module_path, 'data', 'text_train.csv') test_path = os.path.join(module_path, 'data', 'text_test.csv') train = base.load_csv_without_header( train_path, target_dtype=np.int32, features_dtype=np.str, target_column=0) test = base.load_csv_without_header(
tensorflow.contrib.learn.python.learn.datasets.base.load_csv_without_header
459
import tensorflow as tf img_h = img_h_batch[start:end] img_w = img_w_batch[start:end] inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_q, num_objects, img_h, img_w]) tower_grads = [] biases_regularizer = tf.no_regularizer weights_regularizer = tf.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY) with tf.variable_scope(tf.get_variable_scope()): for i in range(num_gpu): with tf.device('/gpu:%d' % i): with tf.name_scope('tower_%d' % i): with slim.arg_scope( [slim.model_variable, slim.variable], device='/device:CPU:0'): with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane, slim.conv2d_transpose, slim.separable_conv2d, slim.fully_connected], weights_regularizer=weights_regularizer, biases_regularizer=biases_regularizer, biases_initializer=tf.constant_initializer(0.0)): gtboxes_and_label_h, gtboxes_and_label_q = tf.py_func(self.get_gtboxes_and_label,
tensorflow.device
460
import tensorflow as tf # pylint: disable=no-value-for-parameter,unexpected-keyword-arg """LSTM layers.""" import tensorflow as tf from deepr.layers import base @base.layer(n_in=2, n_out=3) def LSTM(tensors, num_units: int, bidirectional: bool = False, **kwargs): """LSTM layer.""" words, nwords = tensors t = tf.transpose(words, perm=[1, 0, 2]) lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs) outputs_fw, (hidden_fw, output_fw) = lstm_cell_fw(t, dtype=tf.float32, sequence_length=nwords) if bidirectional: lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs) lstm_cell_bw = tf.contrib.rnn.TimeReversedFusedRNN(lstm_cell_bw) outputs_bw, (hidden_bw, output_bw) = lstm_cell_bw(t, dtype=tf.float32, sequence_length=nwords) outputs = tf.concat([outputs_fw, outputs_bw], axis=-1) hidden = tf.concat([hidden_fw, hidden_bw], axis=-1) output = tf.concat([output_fw, output_bw], axis=-1) else: outputs = outputs_fw hidden = hidden_fw
tensorflow.contrib.rnn.LSTMBlockFusedCell
461
import tensorflow as tf grl = tf.reshape(grl, (-1, samples.get_shape().as_list()[1])) grl = fc(grl, 100, True, None, activation=relu, name='fc1') logits = fc(grl, 1, True, None, activation=None, name='fc2') domain_predictions = tf.sigmoid(logits) domain_loss = tf.losses.log_loss(domain_selection_mask, domain_predictions, weights=weight) domain_accuracy = util.accuracy_tf(domain_selection_mask, tf.round(domain_predictions)) assert_op = tf.Assert(tf.is_finite(domain_loss), [domain_loss]) with tf.control_dependencies([assert_op]): tag_loss = 'losses/domain_loss'
tensorflow.losses.log_loss
462
import tensorflow as tf train_steps_per_epoch = int( math.ceil(hparams.num_train_images / float(hparams.train_batch_size))) eval_steps = hparams.num_eval_images // hparams.eval_batch_size eval_batch_size = (None if mode == 'train' else hparams.eval_batch_size) model = model_lib.AmoebaNetEstimatorModel(hparams, model_dir) if hparams.use_tpu: run_config = build_run_config() image_classifier = tf.contrib.tpu.TPUEstimator( model_fn=model.model_fn, use_tpu=True, config=run_config, params=estimator_parmas, predict_batch_size=eval_batch_size, train_batch_size=hparams.train_batch_size, eval_batch_size=eval_batch_size, export_to_tpu=FLAGS.export_to_tpu, experimental_exported_model_uses_all_cores=FLAGS
tensorflow.contrib.tpu.TPUEstimator
463
import tensorflow as tf y_true: tensor, observations. y_pred: tensor, output of network. Returns: loss value, means negative log-likelihood. """ logL = 0 # pre-calculate cumsum cumsum_y_pred = tf.cumsum(y_pred) hazard_ratio = tf.exp(y_pred) cumsum_hazard_ratio = tf.cumsum(hazard_ratio) if self.train_data['ties'] == 'noties': log_risk = tf.log(cumsum_hazard_ratio) likelihood = y_pred - log_risk # dimension for E: np.array -> [None, 1] uncensored_likelihood = likelihood * y_true
tensorflow.cumsum
464
import tensorflow as tf types = {movielens.USER_COLUMN: rconst.USER_DTYPE, movielens.ITEM_COLUMN: rconst.ITEM_DTYPE} shapes = {movielens.USER_COLUMN: tf.TensorShape([batch_size]), movielens.ITEM_COLUMN: tf.TensorShape([batch_size])}
tensorflow.TensorShape
465
import tensorflow as tf with self._write_locks[index % rconst.NUM_FILE_SHARDS]: self._writers[index % rconst.NUM_FILE_SHARDS].write(example_bytes) else: if self._is_training: mask_start_index = data.pop(rconst.MASK_START_INDEX) batch_size = data[movielens.ITEM_COLUMN].shape[0] data[rconst.VALID_POINT_MASK] = np.less(np.arange(batch_size), mask_start_index) data = (data, data.pop("labels")) self._result_queue.put(data) def start_construction(self): if self._stream_files: tf.gfile.MakeDirs(self.current_data_root) template = os.path.join(self.current_data_root, rconst.SHARD_TEMPLATE) self._writers = [tf.io.TFRecordWriter(template.format(i)) for i in range(rconst.NUM_FILE_SHARDS)] def end_construction(self): if self._stream_files: [writer.close() for writer in self._writers] self._writers = [] self._result_queue.put(self.current_data_root) self._epochs_completed += 1 def data_generator(self, epochs_between_evals):
tensorflow.gfile.MakeDirs
466
import tensorflow as tf self.loss = tf.squared_difference(self.value_estimate, self.target) self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) self.train_op = self.optimizer.minimize( self.loss, global_step=tf.contrib.framework.get_global_step()) def predict(self, state, sess=None):
tensorflow.contrib.framework.get_global_step
467
import tensorflow as tf assert (bsize[2] - ksize[1]) % strides[2] == 0, ERR_MSG_DIV.format( strides[2], bsize[2], ksize[1]) assert strides[0] == strides[3] == 1, ERR_MSG_DIM.format(strides) bstrides = _calc_block_strides(bsize, ksize, strides) # Pad mask. mask_ = tf.expand_dims(mask, 3) mask_ = _pad_input(mask_, ksize, strides, padding, bsize=bsize, bstrides=bstrides) mask_ = tf.nn.max_pool(mask_, bsize, bstrides, 'VALID') # Blocks are always valid conv. mask_ = tf.squeeze(mask_, [3]) indices = tf.where(tf.greater(mask_, tol)) indices = tf.cast(indices, tf.int32) return indices def convert_mask_to_block_indices(mask, bsize, ksize, strides, padding, tol): """
tensorflow.nn.max_pool
468
import tensorflow as tf return f features = collections.OrderedDict() features["input_ids"] = create_int_feature(feature.input_ids) features["input_mask"] = create_int_feature(feature.input_mask) features["segment_ids"] = create_int_feature(feature.segment_ids) features["label_ids"] = create_int_feature([feature.label_id]) features["is_real_example"] = create_int_feature( [int(feature.is_real_example)]) tf_example = tf.train.Example(features=tf.train.Features(feature=features)) return tf_example def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" name_to_features = {
tensorflow.train.Features
469
import tensorflow as tf """ metric_names = list(monitor_dict.keys()) def host_call_fn(global_step, *args): """actual host call function.""" step = global_step[0] with tf.contrib.summary.create_file_writer( logdir=model_dir, filename_suffix=".host_call").as_default(): with tf.contrib.summary.always_record_summaries(): for i, name in enumerate(metric_names): if reduce_fn is None: scalar = args[i][0] else:
tensorflow.contrib.summary.create_file_writer
470
import tensorflow as tf [t2ind, t2val, t2sh] = sp.createRandomSparseTensor(rho_filter, filter_in_sizes) s2 = tf.SparseTensor(indices=t2ind, values=t2val, dense_shape=t2sh) d2 = sp.sparse_to_dense(t2ind, t2val, t2sh) print("strides: \n", strides) print("input shape", tensor_in_sizes) print("filter shape", filter_in_sizes) config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.7 with tf.device("/gpu:0"): convd = sc_module.direct_sparse_data_conversion(t1ind, t1val, t1sh) convf = sc_module.direct_sparse_filter_conversion(t2ind, t2val, t2sh, t1sh) with tf.Session(config=config) as sess: pd = sess.run(convd) pf = sess.run(convf) tf.reset_default_graph() ts = 0 with tf.device("/gpu:0"): approx_scskconv = sc_module.direct_sparse_conv_kd(pd.out_indices, pd.out_values, pd.out_shape, pd.out_block_channel_mapping, pf.out_indices, pf.out_values, pf.out_shape, pf.out_channel_mapping, bias, strides, padding, out_entry_count, dim, max_density, filter_type); with tf.Session(config=config) as sess: t6 = time.time() sv3 = sess.run(approx_scskconv) t5 = time.time() for i in range(0, num_trials):
tensorflow.Session
471
import tensorflow.contrib.layers as layers with tf.variable_scope(scope, reuse=reuse): out = img_in 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)
tensorflow.contrib.layers.convolution2d
472
from tensorflow.python.layers import pooling as pooling_layers mode='VALID', input_layer=None, num_channels_in=None): """Construct a max pooling layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = num_channels_in name = 'mpool' + str(self.counts['mpool']) self.counts['mpool'] += 1 pool = pooling_layers.max_pooling2d( input_layer, [k_height, k_width], [d_height, d_width], padding=mode, data_format=self.channel_pos, name=name) self.top_layer = pool return pool def apool(self, k_height,
tensorflow.python.layers.pooling.max_pooling2d
473
import tensorflow as tf if monitorSession: # MonitoredSession # this will restore all the variables from the latest checkpoint if it exists self._fix_checkpoint_abs_to_rel(self._checkpoint_dir) # need to ensure checkpoint has relative path saved chiefsess_creator = tf.train.ChiefSessionCreator(config=sess_config, checkpoint_dir=self._checkpoint_dir) if self._restore_chkptfile is not None: self._network.init_saver() # this is restoring variables self.sess = tf.train.MonitoredSession(session_creator=chiefsess_creator, hooks=self.hooks) # Restore from some checkpoint if self._restore_chkptfile is not None: raw_sess = self.get_raw_session() if raw_sess.run(self.global_step) == 0: self._network.restore(raw_sess, self._restore_chkptfile) else: self.sess = tf.Session(config=sess_config) #all_variables = tf.get_collection_ref(tf.GraphKeys.GLOBAL_VARIABLES) #self.sess.run(tf.variables_initializer(all_variables))
tensorflow.train.MonitoredSession
474
import tensorflow as tf x=x, h2=l1_h2, layer='h1', layer_idx=0) # Intermediate FF if self.batch_norm: with tf.variable_scope( 'l1_h2_bn', reuse=self.scope_reuse) as scope: l1_h2 = tf.contrib.layers.batch_norm( inputs=l1_h2, scale=True, center=True, fused=True, renorm=False, param_initializers=self.param_initializer, updates_collections=None, scope=scope, reuse=self.reuse,
tensorflow.contrib.layers.batch_norm
475
import tensorflow as tf def testTiedRNNSeq2Seq(self): with self.test_session() as sess: with tf.variable_scope("root", initializer=tf.constant_initializer(0.5)): inp = [tf.constant(0.5, shape=[2, 2])] * 2 dec_inp = [tf.constant(0.4, shape=[2, 2])] * 3 cell = tf.nn.rnn_cell.OutputProjectionWrapper( tf.nn.rnn_cell.GRUCell(2), 4) dec, mem = tf.nn.seq2seq.tied_rnn_seq2seq(inp, dec_inp, cell) 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(1, len(res))
tensorflow.nn.seq2seq.tied_rnn_seq2seq
476
import tensorflow as tf feed_dict={net.data: blobs['data'], net.im_info: blobs['im_info'], net.keep_prob: 1.0} else: feed_dict={net.data: blobs['data'], net.rois: blobs['rois'], net.keep_prob: 1.0} run_options = None run_metadata = None if cfg.TEST.DEBUG_TIMELINE: run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() #theta_tensor = tf.get_default_graph().get_tensor_by_name('spt_trans_theta') cls_score, cls_prob, bbox_pred, rois = sess.run([net.get_output('cls_score'), net.get_output('cls_prob'), net.get_output('bbox_pred'), net.get_output('rois')], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata)
tensorflow.RunMetadata
477
import tensorflow as tf total_loss = tf.reduce_sum(lm_loss * tgt_mask) / tf.reduce_sum(tgt_mask) monitor_dict["total_loss"] = total_loss return total_loss, new_mems, monitor_dict def get_loss(FLAGS, features, labels, mems, is_training): """Pretraining loss with two-stream attention Transformer-XL.""" if FLAGS.use_bfloat16: with tf.tpu.bfloat16_scope(): return two_stream_loss(FLAGS, features, labels, mems, is_training) else: return two_stream_loss(FLAGS, features, labels, mems, is_training) def get_classification_loss( FLAGS, features, n_class, is_training): """Loss for downstream classification tasks."""
tensorflow.tpu.bfloat16_scope
478
from tensorflow.python.ops import common_shapes @ops.RegisterShape("MaxPoolWithArgmax") def _MaxPoolWithArgMaxShape(op): """Shape function for MaxPoolWithArgmax op.""" return common_shapes.max_pool_shape(op) * 2 @ops.RegisterShape("AvgPoolGrad") def _AvgPoolGradShape(op):
tensorflow.python.ops.common_shapes.max_pool_shape
479
from tensorflow.python.ops import logging_ops self._add_hidden_layer_summary(net, "hiddenlayer_%d" % layer_id) logit = layers.legacy_fully_connected( net, self._num_label_columns(), weight_collections=[self._dnn_weight_collection], bias_collections=[self._dnn_weight_collection], name="dnn_logit") self._add_hidden_layer_summary(logit, "dnn_logit") return logit def _add_hidden_layer_summary(self, value, tag): # TODO(zakaria): Move this code to tf.learn and add test. logging_ops.scalar_summary("%s:fraction_of_zero_values" % tag, nn.zero_fraction(value)) logging_ops.histogram_summary("%s:activation" % tag, value) def _linear_logits(self, features): logits, _, _ = layers.weighted_sum_from_feature_columns( columns_to_tensors=features, feature_columns=self._get_linear_feature_columns(), num_outputs=self._num_label_columns(), weight_collections=[self._linear_weight_collection], name="linear") return logits def _get_feature_dict(self, features): if isinstance(features, dict): return features
tensorflow.python.ops.logging_ops.histogram_summary
480
import tensorflow as tf batch_size = tf.shape(targets)[0] time_steps = tf.shape(targets)[1] logits_ = tf.reshape(logits, tf.stack([time_steps * batch_size, logits.get_shape()[2].value])) targets_ = tf.reshape(targets, tf.stack([time_steps * batch_size])) crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_, labels=targets_) crossent = tf.reshape(crossent, tf.stack([batch_size, time_steps])) if rewards is not None: crossent *= tf.stop_gradient(rewards) log_perp = tf.reduce_sum(crossent * weights, axis=1)
tensorflow.stack
481
from tensorflow.python.platform import tf_logging as logging input_feature_key=self._input_feature_key, use_deprecated_input_fn=self._use_deprecated_input_fn) except RuntimeError: # Currently we are not syncronized with saving checkpoints, which leads to # runtime errors when we are calling export on the same global step. # Exports depend on saved checkpoints for constructing the graph and # getting the global step from the graph instance saved in the checkpoint. # If the checkpoint is stale with respect to current step, the global step # is taken to be the last saved checkpoint's global step and exporter # doesn't export the same checkpoint again with the following error. logging.info("Skipping exporting because the existing checkpoint has " "already been exported. " "Consider exporting less frequently.") def end(self, session=None): super(ExportMonitor, self).end(session=session) latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir) if latest_path is None: logging.info("Skipping export at the end since model has not been saved " "yet.")
tensorflow.python.platform.tf_logging.info
482
import tensorflow as tf tf.global_variables(), sharded=True, max_to_keep=10, keep_checkpoint_every_n_hours=2, defer_build=False, save_relative_paths=True) tf.add_to_collection(tf.GraphKeys.SAVERS, saver) saver_listener = mtf.MtfCheckpointSaverListener(lowering) saver_hook = tf.train.CheckpointSaverHook( hparams.model_dir, save_steps=1000, saver=saver, listeners=[saver_listener]) # EVAL mode if mode == tf.estimator.ModeKeys.EVAL:
tensorflow.train.CheckpointSaverHook
483
import tensorflow as tf tf.logging.info("label: %s (id = %d)" % (example.label, label_id)) feature = InputFeatures( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id, is_real_example=True) return feature def file_based_convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, output_file): """Convert a set of `InputExample`s to a TFRecord file.""" writer = tf.python_io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.logging.info("Writing example %d of %d" % (ex_index, len(examples))) feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer) def create_int_feature(values): f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return f features = collections.OrderedDict() features["input_ids"] = create_int_feature(feature.input_ids)
tensorflow.python_io.TFRecordWriter
484
import tensorflow as tf # Setup default values. if not image_pyramid: image_pyramid = [1.0] #if model_options.crop_size is None and model_options.add_image_level_feature: # raise ValueError( # 'Crop size must be specified for using image-level feature.') if model_options.model_variant == 'mobilenet_v2': if (model_options.atrous_rates is not None or model_options.decoder_output_stride is not None): # Output a warning and users should make sure if the setting is desired. tf.logging.warning('Our provided mobilenet_v2 checkpoint does not ' 'include ASPP and decoder modules.') crop_height = ( model_options.crop_size[0] if model_options.crop_size else tf.shape(images)[1]) crop_width = ( model_options.crop_size[1] if model_options.crop_size else tf.shape(images)[2]) # Compute the height, width for the output logits.
tensorflow.logging.warning
485
import tensorflow as tf " batch_shape=()" " event_shape=()" " dtype=float16>") chi2 = tfd.Chi2(df=np.float32([1., 2.]), name="silly") self.assertEqual( repr(chi2), "<tfp.distributions.Chi2" " 'silly/'" # What a silly name that is! " batch_shape=(2,)" " event_shape=()" " dtype=float32>") # There's no notion of partially known shapes in eager mode, so exit # early. if tf.executing_eagerly(): return exp = tfd.Exponential(rate=tf.placeholder_with_default( input=1., shape=None)) self.assertEqual( repr(exp), "<tfp.distributions.Exponential" " 'Exponential/'" " batch_shape=<unknown>" " event_shape=()" " dtype=float32>") def testReprWorksCorrectlyMultivariate(self): mvn_static = tfd.MultivariateNormalDiag(
tensorflow.executing_eagerly
486
import tensorflow as tf states = self.states dxt_list = tf.gradients(self.error, states) #dxt_list[0] = tf.Print(dxt_list[0], [dxt_list[0]], "dxt 0: ") test = tf.gradients(states[0], states[-1]) dxt = tf.stack(dxt_list) xt = tf.stack(states) 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)
tensorflow.abs
487
from tensorflow.contrib.metrics.python.ops import set_ops return sparse_ops.sparse_retain( ids, math_ops.equal(ids.values, selected_id)) # TODO(ptucker): Make this more efficient, maybe add a sparse version of # tf.equal and tf.reduce_any? # Shape of filled IDs is the same as `ids` with the last dim collapsed to 1. ids_shape = array_ops.shape(ids, out_type=dtypes.int64) ids_last_dim = array_ops.size(ids_shape) - 1 filled_selected_id_shape = math_ops.reduced_shape( ids_shape, array_ops.reshape(ids_last_dim, [1])) # Intersect `ids` with the selected ID. filled_selected_id = array_ops.fill( filled_selected_id_shape, math_ops.to_int64(selected_id)) result = set_ops.set_intersection(filled_selected_id, ids) return ops.SparseTensor( indices=result.indices, values=result.values, shape=ids_shape) def _maybe_select_class_id(labels, predictions_idx, selected_id=None): """If class ID is specified, filter all other classes. Args: labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels], where N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. predictions_idx: `int64` `Tensor` of class IDs, with shape [D1, ... DN, k]
tensorflow.contrib.metrics.python.ops.set_ops.set_intersection
488
from tensorflow.python.framework import tensor_shape """Common shape function for binary operators that broadcast their inputs.""" shape_x = op.inputs[0].get_shape() shape_y = op.inputs[1].get_shape() if shape_x.ndims is None or shape_y.ndims is None: return [tensor_shape.unknown_shape()] # To compute the broadcasted dimensions, we zip together shape_x and shape_y, # and pad with 1 to make them the same length. broadcasted_dims = reversed(list(six.moves.zip_longest( reversed(shape_x.dims), reversed(shape_y.dims), fillvalue=tensor_shape.Dimension(1)))) # Next we combine the dimensions according to the numpy broadcasting rules. # http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html return_dims = [] for (dim_x, dim_y) in broadcasted_dims: if dim_x.value is None or dim_y.value is None: # One or both dimensions is unknown. If either dimension is greater than # 1, we assume that the program is correct, and the other dimension will # be broadcast to match it. # TODO(mrry): If we eliminate the shape checks in C++, we must still # assert that the unknown dim is either 1 or the same as the known dim.
tensorflow.python.framework.tensor_shape.Dimension
489
import tensorflow as tf def benchmark_graph(self): """Benchmark Graph performance.""" hparams = get_default_hparams() tf.enable_resource_variables() for sample_size in [10, 25, 50, 100, 200]: hparams.n_samples = sample_size tf.reset_default_graph() with tf.Graph().as_default():
tensorflow.enable_resource_variables
490
from tensorflow.python.ops import gen_math_ops Returns: A `Tensor`. """ with ops.op_scope([x], name, "Pow") as name: return gen_math_ops._pow(x, y, name=name) def complex(real, imag, name=None): """Converts two real numbers to a complex number.
tensorflow.python.ops.gen_math_ops._pow
491
import tensorflow as tf raise ValueError("Expected hparams.coupling to be in %s, got %s" % (exp_coupling, self.hparams.coupling)) if self.is_training: init_features = self.create_init_batch(features) init_op = self.objective_tower(init_features, init=True) init_op = tf.Print( init_op, [init_op], message="Triggering data-dependent init.", first_n=20) tf.add_to_collection("glow_init_op", init_op) train_op = self.objective_tower(features, init=False)
tensorflow.Print
492
import tensorflow as tf def create_variable_for_generator(name, batch_size): return tf.get_variable('learnable_dlatents', shape=(batch_size, 18, 512), dtype='float32', initializer=tf.initializers.random_normal()) class Generator:
tensorflow.initializers.random_normal
493
import tensorflow as tf """Returns the loss function.""" loss = tf.losses.softmax_cross_entropy(
tensorflow.losses.softmax_cross_entropy
494
import tensorflow as tf hooks.append(tf.data.experimental.CheckpointInputPipelineHook(estimator)) train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps, hooks=hooks) eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn, steps=FLAGS.max_eval_steps) tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
tensorflow.estimator.EvalSpec
495
import tensorflow as tf marginalized_gold_scores = tf.reduce_logsumexp(gold_scores, [1]) # [k] log_norm = tf.reduce_logsumexp(antecedent_scores, [1]) # [k]
tensorflow.reduce_logsumexp
496
import tensorflow as tf tf.nn.convolution(_t, self.w, strides=self.strides, dilation_rate=self.dilates, padding='VALID'), self.b,name=name) class Linear(object) : def __init__(self,name,input_dim,output_dim,stddev=0.02) : with tf.variable_scope(name) : self.w = tf.get_variable('w',[input_dim, output_dim], initializer=tf.random_normal_initializer(stddev=stddev)) self.b = tf.get_variable('b',[output_dim], initializer=tf.constant_initializer(0.0)) def __call__(self,input_var,name=None,w=None,b=None,**kwargs) : w = w if w is not None else self.w b = b if b is not None else self.b if( input_var.shape.ndims > 2 ) :
tensorflow.random_normal_initializer
497
import tensorflow as tf tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 run_config = tf.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps, tpu_config=tf.contrib.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=is_per_host)) train_examples = None num_train_steps = None num_warmup_steps = None if FLAGS.do_train: train_examples = processor.get_train_examples(FLAGS.data_dir) num_train_steps = int( len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
tensorflow.contrib.tpu.TPUConfig
498
import tensorflow as tf }) return model_outputs if params['use_bfloat16']: with tf.contrib.tpu.bfloat16_scope(): model_outputs = _model_outputs() def cast_outputs_to_float(d): for k, v in sorted(six.iteritems(d)):
tensorflow.contrib.tpu.bfloat16_scope
499