seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf x = tf.reshape(tf_utils.get_values(x), [-1]) if categorical: x_dtype = x.dtype x = x if x_dtype == tf.string else tf.strings.as_string(x) elements, counts = count_per_key(x) if x_dtype != elements.dtype: elements = tf.strings.to_number(elements, tf.int64) return counts, elements if boundaries is None: boundaries = tf.range(11, dtype=tf.float32) / 10.0 elif isinstance(boundaries, int) or (isinstance(boundaries, tf.Tensor) and boundaries.get_shape().ndims == 0): min_value, max_value = _min_and_max(x, True) boundaries = tf.linspace( tf.cast(min_value, tf.float32), tf.cast(max_value, tf.float32), tf.cast(boundaries, tf.int64)) # Shift the boundaries slightly to account for floating point errors, # and due to the fact that the rightmost boundary is essentially ignored. boundaries = tf.expand_dims(tf.cast(boundaries, tf.float32), 0) - 0.0001 bucket_indices = tf_utils.assign_buckets( tf.cast(x, tf.float32), remove_leftmost_boundary(boundaries)) bucket_vocab, counts = count_per_key(tf.strings.as_string(bucket_indices)) counts = tf_utils.reorder_histogram(bucket_vocab, counts, tf.size(boundaries) - 1) return counts, boundaries
tensorflow.cast
1,200
import tensorflow as tf x_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Input') x_input_l = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Labeled_Input') y_input = tf.placeholder(dtype=tf.float32, shape=[batch_size, n_labels], name='Labels') x_target = tf.placeholder(dtype=tf.float32, shape=[batch_size, input_dim], name='Target')
tensorflow.placeholder
1,201
import tensorflow as tf if greater than 0 then smooth the labels. weight: scale the loss by this factor. name: Optional scope/name for op_scope. Returns: A tensor with the cross entropy loss. """ logits.get_shape().assert_is_compatible_with(labels.get_shape()) with tf.name_scope(name): num_classes = labels.get_shape()[-1].value labels = tf.cast(labels, logits.dtype) if label_smoothing > 0: smooth_positives = 1.0 - label_smoothing smooth_negatives = label_smoothing / num_classes labels = labels * smooth_positives + smooth_negatives cross_entropy = tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=labels, name='xentropy') weight = tf.convert_to_tensor(weight, dtype=logits.dtype.base_dtype, name='loss_weight') loss = tf.multiply(weight, tf.reduce_mean(cross_entropy), name='value') return loss def l1_l2_regularizer(var, weight_l1=1.0, weight_l2=1.0, name='l1_l2_regularizer'): """Define a L2Loss, useful for regularize, i.e. weight decay. Args: var: tensor to regularize. weight_l1: an optional weight to modulate the l1 loss. weight_l2: an optional weight to modulate the l2 loss. name: Optional scope/name for op_scope.
tensorflow.nn.softmax_cross_entropy_with_logits
1,202
import tensorflow as tf 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)
tensorflow.cast
1,203
import tensorflow as tf """Returns the learning phase flag. The learning phase flag is a bool tensor (0 = test, 1 = train) to be passed as input to any Keras function that uses a different behavior at train time and test time. """ graph = tf.get_default_graph() if graph not in _GRAPH_LEARNING_PHASES: phase = tf.placeholder(dtype='bool', name='keras_learning_phase') _GRAPH_LEARNING_PHASES[graph] = phase return _GRAPH_LEARNING_PHASES[graph] def in_train_phase(x, alt): """Selects `x` in train phase, and `alt` otherwise. Note that `alt` should have the *same shape* as `x`.
tensorflow.placeholder
1,204
import tensorflow as tf self._xent = tf.nn.softmax_cross_entropy_with_logits(logits, self.y) self.cost = tf.reduce_mean(self.example_weights * self._xent)
tensorflow.reduce_mean
1,205
import tensorflow as tf # If features are not used, replace feature matrix by identity matrix if not FLAGS.features: features = sp.identity(adj.shape[0]) # Preprocessing on node features features = sparse_to_tuple(features) num_features = features[2][1] features_nonzero = features[1].shape[0] # Define placeholders placeholders = { 'features': tf.sparse_placeholder(tf.float32), 'adj': tf.sparse_placeholder(tf.float32), 'adj_orig': tf.sparse_placeholder(tf.float32), 'dropout': tf.placeholder_with_default(0., shape = ()) } # Create model model = None if model_name == 'gcn_ae': # Standard Graph Autoencoder model = GCNModelAE(placeholders, num_features, features_nonzero) elif model_name == 'gcn_vae': # Standard Graph Variational Autoencoder model = GCNModelVAE(placeholders, num_features, num_nodes, features_nonzero) elif model_name == 'linear_ae':
tensorflow.placeholder_with_default
1,206
import tensorflow as tf assert strides[2] == strides[3], STRIDES_ERR_MSG x = _conv( 'conv1', x, ksize_list[0], _stride_arr(strides[2], data_format), padding, data_format=data_format) with tf.variable_scope('sub2'): x = _batch_norm('bn2', x, is_training, data_format) x = _relu('relu2', x) x = _conv( 'conv2', x, ksize_list[1], _stride_arr(1, data_format), padding,
tensorflow.variable_scope
1,207
import tensorflow as tf per_example_loss=tf.losses.sigmoid_cross_entropy(multi_class_labels=labels, logits=logits,reduction=Reduction.NONE) per_example_loss=tf.reduce_sum(per_example_loss,axis=-1) loss = tf.reduce_mean(per_example_loss,name='train_loss')
tensorflow.reduce_sum
1,208
import tensorflow as tf coverage = tf.zeros_like(attn_dists[0]) # shape (batch_size, attn_length). Initial coverage is zero. covlosses = [] # Coverage loss per decoder timestep. Will be list length max_dec_steps containing shape (batch_size). for a in attn_dists: covloss = tf.reduce_sum(tf.minimum(a, coverage), [1]) # calculate the coverage loss for this step covlosses.append(covloss) coverage += a # update the coverage vector
tensorflow.minimum
1,209
import tensorflow as tf self.dataset = datasets.FlowersData(FLAGS.data_dir) else: raise ValueError('Unknown dataset. Must be one of imagenet or flowers.') self.local_parameter_device_flag = FLAGS.local_parameter_device if self.job_name: self.task_index = FLAGS.task_index self.cluster = tf.train.ClusterSpec({'ps': self.ps_hosts, 'worker': self.worker_hosts}) self.server = None if not self.server: self.server = tf.train.Server(self.cluster, job_name=self.job_name, task_index=self.task_index,
tensorflow.train.ClusterSpec
1,210
import tensorflow as tf
tensorflow.constant_initializer
1,211
import tensorflow as tf 'label':tf.FixedLenFeature([], tf.int64), 'img_raw' : tf.FixedLenFeature([], tf.string), }) image=tf.decode_raw(features['img_raw'],tf.uint8) label=tf.cast(features['label'],tf.int32) image=tf.reshape(image,[4096,1]) return image,label def get_batch(image,label,batch_size,crop_size): #print(image.shape)
tensorflow.reshape
1,212
import tensorflow as tf v = variable_scope.get_variable("v", [options.attention_vec_size]) v = tf.expand_dims(tf.expand_dims(v, axis=0), axis=0) w_c = None 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) word_t_representation = self.embedding_lookup(word_t) (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_representation, encoder_states, encoder_features,
tensorflow.expand_dims
1,213
import tensorflow as tf predict_drop_remainder = True if FLAGS.use_tpu else False predict_input_fn = file_based_input_fn_builder( input_file=predict_file, seq_length=FLAGS.max_seq_length, is_training=False, drop_remainder=predict_drop_remainder) result = estimator.predict(input_fn=predict_input_fn) output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv") with tf.gfile.GFile(output_predict_file, "w") as writer: num_written_lines = 0 tf.logging.info("***** Predict results *****") for (i, prediction) in enumerate(result): probabilities = prediction["probabilities"] if i >= num_actual_predict_examples: break output_line = "\t".join( str(class_probability) for class_probability in probabilities) + "\n"
tensorflow.gfile.GFile
1,214
import tensorflow as tf elif mode == tf.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, label_ids, logits, is_real_example): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions, weights=is_real_example) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example) return { "eval_accuracy": accuracy, "eval_loss": loss, }
tensorflow.metrics.mean
1,215
import tensorflow as tf return loss def log_loss_tf(predictions, labels, eps=1e-7, weights=1.0, name='log_loss'): """Define a log loss. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network . labels: 2D or array tensor, [batch_size, num_classes] ground truth labels or target labels. eps: a constant to set upper or lower limit for labels, smoothening factor name: Optional scope/name for op_scope. Returns: A tensor with the log loss. """ with tf.name_scope(name): predictions.get_shape().assert_is_compatible_with(labels.get_shape()) predictions = tf.to_float(predictions) labels = tf.to_float(labels) losses = -tf.multiply(labels, tf.log(predictions + eps)) - tf.multiply( (1 - labels), tf.log(1 - predictions + eps)) return tf.losses.compute_weighted_loss(losses, weights) def kappa_loss(predictions, labels, y_pow=1, eps=1e-15, num_ratings=5, batch_size=32, name='kappa'): """Define a kappa loss, Its a continuous differentiable approximation of discrete kappa loss. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network .
tensorflow.name_scope
1,216
from tensorflow.python.ops import array_ops batch_shape = array_ops.slice(s, (1,), (self.batch_ndims,)) # Since sample_dims=1 and is left-most, we add 1 to the number of # batch_ndims to get the event start dim. event_start = array_ops.where( self._batch_ndims_is_0, 2, 1 + self.batch_ndims) event_shape = array_ops.slice(s, (event_start,), (self.event_ndims,))
tensorflow.python.ops.array_ops.where
1,217
import tensorflow as tf feature_spec={'x': tf.io.FixedLenFeature([], tf.string)}), dict( testcase_name='fixed_len_float', make_tensors_fn=lambda: {'x': tf.compat.v1.placeholder(tf.float32, (None,))}, feature_spec={'x': tf.io.FixedLenFeature([], tf.float32)}), dict( testcase_name='override', make_tensors_fn=_make_tensors_with_override, feature_spec={'x': tf.io.FixedLenFeature([], tf.int64)}, domains={'x': schema_pb2.IntDomain(is_categorical=True)}), dict( testcase_name='override_with_session', make_tensors_fn=_make_tensors_with_override, feature_spec={'x': tf.io.FixedLenFeature([], tf.int64)}, domains={ 'x': schema_pb2.IntDomain(min=5, max=6, is_categorical=True) },
tensorflow.io.FixedLenFeature
1,218
import tensorflow as tf result = estimator.evaluate( input_fn=eval_input_fn, steps=FLAGS.max_eval_steps) output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") with tf.gfile.GFile(output_eval_file, "w") as writer: tf.logging.info("***** Eval results *****") for key in sorted(result.keys()): tf.logging.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key])))
tensorflow.logging.info
1,219
import tensorflow as tf # Build another graph with 2 nodes, initialized # differently, and a Restore node for them. with self.test_session(graph=tf.Graph()) as sess: v0_2 = tf.Variable(1000.0, name="v0") v1_2 = tf.Variable(2000.0, name="v1") save2 = tf.train.Saver([v0_2, v1_2]) tf.initialize_all_variables().run() # Check that the parameter nodes have been initialized.
tensorflow.Variable
1,220
import tensorflow as tf """A demo script to show to train a segmentation model.""" from absl import app from absl import logging import tensorflow as tf import tensorflow_datasets as tfds from tensorflow_examples.lite.model_maker.third_party.efficientdet import hparams_config from tensorflow_examples.lite.model_maker.third_party.efficientdet.keras import efficientdet_keras def create_mask(pred_mask): pred_mask = tf.argmax(pred_mask, axis=-1) pred_mask = pred_mask[..., tf.newaxis] return pred_mask[0] dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True) def normalize(input_image, input_mask): input_image = tf.cast(input_image, tf.float32) / 255.0 input_mask -= 1
tensorflow.argmax
1,221
import tensorflow as tf def getinputs(path): filename_queue=tf.train.string_input_producer([path])
tensorflow.train.string_input_producer
1,222
import tensorflow as tf return tf.reverse(sequence, [0]) sequence_lengths = tf.convert_to_tensor(sequence_lengths) with tf.control_dependencies( [tf.assert_equal(sequence.shape[1], sequence_lengths.shape[0])]): return tf.reverse_sequence( sequence, sequence_lengths, seq_axis=0, batch_axis=1)
tensorflow.assert_equal
1,223
import tensorflow as tf inputs: 4-D tensor BxHxWxC kernel_size: a list of 2 ints stride: a list of 2 ints Returns: Variable tensor """ with tf.variable_scope(scope) as sc: kernel_h, kernel_w = kernel_size stride_h, stride_w = stride outputs = tf.nn.avg_pool(inputs, ksize=[1, kernel_h, kernel_w, 1], strides=[1, stride_h, stride_w, 1], padding=padding,
tensorflow.variable_scope
1,224
from tensorflow.python.framework import ops return gen_math_ops._tanh(x, name=name) ops.RegisterShape("Abs")(common_shapes.unchanged_shape) ops.RegisterShape("Ceil")(common_shapes.unchanged_shape) ops.RegisterShape("Conj")(common_shapes.unchanged_shape) ops.RegisterShape("Cos")(common_shapes.unchanged_shape) ops.RegisterShape("Exp")(common_shapes.unchanged_shape)
tensorflow.python.framework.ops.RegisterShape
1,225
import tensorflow as tf tf.flags.DEFINE_float('momentum', 0.9, """Momentum for training.""") 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.""")
tensorflow.flags.DEFINE_float
1,226
import tensorflow as tf train=True, validation=FLAGS.validation, shuffle=True) ul_images_eval_train = unlabeled_inputs(batch_size=FLAGS.eval_batch_size, validation=FLAGS.validation, shuffle=True) images_eval_test, labels_eval_test = inputs(batch_size=FLAGS.eval_batch_size, train=False, validation=FLAGS.validation, shuffle=True) def placeholder_like(x, name=None): return tf.placeholder(shape=x.shape, dtype=tf.float32, name=name) def random_sphere(shape): n = tf.random_normal(shape=shape, dtype=tf.float32) n = tf.reshape(n, shape=(int(shape[0]), -1)) n = tf.nn.l2_normalize(n, dim=1) n = tf.reshape(n, shape) return n def random_sphere_numpy(shape): n = np.random.normal(size=shape) proj_shape = tuple([n.shape[0]] + [1 for _ in range(len(shape) - 1)]) return n / np.linalg.norm(n.reshape((n.shape[0], -1)), axis=1).reshape(proj_shape)
tensorflow.placeholder
1,227
import tensorflow as tf # `sloppy` mode means that the interleaving is not exact. This adds # even more randomness to the training pipeline. d = d.apply( tf.contrib.data.parallel_interleave( tf.data.TFRecordDataset, sloppy=is_training, cycle_length=cycle_length,
tensorflow.contrib.data.parallel_interleave
1,228
import tensorflow as tf return (image, mask, tf.shape(image)) class DataTransformationFnTest(test_case.TestCase): def test_combine_additional_channels_if_present(self): image = np.random.rand(4, 4, 3).astype(np.float32) additional_channels = np.random.rand(4, 4, 2).astype(np.float32) tensor_dict = { fields.InputDataFields.image: tf.constant(image), fields.InputDataFields.image_additional_channels: tf.constant(additional_channels), fields.InputDataFields.groundtruth_classes: tf.constant(np.array([1, 1], np.int32)) } input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=1) with self.test_session() as sess: transformed_inputs = sess.run(
tensorflow.constant
1,229
import tensorflow as tf :param cov_structure: "diag" or "full" - "diag": cov holds the diagonal elements of the covariance matrix - "full": cov holds the full covariance matrix (without jitter) :return: sample from the MVN of shape N x D """ eps = tf.random_normal(tf.shape(mean), dtype=settings.float_type) # N x P if cov_structure == "diag": sample = mean + tf.sqrt(cov) * eps # N x P elif cov_structure == "full": cov = cov + (tf.eye(tf.shape(mean)[1], dtype=settings.float_type) * settings.numerics.jitter_level)[None, ...] # N x P x P chol = tf.cholesky(cov) # N x P x P return mean + (tf.matmul(chol, eps[..., None])[..., 0]) # N x P else: raise NotImplementedError # pragma: no cover return sample # N x P def _expand_independent_outputs(fvar, full_cov, full_output_cov): """ Reshapes fvar to the correct shape, specified by `full_cov` and `full_output_cov`.
tensorflow.cholesky
1,230
import tensorflow as tf shape = tf.cast(image_shape, tf.float32) w_greater = tf.greater(image_shape[0], image_shape[1]) shape = tf.cond(w_greater, lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32), lambda: tf.cast([size, shape[1] / shape[0] * size], tf.int32)) return uint8_resize_bicubic(image, shape)
tensorflow.cast
1,231
import tensorflow as tf # Create optimizer ops self.global_step = tf.Variable(0, trainable=False, name='global_step') opt = tf.train.RMSPropOptimizer(self.config['learning_rate']) with tf.control_dependencies(update_ops): self.trainer = opt.apply_gradients( gradvars, global_step=self.global_step) def _eval_graph(self, data): tower_metrics = self._gpu_tower(data, Mode.EVAL) with tf.device('/cpu:0'): self.metrics = {m: tf.reduce_mean(tf.stack([t[m] for t in tower_metrics])) for m in tower_metrics[0]} def _pred_graph(self, data): with tf.name_scope('pred'): with tf.device('/gpu:0'): pred_out = self._model(data, Mode.PRED, **self.config) self.pred_out = {n: tf.identity(p, name=n) for n, p in pred_out.items()} def _build_graph(self): # Training and evaluation network, if tf datasets provided if self.datasets: # Generate iterators for the given tf datasets self.dataset_iterators = {} with tf.device('/cpu:0'): for n, d in self.datasets.items(): if n == 'training': train_batch = self.config['batch_size']*self.n_gpus d = d.repeat().batch(train_batch).prefetch(train_batch)
tensorflow.name_scope
1,232
import tensorflow as tf bottom_shape = tf.shape(bottom) height = (tf.to_float(bottom_shape[1]) - 1.) * np.float32(self._feat_stride[0]) width = (tf.to_float(bottom_shape[2]) - 1.) * np.float32(self._feat_stride[0]) # rois除以h,w就得到了rois在特征图上的位置 x1 = tf.slice(rois, [0, 1], [-1, 1], name="x1") / width y1 = tf.slice(rois, [0, 2], [-1, 1], name="y1") / height x2 = tf.slice(rois, [0, 3], [-1, 1], name="x2") / width y2 = tf.slice(rois, [0, 4], [-1, 1], name="y2") / height # Won't be backpropagated to rois anyway, but to save time 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
tensorflow.slice
1,233
import tensorflow as tf 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 for (batch, (labels, chars, sequence_length)) in enumerate( tfe.Iterator(train_data)): with tf.contrib.summary.record_summaries_every_n_global_steps(log_interval): batch_model_loss = functools.partial(model_loss, labels, chars, sequence_length) optimizer.minimize( batch_model_loss, global_step=tf.train.get_global_step()) if log_interval and batch % log_interval == 0: print("train/batch #%d\tloss: %.6f" % (batch, batch_model_loss())) SOURCE_TRAIN_URL = "https://raw.githubusercontent.com/random-forests/tensorflow-workshop/master/archive/extras/colorbot/data/train.csv" SOURCE_TEST_URL = "https://raw.githubusercontent.com/random-forests/tensorflow-workshop/master/archive/extras/colorbot/data/test.csv" def main(_): data_dir = os.path.join(FLAGS.dir, "data") train_data = load_dataset( data_dir=data_dir, url=SOURCE_TRAIN_URL, batch_size=FLAGS.batch_size) eval_data = load_dataset(
tensorflow.train.get_global_step
1,234
import tensorflow as tf parser.add_argument('--symbolic', action='store_true') args = parser.parse_args() if not args.symbolic: augs = fbresnet_augmentor(args.aug == 'train') df = get_imagenet_dataflow( args.data, 'train', args.batch, augs) # For val augmentor, Should get >100 it/s (i.e. 3k im/s) here on a decent E5 server. TestDataSpeed(df).start() else: assert args.aug == 'train' data = get_imagenet_tfdata(args.data, 'train', args.batch) itr = data.make_initializable_iterator() dp = itr.get_next() dpop = tf.group(*dp) with tf.Session(config=get_default_sess_config()) as sess: sess.run(itr.initializer) for _ in tqdm.trange(200): sess.run(dpop) for _ in tqdm.trange(5000, smoothing=0.1): sess.run(dpop)
tensorflow.group
1,235
import tensorflow as tf segment_ids = features["segment_ids"] label_ids = features["label_ids"] is_real_example = None if "is_real_example" in features: is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32) else: is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32) is_training = (mode == tf.estimator.ModeKeys.TRAIN) (total_loss, per_example_loss, logits, probabilities) = create_model( bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,
tensorflow.shape
1,236
import tensorflow as tf tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), "segment_ids": tf.constant( all_segment_ids, shape=[num_examples, seq_length], dtype=tf.int32), "label_ids": tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32), }) if is_training: d = d.repeat() d = d.shuffle(buffer_size=100) d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder) return d
tensorflow.constant
1,237
import tensorflow as tf w_initializer, b_initializer = tf.random_normal_initializer(0., 0.1), tf.constant_initializer(0.0) # ------------------ build evaluate_net ------------------ with tf.variable_scope('eval_net'): a_fc1 = tf.layers.dense(self.s, 128, tf.nn.relu, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='agent_fc1_e') # a_fc2 = tf.layers.dense(a_fc1, 128, tf.nn.relu, kernel_initializer=w_initializer, # bias_initializer=b_initializer, name='agent_fc2_e') # a_fc3 = tf.layers.dense(a_fc2, 64, tf.nn.relu, kernel_initializer=w_initializer, # bias_initializer=b_initializer, name='agent_fc3_e') self.q_eval = tf.layers.dense(a_fc1, self.num_a, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='q_e') # ------------------ build target_net ------------------ with tf.variable_scope('target_net'): a_fc1_ = tf.layers.dense(self.s_, 128, tf.nn.relu, kernel_initializer=w_initializer, bias_initializer=b_initializer, name='agent_fc1_t') # a_fc2_ = tf.layers.dense(a_fc1_, 128, tf.nn.relu, kernel_initializer=w_initializer, # bias_initializer=b_initializer, name='agent_fc2_t') # a_fc3_ = tf.layers.dense(a_fc2_, 64, tf.nn.relu, kernel_initializer=w_initializer,
tensorflow.layers.dense
1,238
import tensorflow as tf initializer=tf.truncated_normal_initializer(stddev=stddev)) self.g = tf.get_variable('g',[out_dim], initializer=tf.constant_initializer(float('nan'))) self.b = tf.get_variable('b',[out_dim], initializer=tf.constant_initializer(float('nan'))) self.strides = [1, d_h, d_w, 1] self.epsilon = epsilon def __call__(self,input_var,name=None,**kwargs) : shapes = tf.shape(input_var) shapes = tf.stack([shapes[0],shapes[1]*self.strides[1],shapes[2]*self.strides[2],tf.shape(self.b)[0]]) def _init(): v_norm = tf.nn.l2_normalize(self.v,axis=[0,1,3]) t = tf.nn.conv2d_transpose(input_var,v_norm, output_shape=shapes, strides=self.strides, padding='SAME', data_format='NHWC') mu,var = tf.nn.moments(t,axes=[0,1,2]) std = tf.sqrt(var+self.epsilon) return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)]
tensorflow.shape
1,239
import tensorflow as tf for i in range(hparams.tacotron_num_gpus): tf.summary.histogram("mel_outputs %d" % i, model.tower_mel_outputs[i]) tf.summary.histogram("mel_targets %d" % i, model.tower_mel_targets[i]) tf.summary.scalar("before_loss", model.before_loss) tf.summary.scalar("after_loss", model.after_loss) if hparams.predict_linear: tf.summary.scalar("linear_loss", model.linear_loss)
tensorflow.summary.scalar
1,240
import tensorflow as tf """ Standardize log normal random variable x using mus and log_sigmas. """ if inverse: scales = tf.math.exp(log_sigmas) log_x = tf.math.log(x) ldj = log_x log_y = log_x*scales + mus ldj += log_sigmas z = tf.math.exp(log_y) 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 ldj -= log_sigmas z = tf.math.exp(log_y)
tensorflow.math.exp
1,241
from tensorflow.python.framework import ops y: A `Tensor` of type `float`, `double`, `int32`, `complex64`, or `int64`. name: A name for the operation (optional). 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.framework.ops.op_scope
1,242
import tensorflow as tf """ Returns a sample from a D-dimensional Multivariate Normal distribution :param mean: N x D :param cov: N x D or N x D x D :param cov_structure: "diag" or "full" - "diag": cov holds the diagonal elements of the covariance matrix - "full": cov holds the full covariance matrix (without jitter) :return: sample from the MVN of shape N x D """ eps = tf.random_normal(tf.shape(mean), dtype=settings.float_type) # N x P if cov_structure == "diag": sample = mean + tf.sqrt(cov) * eps # N x P elif cov_structure == "full": cov = cov + (tf.eye(tf.shape(mean)[1], dtype=settings.float_type) * settings.numerics.jitter_level)[None, ...] # N x P x P chol = tf.cholesky(cov) # N x P x P return mean + (tf.matmul(chol, eps[..., None])[..., 0]) # N x P else: raise NotImplementedError # pragma: no cover
tensorflow.shape
1,243
import tensorflow as tf Returns: tuple (final output, loss) ''' y = output if add_bias: bias = tf.Variable([0.0]) y = output + bias sig_y = tf.clip_by_value(tf.sigmoid(y), 0.001, 0.999) # avoid NaNs loss = -tf.reduce_sum(target*tf.log(sig_y) + (1-target)*tf.log(1-sig_y)) return sig_y, loss def ranking_margin_objective(output, margin=1.0): ''' Create final model output and loss for pairwise ranking margin objective Loss for single pair (f(p), f(n)) = [margin - f(p) + f(n)]+
tensorflow.log
1,244
import tensorflow as tf def sigmoid_ce_with_logits(logits, labels): return tf.nn.sigmoid_cross_entropy_with_logits(labels=labels, logits=logits) def sigmoid_kl_with_logits(logits, targets): assert isinstance(targets, float) if targets in [0., 1.]: entropy = 0. else: entropy = - targets*tf.log(targets) - (1. - targets)*tf.log(1. - targets) return sigmoid_ce_with_logits(logits, tf.ones_like(logits)*targets) - entropy def gradient_difference_loss(x, y): x_h_diff = x[:, 1:] - x[:, :-1] x_w_diff = x[:, :, 1:] - x[:, :, :-1] y_h_diff = y[:, 1:] - y[:, :-1] y_w_diff = y[:, :, 1:] - y[:, :, :-1] h_diff = tf.abs(tf.abs(x_h_diff) - tf.abs(y_h_diff))
tensorflow.log
1,245
from tensorflow.python.framework import tensor_shape "range (0, 1], got %g" % keep_prob) keep_prob = ops.convert_to_tensor( keep_prob, dtype=x.dtype, name="keep_prob") keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar()) noise_shape = noise_shape or array_ops.shape(x)
tensorflow.python.framework.tensor_shape.scalar
1,246
import tensorflow as tf self._moving_variance = tf.sub(self._moving_second_moment, tf.square(self._moving_mean),
tensorflow.square
1,247
import tensorflow as tf padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]] mask = tf.pad( tf.zeros(cutout_shape, dtype=images.dtype), padding_dims, constant_values=1) patch = tf.ones_like(images, dtype=images.dtype) * replace, mask = tf.expand_dims(mask, -1) mask = tf.tile(mask, [1, 1, num_channels]) images = tf.where( tf.equal(mask, 0), patch, images) images = tf.squeeze(images, axis=0)
tensorflow.tile
1,248
import tensorflow as tf device_setter = tf.train.replica_device_setter( worker_device=worker, ps_device='/cpu:0', ps_tasks=1) with tf.name_scope('{}_{}'.format(mode, i)) as scope: with tf.device(device_setter): net_outputs = self._model(shards[i], mode, **self.config) if mode == Mode.TRAIN: loss = self._loss(net_outputs, shards[i], **self.config) loss += tf.reduce_sum( tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES, scope)) model_params = tf.trainable_variables() grad = tf.gradients(loss, model_params) tower_losses.append(loss) tower_gradvars.append(zip(grad, model_params)) if i == 0: update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS,
tensorflow.get_collection
1,249
from tensorflow.python.framework import constant_op def _ranking_train_input_fn(): features = { "a.f1": constant_op.constant([[3.], [0.3], [1.]]), "a.f2": constant_op.constant([[0.1], [3.], [1.]]), "b.f1": constant_op.constant([[13.], [0.4], [5.]]), "b.f2": constant_op.constant([[1.], [3.], [0.01]]), } label = constant_op.constant([[0], [0], [1]], dtype=dtypes.int32) return features, label def _eval_input_fn(): features = {"x": constant_op.constant([[1.], [2.], [2.]])} label = constant_op.constant([[0], [1], [1]], dtype=dtypes.int32) return features, label def _infer_ranking_train_input_fn(): features = { "f1": constant_op.constant([[3.], [2], [1.]]), "f2": constant_op.constant([[0.1], [3.], [1.]]) } return features, None
tensorflow.python.framework.constant_op.constant
1,250
from tensorflow.python.ops import array_ops # batch_ndims to get the event start dim. event_start = array_ops.where( self._batch_ndims_is_0, 2, 1 + self.batch_ndims) event_shape = array_ops.slice(s, (event_start,), (self.event_ndims,)) new_shape = array_ops.concat(0, (sample_shape, batch_shape, event_shape)) x = array_ops.reshape(x, shape=new_shape)
tensorflow.python.ops.array_ops.slice
1,251
import tensorflow as tf tf.constant(config.local_norm_lvalues, dtype=tf.int64)), 0) rnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.local_norm_key, dtype=tf.int64),
tensorflow.constant
1,252
import tensorflow as tf masked_lm_log_probs, axis=-1, output_type=tf.int32) masked_lm_example_loss = tf.reshape(masked_lm_example_loss, [-1]) masked_lm_ids = tf.reshape(masked_lm_ids, [-1]) masked_lm_weights = tf.reshape(masked_lm_weights, [-1])
tensorflow.reshape
1,253
import tensorflow as tf try: if not tf.io.gfile.exists(a.crop_dir): tf.io.gfile.makedirs(a.crop_dir) except Exception as e:
tensorflow.io.gfile.makedirs
1,254
import tensorflow.contrib.layers as layers 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 gauss_initializer = initializers.xavier_initializer(uniform=False) # stddev = 1/n with tf.variable_scope("convnet"): out = layers.convolution2d( out, num_outputs=num_filters, kernel_size=8, stride=4, activation_fn=tf.nn.relu, weights_initializer=gauss_initializer, trainable=False) out = layers.flatten(out) with tf.variable_scope("action_value"): out = layers.fully_connected(out, num_outputs=num_actions, activation_fn=None) return out def simple_model_w_feat_eng(img_in, num_actions, scope, reuse=False): with tf.variable_scope(scope, reuse=reuse): out = img_in out = layers.flatten(out) # stddev = 1/n, where n = number of inputs gauss_initializer = initializers.xavier_initializer(uniform=False)
tensorflow.contrib.layers.flatten
1,255
import tensorflow as tf # Create mask that can be used to gather elements from L_flat and put them # into a diagonal matrix. diag_mask = np.zeros((self.nb_actions, self.nb_actions), dtype='int32') diag_mask[np.diag_indices(self.nb_actions)] = range(1, self.nb_actions + 1) # Add leading zero element to each element in the L_flat. We use this zero # element when gathering L_flat into a lower triangular matrix L. nb_rows = tf.shape(L_flat)[0] zeros = tf.expand_dims(tf.tile(K.zeros((1,)), [nb_rows]), 1) try: # Old TF behavior. L_flat = tf.concat(1, [zeros, L_flat]) except TypeError: # New TF behavior L_flat = tf.concat([zeros, L_flat], 1) # Finally, process each element of the batch. def fn(a, x): x_ = tf.gather(x, diag_mask) return x_ P = tf.scan(fn, L_flat, initializer=K.zeros((self.nb_actions, self.nb_actions))) else:
tensorflow.concat
1,256
import tensorflow as tf pass else: for support in self._supports: x1 = tf.sparse_tensor_dense_matmul(support, x0) x = self._concat(x, x1) for _ in range(2, self._max_diffusion_step + 1): x2 = 2 * tf.sparse_tensor_dense_matmul(support, x1) - x0 x = self._concat(x, x2) x1, x0 = x2, x1 num_matrices = len(self._supports) * self._max_diffusion_step + 1 # Adds for x itself. x = tf.reshape(x, shape=[num_matrices, self._num_nodes, input_size, batch_size]) x = tf.transpose(x, perm=[3, 1, 2, 0]) # (batch_size, num_nodes, input_size, order) x = tf.reshape(x, shape=[batch_size * self._num_nodes, input_size * num_matrices]) weights = tf.get_variable( 'weights', [input_size * num_matrices, output_size], dtype=dtype, initializer=tf.contrib.layers.xavier_initializer()) x = tf.matmul( x, weights) # (batch_size * self._num_nodes, output_size) biases = tf.get_variable("biases", [output_size], dtype=dtype, initializer=tf.constant_initializer( bias_start, dtype=dtype)) x = tf.nn.bias_add(x, biases) # Reshape res back to: (batch_size, num_node, state_dim)
tensorflow.reshape
1,257
import tensorflow as tf with tf.variable_scope(name): filt, conv_biases = self.get_conv_var(kernal_size, in_channels, out_channels, name) conv = tf.nn.conv2d(bottom, filt, [1,stride,stride,1], padding='SAME') bias = tf.nn.bias_add(conv, conv_biases)
tensorflow.nn.conv2d
1,258
import tensorflow as tf def is_generate_per_split(self): return True def example_reading_spec(self): data_fields = {"dist_targets": tf.VarLenFeature(tf.int64)} if self.has_inputs: data_fields["inputs"] = tf.VarLenFeature(tf.int64) # hack: ignoring true targets and putting dist_targets in targets data_items_to_decoders = { "inputs": tf.contrib.slim.tfexample_decoder.Tensor("inputs"), "targets": tf.contrib.slim.tfexample_decoder.Tensor("dist_targets"), } return (data_fields, data_items_to_decoders) def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): """Get vocab for distill problems.""" # We assume that vocab file is present in data_dir directory where the # data generated will be stored. vocab_filepath = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filepath)
tensorflow.contrib.slim.tfexample_decoder.Tensor
1,259
import tensorflow as tf if w > 1: right = (w - 1) // 2 left = (w - 1) - right pad_right = tf.tile(pad, [1, right, 1]) pad_left = tf.tile(pad, [1, left, 1]) inputs_ = tf.concat([pad_left, encoder_inputs_, pad_right], axis=1) else: inputs_ = encoder_inputs_ inputs_ = tf.nn.convolution(inputs_, filter=filter_, padding='VALID')
tensorflow.concat
1,260
import tensorflow as tf std = tf.sqrt(var+self.epsilon) return [tf.assign(self.g,1/std),tf.assign(self.b,-1.*mu/std)]
tensorflow.assign
1,261
import tensorflow as tf if __name__ == '__main__': tf.test.main()
tensorflow.test.main
1,262
import tensorflow as tf # instead. output_layer = model.get_pooled_output() hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( "output_weights", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( "output_bias", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope("loss"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) probabilities = tf.nn.softmax(logits, axis=-1) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
tensorflow.variable_scope
1,263
import tensorflow as tf def decode_csv(line): # all_data is a list of scalar tensors all_data = tf.decode_csv(line, record_defaults = DEFAULTS) inputs = all_data[:len(all_data) - N_OUTPUTS] # first N_INPUTS values labels = all_data[len(all_data) - N_OUTPUTS:] # last N_OUTPUTS values # Convert each list of rank R tensors to one rank R+1 tensor inputs = tf.stack(inputs, axis = 0) labels = tf.stack(labels, axis = 0) # Convert input R+1 tensor into a feature dictionary of one R+1 tensor features = {TIMESERIES_COL: inputs} return features, labels
tensorflow.stack
1,264
import tensorflow as tf # vanishing gradient regularization, Omega, as in Pascanu # NOTE: this is RELU specific def dOmega_dWrec(self): # states in shape timesteps, batch, n_rec 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)
tensorflow.stack
1,265
import tensorflow as tf return a + b output0 = f(tf.constant([1]), tf.constant([2])) output1 = f(tf.constant([[2]]), tf.constant([3])) tp = pool.ThreadPool(2)
tensorflow.constant
1,266
import tensorflow as tf self.model = model self.encoding = tf.placeholder(self.encode.dtype, self.encode.get_shape(), name='encoding') eval_decode = interpreter.build_decoder(self.encoding, model.config, reuse=True) print(target, eval_decode) self.eval_loss = interpreter.l2_loss(target, eval_decode, name='predictive_reconstruction') self.eval_decode = self._tensor_to_image(eval_decode) self.loss_ae = interpreter.l2_loss(target, model.decode, name='reconstruction') self.decode = self._tensor_to_image(model.decode) self.losses = [self.loss_ae] def build_predictive_model(self): self.build_ae_model() # builds on top of AE model. Due to auxilary operations init self.inputs = tf.placeholder(tf.uint8, [3] + self.batch_shape, name='inputs') self.targets = tf.placeholder(tf.uint8, [3] + self.batch_shape, name='targets') # transform inputs self.raw_inputs = [self._image_to_tensor(self.inputs[i]) for i in range(3)] self.raw_targets = [self._image_to_tensor(self.targets[i]) for i in range(3)] # build AE objective for triplet config = self.model.config models = [interpreter.build_autoencoder(x, config) for x in self.raw_inputs] reco_losses = [1./3 * interpreter.l2_loss(models[i].decode, self.raw_targets[i]) for i in range(3)] # business as usual self.models = models # build predictive objective
tensorflow.placeholder
1,267
import tensorflow as tf dtype = gen_dtype(env, 'state action next_state reward done timeout') train_set = Dataset(dtype, FLAGS.rollout.max_buf_size) dev_set = Dataset(dtype, FLAGS.rollout.max_buf_size) task_train_sets = [Dataset(dtype, FLAGS.rollout.max_buf_size) for i in range(100)] task_dev_sets = [Dataset(dtype, FLAGS.rollout.max_buf_size) for i in range(100)] print ("state and action dim:", dim_state, dim_action) policy = GaussianMLPPolicy(dim_state, dim_action, normalizer=normalizers.state, **FLAGS.policy.as_dict()) warmup_policy = GaussianMLPPolicy(dim_state, dim_action, normalizer=normalizers.state, **FLAGS.policy.as_dict()) print (policy.parameters()) print (warmup_policy.parameters()) sync_warmup_policy = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(warmup_policy.parameters(), policy.parameters())]) # batched noises noise = OUNoise(env.action_space, theta=FLAGS.OUNoise.theta, sigma=FLAGS.OUNoise.sigma, shape=(1, dim_action)) vfn = MLPVFunction(dim_state, [64, 64], normalizers.state) warmup_vfn = MLPVFunction(dim_state, [64, 64], normalizers.state) sync_warmup_vfn = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(warmup_vfn.parameters(), vfn.parameters())]) model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) lazy_model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) warmup_model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) sync_warmup_model = tf.group(*[tf.assign(w_v, p_v) for w_v, p_v in zip(warmup_model.parameters(), model.parameters())])
tensorflow.assign
1,268
import tensorflow as tf tf.estimator.ModeKeys.TRAIN, loss=tf_loss, train_op=train_op, training_chief_hooks=[restore_hook, saver_hook]) def estimator_spec_eval( self, features, logits, labels, loss, restore_hook, use_tpu): """Construct EstimatorSpec for EVAL mode.""" hparams = self.hparams problem = hparams.problem if logits.get_shape().ndims == 3: logits = tf.expand_dims(tf.expand_dims(logits, 2), 3) eval_metrics_fns = metrics.create_evaluation_metrics([problem], hparams) if use_tpu: def metric_fn(tf_logits, labels): with tf.device("cpu:0"), mtf.utils.outside_all_rewrites(): eval_metrics = {} for metric_name, metric_fn in six.iteritems(eval_metrics_fns): if metric_name.split("/")[-1] not in t2t_model.TPU_METRIC_BLACKLIST:
tensorflow.expand_dims
1,269
import tensorflow as tf raise RuntimeError('type error {}'.format(self._var_list)) assert len(restore_key2vars) > 0 restore_key2vars = sorted([(k, v) for k, v in restore_key2vars.items() if k in saved_shapes]) msg = [] var_list = dict() with tf.variable_scope('', reuse=True): for key, var in restore_key2vars: var_shape = var.get_shape().as_list() if var_shape == saved_shapes[key]: var_list[key] = var
tensorflow.variable_scope
1,270
from tensorflow.python.framework import ops @ops.RegisterShape("TopK") @ops.RegisterShape("TopKV2")
tensorflow.python.framework.ops.RegisterShape
1,271
import tensorflow as tf def main(_): tf.logging.set_verbosity(tf.logging.INFO) if not FLAGS.do_train and not FLAGS.do_eval:
tensorflow.logging.set_verbosity
1,272
import tensorflow as tf @dynamic_batching.batch_fn def f(a): return a output = f(tf.constant([1, 2])) coord = tf.train.Coordinator() tf.train.start_queue_runners(coord=coord) with self.assertRaises(tf.errors.CancelledError): session.run(output) with self.assertRaises(tf.errors.CancelledError):
tensorflow.train.Coordinator
1,273
import tensorflow as tf output = facts * tf.expand_dims(scores, -1) output = tf.reshape(output, tf.shape(facts))
tensorflow.shape
1,274
from tensorflow.contrib.eager.python.examples.spinn import data self.assertEqual((3,), logits.shape) def testInferSpinnThrowsErrorIfOnlyOneSentenceIsSpecified(self): snli_1_0_dir = os.path.join(self._temp_data_dir, "snli/snli_1.0") self._create_test_data(snli_1_0_dir) vocab = data.load_vocabulary(self._temp_data_dir) word2index, embed = data.load_word_vectors(self._temp_data_dir, vocab) config = _test_spinn_config( data.WORD_VECTOR_LEN, 4, logdir=os.path.join(self._temp_data_dir, "logdir"),
tensorflow.contrib.eager.python.examples.spinn.data.load_vocabulary
1,275
import tensorflow as tf with tf.name_scope('losses'): with tf.name_scope('LossA'): # reconstruction loss recon_loss_A = tf.reduce_mean(tf.abs(A - ABA), name='recon_loss') # gan loss G_loss_A, D_loss_A = LSGAN_losses(A_dis_real, A_dis_fake)
tensorflow.abs
1,276
import tensorflow as tf lr = args.lr n_epoch = args.n_epoch n_batch_size = args.n_batch_size reg_lambda = args.reg_lambda keep_prob = args.keep_prob cross_stitch_enabled = args.cross_stitch_enabled with tf.variable_scope("placeholder"): X = tf.placeholder(tf.float32, (None, 128), "X") y_1 = tf.placeholder(tf.float32, (None, n_output_1), "y_1") y_2 = tf.placeholder(tf.float32, (None, n_output_2), "y_2") is_training = tf.placeholder(tf.bool, (), "is_training") with tf.variable_scope("network"): with contrib.framework.arg_scope( [contrib.layers.fully_connected], # he initialization weights_initializer=contrib.layers.variance_scaling_initializer(), # l2 regularization weights_regularizer=contrib.layers.l2_regularizer(reg_lambda), # BN normalizer_fn=contrib.layers.batch_norm,
tensorflow.placeholder
1,277
from tensorflow.python.ops import variable_scope as vs 2 * self._num_units, True, bias_initializer=bias_ones, kernel_initializer=self._kernel_initializer) value = math_ops.sigmoid(self._gate_linear([inputs, state])) r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) r_state = r * state if self._candidate_linear is None: with vs.variable_scope("candidate"): self._candidate_linear = _Linear( [inputs, r_state], self._num_units, True, bias_initializer=self._bias_initializer, kernel_initializer=self._kernel_initializer) c = self._activation(self._candidate_linear([inputs, r_state])) u = (1.0 - att_score) * u new_h = u * state + (1 - u) * c
tensorflow.python.ops.variable_scope.variable_scope
1,278
import tensorflow as tf # Build the graph for the deep net y_conv, img_summary = deepnn(x, train) # Define your loss function - softmax_cross_entropy with tf.variable_scope('x_entropy'): cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) # Define your AdamOptimiser, using FLAGS.learning_rate to minimixe the loss function
tensorflow.variable_scope
1,279
import tensorflow as tf raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode)) return output_spec return model_fn def get_masked_lm_output(bert_config, input_tensor, output_weights, positions, label_ids, label_weights): """Get loss and log probs for the masked LM.""" input_tensor = gather_indexes(input_tensor, positions) with tf.variable_scope("cls/predictions"): # We apply one more non-linear transformation before the output layer. # This matrix is not used after pre-training. with tf.variable_scope("transform"): input_tensor = tf.layers.dense( input_tensor, units=bert_config.hidden_size, activation=modeling.get_activation(bert_config.hidden_act), kernel_initializer=modeling.create_initializer( bert_config.initializer_range)) input_tensor = modeling.layer_norm(input_tensor) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. output_bias = tf.get_variable( "output_bias", shape=[bert_config.vocab_size], initializer=tf.zeros_initializer())
tensorflow.variable_scope
1,280
import tensorflow as tf test = ContextAEPushReal() elif args.experiment_type == "sweep": test = ContextAESweep() test.build(tfinput, args.ablation_type) config = tf.ConfigProto() config.gpu_options.allow_growth=True sess = tf.Session(config=config) learning_rate = tf.placeholder(tf.float32, shape=[]) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(test.loss) sess.run(tf.global_variables_initializer()) allloss = []
tensorflow.ConfigProto
1,281
import tensorflow as tf net = DenseLayer(net, n_units=4, act=tf.identity, W_init=tf.random_uniform_initializer(0, 0.01), b_init=None, name='q_a_s') y = net.outputs # action-value / rewards of 4 actions predict = tf.argmax(y, 1) # chose action greedily with reward. in Q-Learning, policy is greedy, so we use "max" to select the next action. ## Below we obtain the loss by taking the sum of squares difference between the target and prediction Q values. nextQ = tf.placeholder(shape=[1, 4], dtype=tf.float32) loss = tl.cost.mean_squared_error(nextQ, y, is_mean=False) # tf.reduce_sum(tf.square(nextQ - y)) train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss) ## Set learning parameters lambd = .99 # decay factor e = 0.1 # e-Greedy Exploration, the larger the more random num_episodes = 10000 with tf.Session() as sess: tl.layers.initialize_global_variables(sess) for i in range(num_episodes): ## Reset environment and get first new observation episode_time = time.time() s = env.reset() # observation is state, integer 0 ~ 15 rAll = 0 for j in range(99): # step index, maximum step is 99 if render: env.render() ## Choose an action by greedily (with e chance of random action) from the Q-network a, allQ = sess.run([predict, y], feed_dict={inputs : [to_one_hot(s, 16)]}) ## e-Greedy Exploration !!! sample random action if np.random.rand(1) < e: a[0] = env.action_space.sample()
tensorflow.Session
1,282
from tensorflow.contrib.learn.python.learn.summary_writer_cache import SummaryWriterCache save_secs: `int`, save every N secs. save_steps: `int`, save every N steps. saver: `Saver` object, used for saving. checkpoint_basename: `str`, base name for the checkpoint files. scaffold: `Scaffold`, use to get saver object. 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 self._last_saved_step = None if save_steps is None and save_secs is None: raise ValueError("Either save_steps or save_secs should be provided") if (save_steps is not None) and (save_secs is not None): raise ValueError("Can not provide both save_steps and save_secs.")
tensorflow.contrib.learn.python.learn.summary_writer_cache.SummaryWriterCache.get
1,283
import tensorflow as tf assert(data_format == 'NCHW' or data_format == 'NHWC') self.w = tf.get_variable('w', [k_h, k_w, input_dim, channel_multiplier], initializer=tf.truncated_normal_initializer(stddev=stddev)) self.b = tf.get_variable('b',[input_dim*channel_multiplier], initializer=tf.constant_initializer(0.0)) if( data_format == 'NCHW' ) : self.strides = [1, 1, d_h, d_w] else : self.strides = [1, d_h, d_w, 1] self.data_format = data_format self.padding = padding def __call__(self,input_var,name=None,**xargs) : return tf.nn.bias_add( tf.nn.depthwise_conv2d(input_var, self.w, data_format=self.data_format, strides=self.strides, padding=self.padding), self.b,data_format=self.data_format,name=name) class Conv3d(object) : def __init__(self,name,input_dim,output_dim,k_t=2,k_h=4,k_w=4,d_t=1,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))
tensorflow.nn.depthwise_conv2d
1,284
import tensorflow as tf self.sample_action = tf.squeeze(pi_eval.sample(1), axis=0) self.eval_action = pi_eval.mode() self.global_step = tf.train.get_or_create_global_step() self.saver = tf.train.Saver() # Loss functions and training
tensorflow.train.get_or_create_global_step
1,285
from tensorflow.python.framework import constant_op def _ranking_train_input_fn(): features = { "a.f1": constant_op.constant([[3.], [0.3], [1.]]), "a.f2": constant_op.constant([[0.1], [3.], [1.]]), "b.f1": constant_op.constant([[13.], [0.4], [5.]]), "b.f2": constant_op.constant([[1.], [3.], [0.01]]), } label = constant_op.constant([[0], [0], [1]], dtype=dtypes.int32) return features, label
tensorflow.python.framework.constant_op.constant
1,286
import tensorflow as tf 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, state_init_a, state_final_a def build_cnet(self, state_in, name, reuse=False, batch_size=64): 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) lstm_c = tf.nn.rnn_cell.LSTMCell(num_units=256)
tensorflow.contrib.layers.l2_regularizer
1,287
import tensorflow as tf trainable=is_pretrain, shape=[out_channels], initializer=tf.constant_initializer(0.0)) x = tf.nn.conv2d(x,w,strides,padding='SAME',name='conv') x = tf.nn.bias_add(x,b,name='bias_add') x = tf.nn.relu(x,name='relu') return x def pool(layer_name, x, kernel_size=[1,2,2,1], strides=[1,2,2,1], is_max_pool=True):
tensorflow.nn.relu
1,288
import tensorflow as tf num_boxes = sample['num_boxes'].numpy() labeled_boxes_init = tf.gather( sample['groundtruth_boxes'], axis=1, indices=[1, 0, 3, 2]) * 256.0 for _, metric in self.metrics.items(): if isinstance(metric, ShapeAccuracyMetric): labels = sample['shapes'] weights = tf.math.sign(labels + 1) # -1 is mapped to zero, else 1 metric.update(labels, detections['shapes_logits'], weights) elif isinstance(metric, BoxIoUMetric): scene_id = str(sample['scene_filename'].numpy(), 'utf-8') # Get ground truth boxes labeled_boxes = labeled_boxes_init
tensorflow.math.sign
1,289
import tensorflow as tf def read_and_decode(filename_queue): reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, # Defaults are not specified since both keys are required. features={ 'image_raw': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.int64), }) if FLAGS.contrast_norm == 'areafactor': image = tf.decode_raw(features['image_raw'], tf.float32) else: image = tf.decode_raw(features['image_raw'], tf.uint8) image = tf.cast(image, tf.float32) * (1. / 255)
tensorflow.FixedLenFeature
1,290
from tensorflow.python.framework import ops return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())] return [op.inputs[1].get_shape()] @ops.RegisterShape("AssignAdd") @ops.RegisterShape("AssignSub") def _AssignUpdateShape(op): """Shape function for the AssignAdd and AssignSub dense update ops."""
tensorflow.python.framework.ops.RegisterShape
1,291
import tensorflow as tf X = tf.reshape(X, (-1, ch)) W = self._make_var('W', (ch, out_ch), no_reg=no_reg) X = tf.matmul(X, W) X = tf.reshape(X, (-1, out_ch)) # Sanity shape check return X def _add_factorized_reduction(self, X, in_w, in_h, in_ch, out_ch, is_train=False): ''' Output is of shape (in_w // 2, in_h // 2, out_ch) ''' assert in_w % 2 == 0 and in_h % 2 == 0, 'Width & height ({} & {}) must both be even!'.format(in_w, in_h) with tf.variable_scope('fac_reduc'): # Split area into 2 halves half_1 = tf.nn.avg_pool(X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID') shifted_X = tf.pad(X, ((0, 0), (0, 1), (0, 1), (0, 0)))[:, 1:, 1:, :] half_2 = tf.nn.avg_pool(shifted_X, ksize=(1, 1, 1, 1), strides=(1, 2, 2, 1), padding='VALID') # Apply 1 x 1 convolution to each half separately W_half_1 = self._make_var('W_half_1', (1, 1, in_ch, out_ch >> 1)) X_half_1 = tf.nn.conv2d(half_1, W_half_1, (1, 1, 1, 1), padding='VALID') W_half_2 = self._make_var('W_half_2', (1, 1, in_ch, out_ch >> 1)) X_half_2 = tf.nn.conv2d(half_2, W_half_2, (1, 1, 1, 1), padding='VALID') # Concat both halves across channels X = tf.concat([X_half_1, X_half_2], axis=3) # Apply batch normalization X = self._add_batch_norm(X, out_ch, is_train=is_train)
tensorflow.pad
1,292
import tensorflow as tf 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(tf.float32), 'image/object/class/label': tf.io.VarLenFeature(tf.int64), 'image/object/area': tf.io.VarLenFeature(tf.float32), 'image/object/is_crowd': tf.io.VarLenFeature(tf.int64), } if include_mask: self._keys_to_features.update({ 'image/object/mask': tf.io.VarLenFeature(tf.string), }) def _decode_image(self, parsed_tensors): """Decodes the image and set its static shape.""" image = tf.io.decode_image(parsed_tensors['image/encoded'], channels=3) image.set_shape([None, None, 3]) return image def _decode_boxes(self, parsed_tensors): """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']
tensorflow.io.VarLenFeature
1,293
import tensorflow as tf # patch_size = int(sizes[idx[0][0]]) patch_size = self.get_random_patch_size() print('Patch size:',patch_size) window = [1,patch_size,patch_size,1] print('Window:',window) n_row,n_col,n_channel = x.shape n_patch = n_row*n_col // (patch_size**2) patches = tf.image.extract_patches(tf.expand_dims(x,0),sizes=window,strides=window,rates=[1, 1, 1, 1],padding='VALID') patches = tf.reshape(patches,[n_patch,patch_size,patch_size,n_channel]) patches = tf.random.shuffle(patches) rows = tf.split(patches,n_col//patch_size,axis=0) rows = [tf.concat(tf.unstack(x),axis=1) for x in rows] x_aug = tf.concat(rows,axis=0) x_aug = tf.convert_to_tensor(x_aug) return tf.concat([x, x_aug],axis=2)
tensorflow.reshape
1,294
import tensorflow as tf def mlp_dropout(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None, dropout_rate=0): for h in hidden_sizes[:-1]: x = tf.layers.dense(x, units=h, activation=activation) x = tf.layers.dropout(x, rate=dropout_rate, training=True) x = tf.layers.dropout(x, rate=dropout_rate, training=True) return tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation) def mlp(x, hidden_sizes=(32,), activation=tf.tanh, output_activation=None): for h in hidden_sizes[:-1]: x = tf.layers.dense(x, units=h, activation=activation) return tf.layers.dense(x, units=hidden_sizes[-1], activation=output_activation)
tensorflow.layers.dense
1,295
import tensorflow as tf } inputs = tf.placeholder(tf.int32, shape=[batch_size, 6]) regressor = XLNetRegressor(hparams=hparams) logits = regressor(inputs) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) logits_ = sess.run( logits, feed_dict={inputs: np.random.randint(30521, size=(batch_size, 6))}) self.assertEqual(logits_.shape, (batch_size,))
tensorflow.global_variables_initializer
1,296
import tensorflow as tf out = out + beta return out def max_pool(img, k): return tf.nn.max_pool(img, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME') # Consider stride size when using xavier for fp network
tensorflow.nn.max_pool
1,297
import tensorflow as tf for i, ((ntime, nband, nfilt), (ptime, pband)) in enumerate(zip(cnn_filter_shapes, cnn_pool)): layer_name = 'cnn_{}'.format(i) with tf.variable_scope(layer_name): filters = tf.get_variable('filters', [ntime, nband, nfilt_last, nfilt], initializer=cnn_init, dtype=dtype)
tensorflow.variable_scope
1,298
import tensorflow as tf def test_maximum_batch_size(self): with self.test_session() as session: @dynamic_batching.batch_fn_with_options(maximum_batch_size=2) def f(a, b): batch_size = tf.shape(a)[0] return a + b, tf.tile([batch_size], [batch_size]) outputs = [ f(tf.constant([1]), tf.constant([2])),
tensorflow.shape
1,299