seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf y += dense(pos_feats, encoder.attn_size, use_bias=False, name='P_a') if encoder.attn_filters: filter_shape = [encoder.attn_filter_length * 2 + 1, 1, 1, encoder.attn_filters] filter_ = get_variable('filter', filter_shape) prev_weights = tf.reshape(prev_weights, tf.stack([batch_size, time_steps, 1, 1])) conv = tf.nn.conv2d(prev_weights, filter_, [1, 1, 1, 1], 'SAME') conv = tf.squeeze(conv, axis=2) y += dense(conv, encoder.attn_size, use_bias=False, name='C_a') v = get_variable('v_a', [encoder.attn_size]) return tf.reduce_sum(v * tf.tanh(y), axis=2) def global_attention(state, hidden_states, encoder, encoder_input_length, scope=None, context=None, **kwargs): with tf.variable_scope(scope or 'attention_{}'.format(encoder.name)): if context is not None and encoder.use_context: state = tf.concat([state, context], axis=1) e = compute_energy(hidden_states, state, encoder, input_length=encoder_input_length, **kwargs) mask = tf.sequence_mask(encoder_input_length, maxlen=tf.shape(hidden_states)[1], dtype=tf.float32) e *= mask
tensorflow.tanh
8,500
import tensorflow as tf if verbose: print("Iteration %d: loss %.4f" % (i, loss)) if logdir: with summary_writer.as_default(): with tf.contrib.summary.always_record_summaries(): tf.contrib.summary.scalar("loss", loss) class L2hmcTest(tf.test.TestCase):
tensorflow.contrib.summary.always_record_summaries
8,501
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten # Block 1 conv1a = Conv2D(padding="same", filters=RNN_SIZE//8, kernel_size=[8, 8], strides=4, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(self.inputs) conv1b = Conv2D(padding="same", filters=RNN_SIZE//8, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv1a) conv1c = Conv2D(padding="same", filters=RNN_SIZE//8, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv1b) pool1 = MaxPool2D(pool_size=[2,2])(conv1c) # Block 2 conv2a = Conv2D(padding="same", filters=RNN_SIZE//4, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(pool1)
tensorflow.keras.layers.MaxPool2D
8,502
import tensorflow as tf def _fake_model_preprocessor_fn(image): return (image, tf.expand_dims(tf.shape(image)[1:], axis=0)) def _fake_image_resizer_fn(image, mask): 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)
tensorflow.shape
8,503
import tensorflow as tf finetune_one_hot_labels, global_step, loss_weights, inst_weights) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops): src_train_op, _ = get_src_train_op(loss) with tf.control_dependencies([src_train_op]): target_avg_pool = get_logits( target_features, mode, FLAGS.target_dataset, reuse=True) target_logits = do_cls( target_avg_pool, target_num_classes, name='final_target_dense') is_prediction_correct = tf.equal( tf.argmax(tf.identity(target_logits), axis=1), tf.argmax(target_one_hot_labels, axis=1)) acc = tf.reduce_mean(tf.cast(is_prediction_correct, tf.float32)) entropy = loss_entropy + rl_entropy log_prob = loss_log_prob + log_prob train_op, _, _ = meta_train_op(acc, entropy, log_prob, rl_scope, params) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) def rl_label_weights(name=None): """Returns the weight for importance.""" with tf.variable_scope(name, 'rl_op_selection'): num_classes = FLAGS.src_num_classes num_choices = FLAGS.num_choices
tensorflow.cast
8,504
import tensorflow as tf x: A tensor or variable. alpha: A scalar, slope of negative section (default=`0.`). max_value: Saturation threshold. Returns ------- A tensor. """ if alpha != 0.: negative_part = tf.nn.relu(-x) x = tf.nn.relu(x) if max_value is not None: max_value = _to_tensor(max_value, x.dtype.base_dtype) zero = _to_tensor(0., x.dtype.base_dtype) x = tf.clip_by_value(x, zero, max_value) if alpha != 0.: alpha = _to_tensor(alpha, x.dtype.base_dtype) x -= alpha * negative_part
tensorflow.nn.relu
8,505
import tensorflow as tf nas_training_hyper_parameters=nas_training_hyper_parameters) if model_options.decoder_output_stride: crop_size = model_options.crop_size if crop_size is None: crop_size = [tf.shape(images)[1], tf.shape(images)[2]] features = refine_by_decoder( features, end_points, crop_size=crop_size,
tensorflow.shape
8,506
import tensorflow as tf fpositive_mask = tf.cast(positive_mask, tf.float32) n_positives = tf.reduce_sum(fpositive_mask) # negtive examples are those max_overlap is still lower than neg_threshold, note that some positive may also has lower jaccard # note those gscores is 0 is either be ignored during anchors encode or anchors have 0 overlap with all ground truth #negtive_mask = tf.logical_and(tf.logical_and(tf.logical_not(tf.logical_or(positive_mask, glabels < 0)), gscores < params['neg_threshold']), gscores > 0.) negtive_mask = tf.logical_and(tf.equal(glabels, 0), gscores > 0.) #negtive_mask = tf.logical_and(tf.logical_and(tf.logical_not(positive_mask), gscores < params['neg_threshold']), gscores > 0.) #negtive_mask = tf.logical_and(gscores < params['neg_threshold'], tf.logical_not(positive_mask)) fnegtive_mask = tf.cast(negtive_mask, tf.float32) n_negtives = tf.reduce_sum(fnegtive_mask) n_neg_to_select = tf.cast(params['negative_ratio'] * n_positives, tf.int32) n_neg_to_select = tf.minimum(n_neg_to_select, tf.cast(n_negtives, tf.int32)) # hard negative mining for classification predictions_for_bg = tf.nn.softmax(cls_pred)[:, 0]
tensorflow.cast
8,507
import tensorflow as tf def focal_loss(onehot_labels, cls_preds, alpha=0.25, gamma=2.0, name=None, scope=None): """Compute softmax focal loss between logits and onehot labels logits and onehot_labels must have same shape [batchsize, num_classes] and the same data type (float16, 32, 64) Args: onehot_labels: Each row labels[i] must be a valid probability distribution cls_preds: Unscaled log probabilities alpha: The hyperparameter for adjusting biased samples, default is 0.25 gamma: The hyperparameter for penalizing the easy labeled samples name: A name for the operation (optional) Returns: A 1-D tensor of length batch_size of same type as logits with softmax focal loss """ with tf.name_scope(scope, 'focal_loss', [cls_preds, onehot_labels]) as sc: logits = tf.convert_to_tensor(cls_preds) onehot_labels = tf.convert_to_tensor(onehot_labels) precise_logits = tf.cast(logits, tf.float32) if ( logits.dtype == tf.float16) else logits onehot_labels = tf.cast(onehot_labels, precise_logits.dtype) predictions = tf.nn.sigmoid(logits) predictions_pt = tf.where(tf.equal(onehot_labels, 1), predictions, 1.-predictions) # add small value to avoid 0 epsilon = 1e-8 alpha_t = tf.scalar_mul(alpha, tf.ones_like(onehot_labels, dtype=tf.float32)) alpha_t = tf.where(tf.equal(onehot_labels, 1.0), alpha_t, 1-alpha_t) losses = tf.reduce_sum(-alpha_t * tf.pow(1. - predictions_pt, gamma) * tf.log(predictions_pt+epsilon),
tensorflow.name_scope
8,508
import tensorflow as tf if __name__ == '__main__': SESS = tf.Session() with tf.device('/cpu:0'): OPT = tf.train.AdamOptimizer(1e-4) # 后续主要是使用该optimizer中的apply—gradients操作 # OPT_C = tf.train.RMSPropOptimizer(LR_C, name='RMSPropC') # 定义critic训练过程 GLOBAL_AC = ACnet(scope=GLOBAL_NET_SCOPE) # 创建中央大脑GLOBALE_AC,只创建结构(A和C的参数) workers = [] for i in range(N_workers): # N—workers等于cpu数量
tensorflow.train.AdamOptimizer
8,509
import tensorflow as tf assert isinstance(targets, float) if targets in [0., 1.]: entropy = 0. else: entropy = - targets * np.log(targets) - \ (1. - targets) * np.log(1. - targets) return tf.nn.sigmoid_cross_entropy_with_logits( labels=tf.ones_like(logits) * targets, logits=logits) - entropy def _setup_model_loss(self, update_ops=None, num_classes=6): self.learning_rate_d = tf.placeholder(tf.float32, shape=[], name="learning_rate_placeholder") self.learning_rate_g = tf.placeholder(tf.float32, shape=[], name="learning_rate_placeholder") d_optimizer = self._optimizer(
tensorflow.ones_like
8,510
import tensorflow as tf scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*"
tensorflow.logging.info
8,511
import tensorflow as tf if len(sampled_words)!=0: sampled_words = tf.stack(sampled_words, axis=1) # [batch_size, max_dec_steps] vocab_scores = tf.stack(vocab_scores, axis=1) # [batch_size, max_dec_steps, vocab] # calculating loss self._loss = None
tensorflow.stack
8,512
import tensorflow as tf img_summary: a string tensor containing sampled input images. """ # Reshape to use within a convolutional neural net. Last dimension is for # 'features' - it would be 1 one for a grayscale image, 3 for an RGB image, # 4 for RGBA, etc. x_image = tf.reshape(x, [-1, FLAGS.img_width, FLAGS.img_height, FLAGS.img_channels]) x_image = tf.cond(train, lambda: tf.map_fn(tf.image.random_flip_left_right, x_image), lambda: x_image) x_image = tf.cond(train, lambda: tf.map_fn(lambda x: tf.image.random_brightness(x, 0.5), x_image), lambda: x_image) img_summary = tf.summary.image('Input_images', x_image) # First convolutional layer - maps one image to 32 feature maps. with tf.variable_scope('Conv_1'): conv1 = tf.layers.conv2d( inputs=x_image, filters=32,
tensorflow.image.random_brightness
8,513
from tensorflow.python.client import device_lib def main(_): if not FLAGS.data_path: raise ValueError("Must set --data_path to PTB data directory") gpus = [ x.name for x in device_lib.list_local_devices() if x.device_type == "GPU" ] if FLAGS.num_gpus > len(gpus): raise ValueError( "Your machine has only %d gpus " "which is less than the requested --num_gpus=%d."
tensorflow.python.client.device_lib.list_local_devices
8,514
from tensorflow.contrib.framework.python.framework import checkpoint_utils """Returns cluster centers.""" clusters = checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_VARIABLE) return np.squeeze(clusters, 1) def covariances(self): """Returns the covariances.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE) def _parse_tensor_or_dict(self, features): if isinstance(features, dict): return array_ops.concat([features[k] for k in sorted(features.keys())], 1)
tensorflow.contrib.framework.python.framework.checkpoint_utils.load_variable
8,515
import tensorflow as tf biases = _variable_on_cpu('biases', [num_outputs], tf.constant_initializer(0.0)) outputs = tf.nn.bias_add(outputs, biases)
tensorflow.nn.bias_add
8,516
import tensorflow as tf import tensorflow as tf #add_layer 函数里面所有的with都是为了tensorboard添加上去的 def add_layer(inputs, in_size, out_size, activation_function=None,nameScope="layer"): # add one more layer and return the output of this layer with tf.name_scope(nameScope): with tf.name_scope('weights'): Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
tensorflow.name_scope
8,517
import tensorflow as tf targets_dx = (gt_boxes_urx - bboxes_urx)/(bboxes_width * variances[0]) targets_dy = (gt_boxes_ury - bboxes_ury)/(bboxes_height * variances[0]) targets_dw = tf.log(gt_boxes_width / bboxes_width) / variances[1] targets_dh = tf.log(gt_boxes_height / bboxes_height) / variances[1]
tensorflow.log
8,518
import tensorflow.contrib.graph_editor as ge - 'speed': checkpoint all outputs of convolutions and matmuls. these ops are usually the most expensive, so checkpointing them maximizes the running speed (this is a good option if nonlinearities, concats, batchnorms, etc are taking up a lot of memory) - 'memory': try to minimize the memory usage (currently using a very simple strategy that identifies a number of bottleneck tensors in the graph to checkpoint) - 'collection': look for a tensorflow collection named 'checkpoints', which holds the tensors to checkpoint ''' # print("Calling memsaving gradients with", checkpoints) if not isinstance(ys,list): ys = [ys] if not isinstance(xs,list): xs = [xs] bwd_ops = ge.get_backward_walk_ops([y.op for y in ys], inclusive=True) debug_print("bwd_ops: %s", bwd_ops) # forward ops are all ops that are candidates for recomputation fwd_ops = ge.get_forward_walk_ops([x.op for x in xs], inclusive=True, within_ops=bwd_ops) debug_print("fwd_ops: %s", fwd_ops) # exclude ops with no inputs fwd_ops = [op for op in fwd_ops if op.inputs]
tensorflow.contrib.graph_editor.get_backward_walk_ops
8,519
import tensorflow as tf src_features, src_labels = features['src'], tf.cast(labels['src'], tf.int64) finetune_features = features['finetune'] target_features = features['target'] num_classes = FLAGS.src_num_classes finetune_one_hot_labels = tf.one_hot( tf.cast(labels['finetune'], tf.int64), target_num_classes) target_one_hot_labels = tf.one_hot( tf.cast(labels['target'], tf.int64), target_num_classes) with tf.variable_scope('rl_controller') as rl_scope: # It creates a `rl_scope` which will be used for ops. pass rl_entropy, label_weights, log_prob = rl_label_weights(rl_scope) loss_entropy, loss_weights, loss_log_prob = get_loss_weights(rl_scope) def gather_init_weights():
tensorflow.cast
8,520
from tensorflow.python.framework import ops returned_dims = [] if keep_dims: for i, dim in enumerate(input_shape.dims): if i in reduction_indices: returned_dims.append(1) else: returned_dims.append(dim) else: for i, dim in enumerate(input_shape.dims): if i not in reduction_indices: returned_dims.append(dim) return [tensor_shape.TensorShape(returned_dims)] @ops.RegisterShape("SegmentMax") @ops.RegisterShape("SegmentMean") @ops.RegisterShape("SegmentMin") @ops.RegisterShape("SegmentProd") @ops.RegisterShape("SegmentSum") def _SegmentReductionShape(op): """Common shape function for segment reduction ops.""" data_shape = op.inputs[0].get_shape() segment_ids_shape = op.inputs[1].get_shape() segment_ids_shape.assert_has_rank(1) return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])] @ops.RegisterShape("SparseSegmentMean") @ops.RegisterShape("SparseSegmentSum")
tensorflow.python.framework.ops.RegisterShape
8,521
import tensorflow as tf init_b = tf.constant_initializer(0.01) with tf.variable_scope('l1'): n_l1 = 700 # combine the action and states together in this way w1_s = tf.get_variable('w1_s', [self.s_dim, n_l1], initializer=init_w, trainable=trainable) w1_a = tf.get_variable('w1_a', [self.a_dim, n_l1], initializer=init_w, trainable=trainable) b1 = tf.get_variable('b1', [1, n_l1], initializer=init_b, trainable=trainable) net = tf.nn.relu(tf.matmul(s, w1_s) + tf.matmul(a, w1_a) + b1) with tf.variable_scope('l2'): net = tf.layers.dense(net, 20, activation=tf.nn.relu, kernel_initializer=init_w, bias_initializer=init_b, name='l2', trainable=trainable) with tf.variable_scope('q'): q = tf.layers.dense(net, 1, kernel_initializer=init_w, bias_initializer=init_b, trainable=trainable) # Q(s,a) return q
tensorflow.matmul
8,522
import tensorflow as tf hparams, tf.estimator.ModeKeys.TRAIN ) try: num_target_frames = hparams.video_num_target_frames except AttributeError: num_target_frames = 1 target_value_shape_suffix = [num_target_frames] if distributional_size > 1: target_value_shape_suffix = [num_target_frames, distributional_size] features = { "inputs": observations, "epoch": tf.constant(epoch + 1), "input_action": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "input_reward": tf.zeros(obs_shape[:2] + [1], dtype=tf.int32), "targets": tf.zeros(obs_shape[:1] + [num_target_frames] + obs_shape[2:]), "target_action": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_reward": tf.zeros( obs_shape[:1] + [num_target_frames, 1], dtype=tf.int32), "target_policy": tf.zeros( obs_shape[:1] + [num_target_frames] + [action_space.n]), "target_value": tf.zeros( obs_shape[:1] + target_value_shape_suffix) } model.distributional_value_size = max(distributional_size, 1) model.use_epochs = hparams.use_epochs with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): t2t_model.create_dummy_vars() (targets, _) = model(features) target_values = targets["target_value"][:, 0]
tensorflow.zeros
8,523
import tensorflow as tf if self.n_step: q_backup_n = tf.stop_gradient( self.rewards_ph_n + (1 - self.terminals_ph_n) *( self.gamma**self.n_step_length ) * self.value_target_n) qf1_loss_n = 0.5 * tf.reduce_mean(((q_backup_n - qf1) ** 2)*self.weight_ph) qf1_loss_n_col = tf.reduce_mean(((q_backup_n - qf1) ** 2),1) qf2_loss_n = 0.5 * tf.reduce_mean(((q_backup_n - qf2) ** 2)*self.weight_ph) if self.n_step:
tensorflow.reduce_mean
8,524
import tensorflow as tf tf.less_equal(x0, max_x) & tf.greater_equal(x0, 0)) x1_valid = tf.to_float( tf.less_equal(x1, max_x) & tf.greater_equal(x1, 0)) y0_valid = tf.to_float(
tensorflow.greater_equal
8,525
import tensorflow as tf eval_file = os.path.join(FLAGS.output_dir, "eval.tf_record") file_based_convert_examples_to_features( eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file) tf.logging.info("***** Running evaluation *****") tf.logging.info(" Num examples = %d (%d actual, %d padding)", len(eval_examples), num_actual_eval_examples, len(eval_examples) - num_actual_eval_examples)
tensorflow.logging.info
8,526
import tensorflow as tf # print('vnet scope T/R', is_train, reuse_unet) encoderscope = 'unet_enc' decoderscope = 'unet_dec' reuse_encoder = reuse_unet reuse_decoder = reuse_unet print([encoderscope, ' ', decoderscope]) # ===============================================================================ENCODER with tf.variable_scope(encoderscope) as scope: if reuse_encoder: scope.reuse_variables() with tf.variable_scope('color_encoder'): X = encoder_conf('eI', I[:, :, :, :-1], 96, 5, 1, norm, reuse_encoder, is_train, self.args.dropout) # 128 > 124 X0 = encoder_conf('d0', X, 96, 2, 2, norm, reuse_encoder, is_train, self.args.dropout) # 124 > 62 @2 X = encoder_conf('e1', X0, 128, 3, 1, norm, reuse_encoder, is_train, self.args.dropout) # 62 > 60 X_EARLY = X X1 = encoder_conf('d1', X, 128, 2, 2, norm, reuse_encoder, is_train, self.args.dropout) # 60 > 30 @4
tensorflow.variable_scope
8,527
import tensorflow as tf raise ValueError('split name %s was not recognized.' % split_name) file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if reader is None: reader = tf.TFRecordReader # Features in Pascal VOC TFRecords. keys_to_features = { 'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'), 'image/height': tf.FixedLenFeature([1], tf.int64), 'image/width': tf.FixedLenFeature([1], tf.int64), 'image/channels': tf.FixedLenFeature([1], tf.int64), 'image/shape': tf.FixedLenFeature([3], tf.int64), 'image/object/bbox/xmin': tf.VarLenFeature(dtype=tf.float32), 'image/object/bbox/ymin': tf.VarLenFeature(dtype=tf.float32),
tensorflow.FixedLenFeature
8,528
from tensorflow.python.framework import ops as _ops def __init__(self, dtype, shape, send_device, recv_device, name=None): """Construct a channel. Args: dtype: The dtype of tensors sent through the channel. shape: The shape of tensors sent through the channel. Must be a fully defined shape for TPUs. send_device: A fully-specified tensorflow device. recv_device: A fully-specified tensorflow device. name: A name for the channel (optional). """ current_graph = _ops.get_default_graph() assert current_graph, "A channel is scoped within a tf.Graph" self._dtype = dtype self._send_device = send_device self._recv_device = recv_device self._name = current_graph.unique_name(name if name else "channel") assert shape is not None shape = _tensor_shape.TensorShape(shape) self._shape = shape
tensorflow.python.framework.ops.get_default_graph
8,529
import tensorflow as tf def decode_needs_input_shape(self): """See base class.""" return False def get_params(self): """See base class.""" return {}, {} def encode(self, x, encode_params): """See base class.""" del encode_params # Unused. return {self.ENCODED_VALUES_KEY: x + tf.sign(tf.random.normal(tf.shape(x)))} def decode(self, encoded_tensors, decode_params, num_summands=None, shape=None): """See base class.""" del decode_params # Unused. del num_summands # Unused. del shape # Unused.
tensorflow.shape
8,530
from tensorflow.python.ops import math_ops logits, array_ops.reshape(target, [-1])) if weight_tensor is None: return math_ops.reduce_mean(loss_vec, name="loss") else: loss_vec = array_ops.reshape(loss_vec, shape=(-1,)) loss_vec = math_ops.mul( loss_vec, array_ops.reshape(weight_tensor, shape=(-1,))) return math_ops.div( math_ops.reduce_sum(loss_vec), math_ops.to_float(math_ops.reduce_sum(weight_tensor)), name="loss") def _get_linear_vars(self): if self._get_linear_feature_columns(): return ops.get_collection(self._linear_weight_collection) return [] def _get_linear_training_ops(self, linear_grads, linear_vars): if self._get_linear_feature_columns():
tensorflow.python.ops.math_ops.reduce_sum
8,531
import tensorflow as tf output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op, scaffold_fn=scaffold_fn) elif mode == tf.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, label_ids, logits): predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) accuracy = tf.metrics.accuracy(label_ids, predictions) loss = tf.metrics.mean(per_example_loss) return { "eval_accuracy": accuracy, "eval_loss": loss, } eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
tensorflow.argmax
8,532
import tensorflow as tf data: Data_loader object to interact with dataset. config: Config object to store data related to training, testing and validation. logger: Logger object to use tensorboard. """ def __init__(self, sess, model, data, config, logger): self.model = model self.config = config self.sess = sess self.data = data self.logger = logger if not self.config.pretrain: # If not pretrain then initialize variables. self.init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) self.sess.run(self.init) def train(self): """Train the model for the number of epochs in config.num_epochs. Calls validate_epoch if config.use_val is set to true and per config.val_per_epoch. Returns: """ for cur_epoch in range(self.model.cur_epoch_tensor.eval(self.sess), self.config.num_epochs + 1, 1): self.data.prepare_new_epoch_data() self.train_epoch()
tensorflow.local_variables_initializer
8,533
from tensorflow.python.ops import math_ops # 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:
tensorflow.python.ops.math_ops.to_int64
8,534
from tensorflow.python.ops import gen_nn_ops """ with ops.op_scope([value, bias], name, "BiasAdd") as name: value = ops.convert_to_tensor(value, name="input") bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias") return gen_nn_ops._bias_add(value, bias, data_format=data_format, name=name) ops.RegisterShape("BiasAdd")(common_shapes.bias_add_shape)
tensorflow.python.ops.gen_nn_ops._bias_add
8,535
from tensorflow.python.training import training as train Raises: ValueError: if: * `loss` is an invalid type or shape. * `global_step` is an invalid type or shape. * `learning_rate` is an invalid type or value. * `optimizer` has the wrong type. * `clip_gradients` is neither float nor callable. * `learning_rate` and `learning_rate_decay_fn` are supplied, but no `global_step` is available. * `gradients` is empty. """ loss = ops.convert_to_tensor(loss) contrib_framework.assert_scalar(loss) if global_step is None: global_step = train.get_global_step() else: train.assert_global_step(global_step) with vs.variable_scope(name, "OptimizeLoss", [loss, global_step]): # Update ops take UPDATE_OPS collection if not provided. if update_ops is None: update_ops = set(ops.get_collection(ops.GraphKeys.UPDATE_OPS)) # Make sure update ops are ran before computing loss. if update_ops: loss = control_flow_ops.with_dependencies(list(update_ops), loss) # Learning rate variable, with possible decay. lr = None if learning_rate is not None:
tensorflow.python.training.training.get_global_step
8,536
import tensorflow as tf x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor in one hot form, the nearest neighbor itself, the commitment loss, embedding training loss. """ x_means_hot = self.nearest_neighbor(x, means) x_means_hot_flat = tf.reshape( x_means_hot, [-1, self.hparams.num_blocks, self.hparams.block_v_size]) x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means) x_means = tf.transpose(x_means, [1, 0, 2]) q_loss = tf.reduce_mean( tf.squared_difference(tf.stop_gradient(x), x_means)) e_loss = tf.reduce_mean( tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, x_means, q_loss, e_loss def bit_to_int(self, x_bit, num_bits, base=2): """Turn x_bit representing numbers bitwise (lower-endian) to int tensor. Args: x_bit: Tensor containing numbers in a particular base to be
tensorflow.transpose
8,537
import tensorflow as tf 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')
tensorflow.layers.dense
8,538
import tensorflow as tf self.assertEqual( tf.train.latest_checkpoint(self.get_temp_dir()), os.path.join(self.get_temp_dir(), "sharded-?????-of-00002")) def testSaverDef(self): with self.test_session(): v0 = tf.Variable(123, name="v0") save = tf.train.Saver({"v0": v0}, sharded=True) sd = save.as_saver_def() self.assertTrue(sd.sharded) class MaxToKeepTest(tf.test.TestCase):
tensorflow.Variable
8,539
import tensorflow as tf #Construct predictions image = tf.placeholder(tf.float32,shape=[hps.batch_size, image_size, image_size, num_channel])############MNIST and CIFAR10 are different ar here adv_image = tf.placeholder(tf.float32,shape=[hps.batch_size, image_size, image_size, num_channel])############MNIST and CIFAR10 are different ar here predict = tf.placeholder(tf.float32,shape=[hps.batch_size, 10]) logit_nor,tsne_logit_nor = model_carlini_adv.predict(image,tsne_logits=True) logit_adv,tsne_logit_adv = model_carlini_adv.predict(adv_image,tsne_logits=True) predict_nor = tf.nn.softmax(logit_nor) predict_adv = tf.nn.softmax(logit_adv) # Calculate entropy argmax_y_onehot = tf.one_hot(tf.argmax(predict, 1), 10, on_value=0.0, off_value=1.0, axis=-1) normalized_y_nonmaximal = tf.reduce_sum(predict * argmax_y_onehot, 1) entropy = tf.reduce_sum(-tf.log(predict) * predict * argmax_y_onehot,1) / normalized_y_nonmaximal + tf.log(normalized_y_nonmaximal) for k in range(1): result_dict = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_for_attack_' + f1 + '.mat') result_dict_median = loadmat('kernel_para_'+FLAGS.dataset+'/kernel1000_median_for_attack_' + f1 + '.mat')
tensorflow.nn.softmax
8,540
import tensorflow as tf initializer=modeling.create_initializer(bert_config.initializer_range)) output_bias = tf.get_variable( "output_bias", shape=[2], initializer=tf.zeros_initializer()) logits = tf.matmul(input_tensor, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) log_probs = tf.nn.log_softmax(logits, axis=-1) labels = tf.reshape(labels, [-1]) one_hot_labels = tf.one_hot(labels, depth=2, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, log_probs) def gather_indexes(sequence_tensor, positions): """Gathers the vectors at the specific positions over a minibatch.""" sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3) batch_size = sequence_shape[0]
tensorflow.reduce_sum
8,541
import tensorflow as tf cell_drop=tf.contrib.rnn.DropoutWrapper(gru,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) else: if activation == 'linear': cell_basic = tf.contrib.rnn.BasicRNNCell(state_size,activation=tf.identity) cell_drop=tf.contrib.rnn.DropoutWrapper(cell_basic,variational_recurrent=True,dtype=tf.float32, input_size=num_input,input_keep_prob=input_prob,state_keep_prob=state_prob) elif activation == 'relu': cell_basic = tf.contrib.rnn.BasicRNNCell(state_size, activation=tf.nn.relu) cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32, input_size=num_input, input_keep_prob=input_prob, state_keep_prob=state_prob) else: #tanh by default cell_basic = tf.contrib.rnn.BasicRNNCell(state_size) cell_drop = tf.contrib.rnn.DropoutWrapper(cell_basic, variational_recurrent=True, dtype=tf.float32, input_size=num_input, input_keep_prob=input_prob, state_keep_prob=state_prob)
tensorflow.contrib.rnn.DropoutWrapper
8,542
import tensorflow as tf tt_rank = tt_rank.astype(int) # Empirically entries of a TT tensor with cores initialized from N(0, 1) # will have variances np.prod(tt_rank) and mean 0. # We scale each TT-core to obtain the desired stddev cr_exponent = -1.0 / (2 * num_dims) var = np.prod(tt_rank ** cr_exponent) core_stddev = stddev ** (1.0 / num_dims) * var with tf.name_scope(name): tt = tensor_with_random_cores(shape, tt_rank=tt_rank, stddev=core_stddev, dtype=dtype) if np.abs(mean) < 1e-8: return tt else: raise NotImplementedError('non-zero mean is not supported yet')
tensorflow.name_scope
8,543
import tensorflow as tf num_to_add = int(max(self.batch_size/self.num_angles, 1)) idx = tf.range(0, self.batch_size, 1) idx = tf.random_shuffle(idx)[0:num_to_add] self.fake_to_add = tf.gather(self.generator_out, idx) self.mixed_pc = tf.concat([self.real_pc_rotated, self.fake_to_add], 0) self.mixed_label = tf.concat([self.rot_label_pl, tf.constant(self.num_angles, shape = (num_to_add,))], axis = 0) mixed_idx = tf.range(0, self.mixed_label.get_shape().as_list()[0], 1) mixed_idx = tf.random_shuffle(mixed_idx)[0:self.batch_size] self.mixed_pc = tf.gather(self.mixed_pc, mixed_idx) self.mixed_label = tf.gather(self.mixed_label, mixed_idx) self.mixed_pred, mixed_end_points = self.get_pred(self.mixed_pc) self.mixed_loss = self.get_loss(self.mixed_pred, self.mixed_label, mixed_end_points)
tensorflow.random_shuffle
8,544
import tensorflow as tf # Check that the parameter nodes have been restored. self.assertEqual(10.0, v0_2.eval()) self.assertEqual(20.0, v1_2.eval()) def testInt64(self): save_path = os.path.join(self.get_temp_dir(), "int64") with self.test_session() as sess: # Build a graph with 1 node, and save and restore for them. v = tf.Variable(np.int64(15), name="v") save = tf.train.Saver({"v": v}, restore_sequentially=True) tf.initialize_all_variables().run() # Save the initialized values in the file at "save_path" val = save.save(sess, save_path) self.assertTrue(isinstance(val, six.string_types)) self.assertEqual(save_path, val) with self.test_session() as sess: v = tf.Variable(np.int64(-1), name="v") save = tf.train.Saver({"v": v})
tensorflow.initialize_all_variables
8,545
import tensorflow as tf w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5]) with tf.variable_scope("proj_seq2seq"): dec, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] with tf.variable_scope("other"): d3, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() d1, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) d2, _ = tf.nn.seq2seq.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True)
tensorflow.variable_scope
8,546
import tensorflow as tf def update(self, labeled_sdfs, labeled_classes, labeled_poses, predicted_sdfs, predicted_classes, predicted_poses): """Update.""" labeled_rotations = labeled_poses[0] labeled_translations = labeled_poses[1] labeled_sizes = labeled_poses[2] status = True if status: box_limits_x = [100, -100] # box_limits_y = [100, -100] box_limits_z = [100, -100] for i in range(labeled_translations.shape[0]): rot = tf.reshape(tf.gather(labeled_rotations[i], [0, 2, 6, 8]), [2, 2]) min_x = tf.cast(0.0 - labeled_sizes[i][0] / 2.0, dtype=tf.float32) max_x = tf.cast(0.0 + labeled_sizes[i][0] / 2.0, dtype=tf.float32) # min_y = tf.cast(0.0 - labeled_sizes[i][1] / 2.0, dtype=tf.float32) # max_y = tf.cast(0.0 + labeled_sizes[i][1] / 2.0, dtype=tf.float32) min_z = tf.cast(0.0 - labeled_sizes[i][2] / 2.0, dtype=tf.float32) max_z = tf.cast(0.0 + labeled_sizes[i][2] / 2.0, dtype=tf.float32) translation = tf.reshape([labeled_translations[i][0], labeled_translations[i][2]], [2, 1]) pt_0 = rot @ tf.reshape([min_x, min_z], [2, 1]) + translation
tensorflow.gather
8,547
import tensorflow as tf tgt_dif = tgt_flat1 - tgt_flat2 pred_dif = pred_flat1 - pred_flat2 geq = tf.cast(tgt_dif > 0, tf.bool) # tgt_posi_dif = tf.where(geq, tgt_dif, -tgt_dif) pred_posi_dif = tf.where(geq, pred_dif, -pred_dif) loss = tf.maximum(0., margin-pred_posi_dif) cstr_pct = tf.math.count_nonzero(loss, dtype=tf.float32) / tf.cast(tf.reduce_prod(tf.shape(loss)), tf.float32)
tensorflow.where
8,548
from tensorflow.contrib.framework import tensor_util update_op: `Operation` that increments `true_positives` and `false_negatives` variables appropriately and whose value matches `recall`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, or if `ignore_mask` is not `None` and its shape doesn't match `predictions`, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope(name, 'recall', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) weights = _mask_weights(ignore_mask, weights) true_positives, true_positives_update_op = _streaming_true_positives( predictions, labels, weights, metrics_collections=None, updates_collections=None, name=None) false_negatives, false_negatives_update_op = _streaming_false_negatives( predictions, labels, weights, metrics_collections=None, updates_collections=None, name=None)
tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions
8,549
import tensorflow as tf word_emb = lm_embeddings["word_emb"] # [num_sentences, max_sentence_length, 512] lm_emb = tf.stack([tf.concat([word_emb, word_emb], -1), lm_embeddings["lstm_outputs1"], lm_embeddings["lstm_outputs2"]], -1) # [num_sentences, max_sentence_length, 1024, 3] lm_emb_size = util.shape(lm_emb, 2) lm_num_layers = util.shape(lm_emb, 3) with tf.variable_scope("lm_aggregation"): self.lm_weights = tf.nn.softmax(tf.get_variable("lm_scores", [lm_num_layers], initializer=tf.constant_initializer(0.0))) self.lm_scaling = tf.get_variable("lm_scaling", [], initializer=tf.constant_initializer(1.0)) flattened_lm_emb = tf.reshape(lm_emb, [num_sentences * max_sentence_length * lm_emb_size, lm_num_layers]) flattened_aggregated_lm_emb = tf.matmul(flattened_lm_emb, tf.expand_dims(self.lm_weights, 1)) # [num_sentences * max_sentence_length * emb, 1] aggregated_lm_emb = tf.reshape(flattened_aggregated_lm_emb, [num_sentences, max_sentence_length, lm_emb_size])
tensorflow.variable_scope
8,550
import tensorflow as tf if mode == tf.estimator.ModeKeys.EVAL: batch_size = features['images'].shape[0].value assert batch_size == 1 evaluator = Evaluator(num_classes=params['num_classes']) eval_metric_ops = evaluator.get_metric_ops(labels, predictions) return tf.estimator.EstimatorSpec( mode, loss=total_loss, eval_metric_ops=eval_metric_ops ) assert mode == tf.estimator.ModeKeys.TRAIN with tf.variable_scope('learning_rate'): global_step = tf.train.get_global_step() learning_rate = tf.train.cosine_decay( params['initial_learning_rate'], global_step, decay_steps=params['num_steps'] ) tf.summary.scalar('learning_rate', learning_rate) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(update_ops), tf.variable_scope('optimizer'): optimizer = tf.train.AdamOptimizer(learning_rate) grads_and_vars = optimizer.compute_gradients(total_loss) train_op = optimizer.apply_gradients(grads_and_vars, global_step) for g, v in grads_and_vars: tf.summary.histogram(v.name[:-2] + '_hist', v)
tensorflow.train.get_global_step
8,551
import tensorflow as tf context, alpha = self._attention_layer(features, features_proj, h, reuse=(t!=0)) alpha_list.append(alpha) if self.selector: context, beta = self._selector(context, h, reuse=(t!=0)) beta_list.append(beta) with tf.variable_scope('lstm', reuse=(t!=0)): _, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x, context]), state=[c, h]) logits = self._decode_lstm(x, h, context, reuse=(t!=0)) sampled_word = tf.argmax(logits, 1) sampled_word_list.append(sampled_word) alphas = tf.transpose(tf.stack(alpha_list), (1, 0, 2)) # (N, T, L) betas = tf.transpose(tf.squeeze(beta_list), (1, 0)) # (N, T) sampled_captions = tf.transpose(tf.stack(sampled_word_list), (1, 0)) # (N, max_len)
tensorflow.concat
8,552
import tensorflow as tf flags.DEFINE_float( "warmup_proportion", 0.1, "Proportion of training to perform linear learning rate warmup for. " "E.g., 0.1 = 10% of training.") flags.DEFINE_integer("save_checkpoints_steps", 1000, "How often to save the model checkpoint.") flags.DEFINE_integer("iterations_per_loop", 1000, "How many steps to make in each estimator call.") flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") tf.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") tf.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string(
tensorflow.flags.DEFINE_string
8,553
import tensorflow as tf if clone_losses: clone_loss = tf.add_n(clone_losses, name='clone_loss') if num_clones > 1: clone_loss = tf.div(clone_loss, 1.0 * num_clones, name='scaled_clone_loss') all_losses.append(clone_loss) if regularization_losses: regularization_loss = tf.add_n(regularization_losses, name='regularization_loss') all_losses.append(regularization_loss) if all_losses: sum_loss = tf.add_n(all_losses) # Add the summaries out of the clone device block. if clone_loss is not None: tf.summary.scalar('clone_loss', clone_loss) # tf.summary.scalar(clone.scope + '/clone_loss', clone_loss) if regularization_loss is not None: tf.summary.scalar('regularization_loss', regularization_loss) return sum_loss def _optimize_clone(optimizer, clone, num_clones, regularization_losses,
tensorflow.add_n
8,554
import tensorflow as tf for i in range(self.config["coref_depth"]): with tf.variable_scope("coref_layer", reuse=(i > 0)): top_antecedent_emb = tf.gather(top_span_emb, top_antecedents) # [k, c, emb] top_antecedent_scores = top_fast_antecedent_scores + self.get_slow_antecedent_scores(top_span_emb, top_antecedents, top_antecedent_emb, top_antecedent_offsets, top_span_speaker_ids, genre_emb) # [k, c]
tensorflow.gather
8,555
import tensorflow as tf dataset = dataset.map(concat_and_add_mask) return dataset @gin.configurable(module='trax.data', denylist=['dataset', 'training']) def lm_token_preprocessing(dataset, training): """Concatenates inputs, 0, targets, with masking only for targets.""" del training def concat_and_add_mask(x): inp = x['inputs'] targets = x['targets'] pad = tf.expand_dims(tf.zeros_like(inp[0]), axis=0) concat = tf.concat([inp, pad, targets], axis=0) mask = tf.concat([tf.zeros_like(inp), pad, tf.ones_like(targets)], axis=0) x['inputs'] = concat x['targets'] = concat x['mask'] = mask return x dataset = dataset.map(concat_and_add_mask) return dataset @gin.configurable(module='trax.data', denylist=['hparams']) def bair_robot_pushing_hparams(hparams=None, video_num_input_frames=1,
tensorflow.concat
8,556
import tensorflow as tf :return: does not return anything """ # Reconstruction Phase with tf.variable_scope(tf.get_variable_scope()): encoder_output_label, encoder_output_latent = encoder(x_input) # Concat class label and the encoder output decoder_input = tf.concat([encoder_output_label, encoder_output_latent], 1)
tensorflow.get_variable_scope
8,557
import tensorflow as tf self.mixed_pred, mixed_end_points = self.get_pred(self.mixed_pc) self.mixed_loss = self.get_loss(self.mixed_pred, self.mixed_label, mixed_end_points) with tf.variable_scope('discriminator') as scope: self.real_prob, self.real_logit = self.discriminator(self.real_pc_rotated, scope=scope, **disc_kwargs) self.synthetic_prob, self.synthetic_logit = self.discriminator(self.gen_out_rotated, reuse=True, scope=scope, **disc_kwargs) # Compute WGAN losses self.loss_d = tf.reduce_mean(self.synthetic_logit) - tf.reduce_mean(self.real_logit) # comparing rotated fake and real images self.loss_g = -tf.reduce_mean(self.synthetic_logit) # Add rotation loss if self.ms_task: self.g_ms_loss = tf.abs(self.gen_out_rot_loss - self.real_pc_rot_loss, name = 'abs') self.d_ms_loss = self.mixed_loss self.loss_d_rot = self.loss_d + self.weight_rotation_loss_d * self.d_ms_loss self.loss_g_rot = self.loss_g + self.weight_rotation_loss_g * self.g_ms_loss
tensorflow.reduce_mean
8,558
import tensorflow as tf self._plot_model_hooks_kwargs = {"time_reference" : self._time_reference_str, "plot_offset": self._plot_offset} self._n_steps_stats = self._get_steps(config["stats_period"], self._time_reference_str) # stop hook tot_steps = int(self._opts['epochs']+1)*self.n_batches_per_epoch hooks.append(tf.train.StopAtStepHook(last_step=tot_steps)) # general info hook (no average on validation but only on train loop) hooks.append(self._create_general_info_hook(config)) # regularizers hook (no average on validation but only on train loop) hooks.append(self._create_regularizers_hook(config))
tensorflow.train.StopAtStepHook
8,559
from tensorflow.python.framework import ops Dimensions typically: batch, out_units. """ with ops.op_scope([x, weights, biases], name, "xw_plus_b") as name: x = ops.convert_to_tensor(x, name="x") weights = ops.convert_to_tensor(weights, name="weights") biases = ops.convert_to_tensor(biases, name="biases")
tensorflow.python.framework.ops.convert_to_tensor
8,560
import tensorflow as tf tf.less_equal(y0, max_y) & tf.greater_equal(y0, 0)) y1_valid = tf.to_float( tf.less_equal(y1, max_y) & tf.greater_equal(y1, 0)) z0_valid = tf.to_float(
tensorflow.greater_equal
8,561
import tensorflow as tf facts = tf.array_ops.transpose(facts, [1, 0, 2]) mask = tf.equal(mask, tf.ones_like(mask)) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] queries = tf.tile(query, [1, tf.shape(facts)[1]]) queries = tf.reshape(queries, tf.shape(facts)) din_all = tf.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = tf.layers.dense(din_all, 80, activation=tf.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, 40, activation=tf.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = tf.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = tf.reshape(d_layer_3_all, [-1, 1, tf.shape(facts)[1]]) scores = d_layer_3_all
tensorflow.concat
8,562
import tensorflow as tf relevant example. propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element. name: A string used as the name for this variable scope. Returns: (tf.Tensor) A single value tensor containing the loss. """ loss = None with tf.name_scope(name, "click_softmax_cross_entropy",[output]): label_dis = labels*propensity_weights / tf.reduce_sum(labels*propensity_weights, 1, keep_dims=True) loss = tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=label_dis) * tf.reduce_sum(labels*propensity_weights, 1) return tf.reduce_sum(loss) / tf.reduce_sum(labels*propensity_weights) def click_loglikelihood(self, labels, propensity,train_output, name=None): """Computes listwise softmax loss with propensity weighting. Args: output: (tf.Tensor) A tensor with shape [batch_size, list_size]. Each value is the ranking score of the corresponding example. labels: (tf.Tensor) A tensor of the same shape as `output`. A value >= 1 means a relevant example. propensity_weights: (tf.Tensor) A tensor of the same shape as `output` containing the weight of each element.
tensorflow.reduce_sum
8,563
import tensorflow as tf Variable Tensor """ if use_xavier: initializer = tf.contrib.layers.xavier_initializer() var = _variable_on_cpu(name, shape, initializer) else: # initializer = tf.truncated_normal_initializer(stddev=stddev) with tf.device('/cpu:0'): var = tf.truncated_normal(shape, stddev=np.sqrt(2 / shape[-1])) var = tf.round(var * tf.constant(1000, dtype=tf.float32)) / tf.constant(1000, dtype=tf.float32) var = tf.Variable(var, name='weights') if wd is not None: weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss') tf.add_to_collection('losses', weight_decay) return var def conv1d(inputs,
tensorflow.constant
8,564
from tensorflow.python.framework import ops node.input[1]) filter_shape.assert_is_fully_defined() output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) output_shape.assert_is_fully_defined() filter_height = int(filter_shape[0]) filter_width = int(filter_shape[1]) filter_in_depth = int(filter_shape[2]) output_count = np.prod(output_shape.as_list()) return ops.OpStats("flops", (output_count * filter_in_depth * filter_height * filter_width * 2)) @ops.RegisterStatistics("Conv2D", "weight_parameters") def _calc_conv_weight_params(graph, node): """Calculates the on-disk size of the weights for Conv2D.""" input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0]) input_shape.assert_is_fully_defined() filter_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1]) filter_shape.assert_is_fully_defined() output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name) output_shape.assert_is_fully_defined() filter_height = int(filter_shape[0]) filter_width = int(filter_shape[1])
tensorflow.python.framework.ops.RegisterStatistics
8,565
import tensorflow as tf else: return 0 # For ACER def get_by_index(x, idx): assert(len(x.get_shape()) == 2) assert(len(idx.get_shape()) == 1) idx_flattened = tf.range(0, x.shape[0]) * x.shape[1] + idx y = tf.gather(tf.reshape(x, [-1]), # flatten input idx_flattened) # use flattened indices return y def check_shape(ts,shapes): i = 0 for (t,shape) in zip(ts,shapes): assert t.get_shape().as_list()==shape, "id " + str(i) + " shape " + str(t.get_shape()) + str(shape) i += 1
tensorflow.reshape
8,566
import tensorflow as tf 0: self._add_separable_conv_3x3_op, 1: self._add_separable_conv_5x5_op, 2: self._add_avg_pool_3x3_op, 3: self._add_max_pool_3x3_op, 4: self._add_identity_op, 5: self._add_separable_conv_7x7_op } def _add_avg_pool_3x3_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): filter_size = 3 stride = 2 if is_reduction else 1 with tf.variable_scope('avg_pool_3x3_op'): X = tf.nn.avg_pool(X, ksize=(1, filter_size, filter_size, 1), strides=[1, stride, stride, 1], padding='SAME') X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X def _add_identity_op(self, X, input_idx, ni, w, h, ch, is_reduction, is_dynamic, is_train): stride = 2 if is_reduction else 1 with tf.variable_scope('identity_op'): # If stride > 1, calibrate, else, just return itself if stride > 1: X = self._calibrate(X, w, h, ch, w // stride, h // stride, ch, is_train=is_train) X = tf.reshape(X, (-1, w // stride, h // stride, ch)) # Sanity shape check return X
tensorflow.nn.avg_pool
8,567
import tensorflow as tf span_attention = tf.nn.softmax(span_head_scores, 1) # [k, max_span_width, 1] span_head_emb = tf.reduce_sum(span_attention * span_text_emb, 1) # [k, emb] span_emb_list.append(span_head_emb) span_emb = tf.concat(span_emb_list, 1) # [k, emb] return span_emb # [k, emb] def get_mention_scores(self, span_emb):
tensorflow.concat
8,568
import tensorflow as tf axis=0) # operation of choosing action # 更新 self.update_old_action_op_op = [ olda.assign(a) for a, olda in zip( action_op_params, old_action_op_params)] # 定義輸入變數 self.tfa = tf.placeholder(tf.float32, [None, action_dim], 'action') self.tfadv = tf.placeholder(tf.float32, [None, 1], 'advantage') # 機率比較 ratio = action_op.prob(self.tfa) / \ (old_action_op.prob(self.tfa) + 1e-5) # 替代損失
tensorflow.placeholder
8,569
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
8,570
import tensorflow as tf if head is not None: cross_entropy = -tf.reduce_sum(tf.mul(labels * tf.log(softmax), head), axis=[1])
tensorflow.log
8,571
import tensorflow.contrib as contrib 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, normalizer_params={ "is_training": is_training, "scale": True,
tensorflow.contrib.layers.variance_scaling_initializer
8,572
import tensorflow as tf self.Y_hat = training_decoder_output.rnn_output out_decoder2 = tf.reshape(self.Y_hat, [tf.shape(self.Y_hat)[0], -1, n_mels])
tensorflow.shape
8,573
from tensorflow.python.ops import array_ops return [tensor_shape.vector(None)] else: return [tensor_shape.vector((limit_value - start_value + delta_value - 1) // delta_value)] # Reduction operations def _ReductionDims(x, reduction_indices): """Returns range(0, rank(x)) if reduction_indices is None.""" if reduction_indices is not None: return reduction_indices else: return range(0, array_ops.rank(x)) def reduce_sum(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the sum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1.
tensorflow.python.ops.array_ops.rank
8,574
import tensorflow as tf trainable=False) # Loss value reg_item = tf.contrib.layers.l1_l2_regularizer(L1_reg, L2_reg) reg_term = tf.contrib.layers.apply_regularization(reg_item, self.nnweights) loss_fun = self._negative_log_likelihood(y_, y) loss = loss_fun + reg_term # SGD Optimizer if optimizer == 'sgd': lr = tf.train.exponential_decay( learning_rate, global_step, 1, learning_rate_decay ) train_step = tf.train.GradientDescentOptimizer(lr).minimize(loss, global_step=global_step) elif optimizer == 'adam': train_step = tf.train.GradientDescentOptimizer(learning_rate).\ minimize(loss, global_step=global_step) else: raise NotImplementedError('activation not recognized') # init op init_op = tf.global_variables_initializer() # Save into class members self.X = X self.y_ = y_ self.y = y self.global_step = global_step self.loss = loss
tensorflow.train.GradientDescentOptimizer
8,575
import tensorflow as tf token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings ) output_layer = model.get_sequence_output() hidden_size = output_layer.shape[-1].value output_weight = 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: output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) output_layer = tf.reshape(output_layer, [-1, hidden_size]) logits = tf.matmul(output_layer, output_weight, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) logits = tf.reshape(logits, [-1, FLAGS.max_seq_length, 11]) log_probs = tf.nn.log_softmax(logits, axis=-1) # labels = tf.cast(labels,dtype=tf.float32) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_sum(per_example_loss) return (loss, per_example_loss, logits)
tensorflow.variable_scope
8,576
import tensorflow as tf processed_image = utils.process_image(image, mean_pixel) with tf.variable_scope("inference"): image_net = vgg_net(weights, processed_image) conv_final_layer = image_net["conv5_3"] pool5 = utils.max_pool_2x2(conv_final_layer) W6 = utils.weight_variable([7, 7, 512, 4096], name="W6") b6 = utils.bias_variable([4096], name="b6") conv6 = utils.conv2d_basic(pool5, W6, b6) relu6 = tf.nn.relu(conv6, name="relu6") if FLAGS.debug: utils.add_activation_summary(relu6) relu_dropout6 = tf.nn.dropout(relu6, keep_prob=keep_prob) W7 = utils.weight_variable([1, 1, 4096, 4096], name="W7") b7 = utils.bias_variable([4096], name="b7") conv7 = utils.conv2d_basic(relu_dropout6, W7, b7) relu7 = tf.nn.relu(conv7, name="relu7") if FLAGS.debug: utils.add_activation_summary(relu7) relu_dropout7 = tf.nn.dropout(relu7, keep_prob=keep_prob)
tensorflow.nn.relu
8,577
import tensorflow as tf with tf.Graph().as_default():
tensorflow.Graph
8,578
import tensorflow as tf var_list = None if self.params["warm_start_dir"]: output_vars1 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="task_dependent") output_vars2 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="task_independent/Variable_1")
tensorflow.get_collection
8,579
import tensorflow as tf losses_eval_test = build_eval_graph(images_eval_test, labels_eval_test, images_eval_test, ul_u_eval_test) init_op = tf.global_variables_initializer()
tensorflow.global_variables_initializer
8,580
import tensorflow as tf action_spec = self._actor.output_tensor_spec states_tiled = tf.tile(states[:, None], [1, num_tasks, 1]) # B x B x D states_tiled = tf.reshape(states_tiled, [batch_size * num_tasks, obs_dim]) # B*B x D actions_tiled = tf.tile(actions[:, None], [1, num_tasks, 1]) # B x B x D actions_tiled = tf.reshape(actions_tiled, [batch_size * num_tasks, action_dim]) # B*B x D tasks_tiled = tf.tile(tasks[None], [batch_size, 1, 1]) # B x B x D tasks_tiled = tf.reshape(tasks_tiled, [batch_size * num_tasks, task_dim]) # B*B x D
tensorflow.reshape
8,581
import tensorflow as tf sc = getOrCreateSparkContext() train_rdd = callBigDlFunc("float", "createRDDFromTFRecords", file_path, sc, serialized_graph, serialized_example.name, output_names) validation_rdd = None if validation_file_path is not None: validation_rdd = callBigDlFunc("float", "createRDDFromTFRecords", validation_file_path, sc, serialized_graph, serialized_example.name, output_names) tensor_structure = nest.pack_sequence_as(results, [TensorMeta(tf.as_dtype(t.dtype), shape=t.shape, name="data_%s" % i) for i, t in enumerate(nest.flatten(results))]) super(TFRecordDataset, self).__init__(tensor_structure, batch_size, batch_per_thread, hard_code_batch_size) self.train_rdd = train_rdd self.validation_rdd = validation_rdd def get_prediction_data(self):
tensorflow.as_dtype
8,582
import tensorflow as tf 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
tensorflow.add_to_collection
8,583
import tensorflow as tf def _SaveAndLoad(self, var_name, var_value, other_value, save_path): with self.test_session() as sess: var = tf.Variable(var_value, name=var_name) save = tf.train.Saver({var_name: var}) var.initializer.run() val = save.save(sess, save_path) self.assertEqual(save_path, val) with self.test_session() as sess: var = tf.Variable(other_value, name=var_name) save = tf.train.Saver({var_name: var}) save.restore(sess, save_path) self.assertAllClose(var_value, var.eval()) def testCacheRereadsFile(self): save_path = os.path.join(self.get_temp_dir(), "cache_rereads") # Save and reload one Variable named "var0". self._SaveAndLoad("var0", 0.0, 1.0, save_path) # Save and reload one Variable named "var1" in the same file. # The cached readers should know to re-read the file.
tensorflow.train.Saver
8,584
import tensorflow as tf # non-linear rep_map = bn_dense_layer(rep_tensor, ivec, True, 0., 'bn_dense_map', activation, False, wd, keep_prob, is_train) # ensure the seletion is right dep_selection = tf.logical_and(rep_mask, dep_selection) head_selection = tf.logical_and(rep_mask, head_selection) rep_dep_tensor, rep_dep_mask, dep_org_idx = reduce_data_rep_max_len(rep_map, dep_selection) rep_head_tensor,rep_head_mask, head_org_idx = reduce_data_rep_max_len(rep_map, head_selection) sl_dep, sl_head = tf.shape(rep_dep_tensor)[1], tf.shape(rep_head_tensor)[1] if keep_unselected: unhead_selection = tf.logical_and(rep_mask, tf.logical_not(head_selection)) rep_unhead_tensor, rep_unhead_mask, unhead_org_idx = reduce_data_rep_max_len(rep_map, unhead_selection) sl_unhead = tf.shape(rep_unhead_tensor)[1] attn_result = tf.cond( tf.equal(sl_head, 0), lambda: tf.zeros([bs, 0, hn], tf.float32), lambda: self_attention_for_selected_head( head_selection, head_org_idx, sl_head, rep_head_mask, dep_selection, dep_org_idx, sl_dep, rep_dep_mask, rep_map, rep_dep_tensor, keep_prob, is_train, direction, ivec ) ) if keep_unselected:
tensorflow.shape
8,585
import tensorflow as tf initializer=tf.constant_initializer(float('nan'))) self.epsilon = epsilon def __call__(self,input_var,name=None,**kwargs) : if( input_var.shape.ndims > 2 ) : dims = tf.reduce_prod(tf.shape(input_var)[1:]) input_var = tf.reshape(input_var,[-1,dims]) def _init(): v_norm = tf.nn.l2_normalize(self.v,axis=0)
tensorflow.shape
8,586
import tensorflow as tf if __name__ == "__main__": flags.mark_flag_as_required("data_dir") flags.mark_flag_as_required("task_name") flags.mark_flag_as_required("vocab_file") flags.mark_flag_as_required("bert_config_file") flags.mark_flag_as_required("output_dir") tf.app.run()
tensorflow.app.run
8,587
import tensorflow as tf bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) if FLAGS.max_seq_length > bert_config.max_position_embeddings: raise ValueError( "Cannot use sequence length %d because the BERT model " "was only trained up to sequence length %d" % (FLAGS.max_seq_length, bert_config.max_position_embeddings)) tf.gfile.MakeDirs(FLAGS.output_dir) task_name = FLAGS.task_name.lower() if task_name not in processors: raise ValueError("Task not found: %s" % (task_name)) processor = processors[task_name]()
tensorflow.gfile.MakeDirs
8,588
import tensorflow as tf indices.active_block_indices, x, dynamic_bsize=tf.constant(block_params.bsize_out, dtype=tf.int32), dynamic_bstride=tf.constant(block_params.bsize_out, dtype=tf.int32), dynamic_boffset=tf.constant([0, 0], dtype=tf.int32), add=True, transpose=transpose) else:
tensorflow.constant
8,589
import tensorflow as tf if anchor_match_mining_distance_matrix is None: anchor_match_mining_distance_matrix = anchor_match_distance_matrix if use_semi_hard: if anchor_positive_mining_distances is None: raise ValueError('Positive match embeddings must be specified to compute ' 'semi-hard distances.') anchor_positive_mining_distances = tf.expand_dims( anchor_positive_mining_distances, axis=-1) indicators &= ( anchor_match_mining_distance_matrix > anchor_positive_mining_distances) def find_hard_distances(distance_matrix, indicator_matrix): distance_matrix = tf.where( tf.stop_gradient(indicator_matrix), distance_matrix, tf.fill(tf.shape(distance_matrix), distance_matrix.dtype.max)) hard_distances = tf.math.reduce_min(distance_matrix, axis=-1) return hard_distances hard_negative_mining_distances = find_hard_distances( anchor_match_mining_distance_matrix, indicators) indicators &= tf.math.equal( anchor_match_mining_distance_matrix, tf.expand_dims(hard_negative_mining_distances, axis=-1)) hard_negative_distances = find_hard_distances(anchor_match_distance_matrix, indicators)
tensorflow.stop_gradient
8,590
import tensorflow as tf def _enqueue_loop(): while True: random.shuffle(train_examples) for example in train_examples: tensorized_example = self.tensorize_example(example, is_training=True) feed_dict = dict(zip(self.queue_input_tensors, tensorized_example)) session.run(self.enqueue_op, feed_dict=feed_dict) enqueue_thread = threading.Thread(target=_enqueue_loop) enqueue_thread.daemon = True enqueue_thread.start() def restore(self, session): # Don't try to restore unused variables from the TF-Hub ELMo module. vars_to_restore = [v for v in tf.global_variables() if "module/" not in v.name] saver = tf.train.Saver(vars_to_restore) checkpoint_path = os.path.join(self.config["log_dir"], "model.max.ckpt") print("Restoring from {}".format(checkpoint_path)) session.run(tf.global_variables_initializer()) saver.restore(session, checkpoint_path) def load_lm_embeddings(self, doc_key): if self.lm_file is None: return np.zeros([0, 0, self.lm_size, self.lm_layers]) file_key = doc_key.replace("/", ":") group = self.lm_file[file_key] num_sentences = len(list(group.keys())) sentences = [group[str(i)][...] for i in range(num_sentences)] lm_emb = np.zeros([num_sentences, max(s.shape[0] for s in sentences), self.lm_size, self.lm_layers])
tensorflow.train.Saver
8,591
import tensorflow as tf tf.reshape(poses[0][i], [1, 1, 3, 3]), tf.reshape(poses[1][i], [1, 1, 3]), inverse=True) * 2.0 samples_object = (samples_object * (29.0/32.0) / 2.0 + 0.5) * 32.0 - 0.5 samples = tf.squeeze(samples_object) interpolated = trilinear.interpolate(sdf, samples) occupancy_value = tf.math.sign(tf.nn.relu(interpolated + self.tol)) sdf_values += occupancy_value intersection = tf.reduce_sum(tf.math.sign(tf.nn.relu(sdf_values - 1))) if intersection > prev_intersection: prev_intersection = intersection num_collisions += 1 status2 = False if status2: a = 1 values = interpolated inter = tf.reshape(values, [self.resolution, self.resolution, self.resolution]) inter = tf.transpose(tf.reduce_max(inter, axis=a)) im = axs[fig_obj_count, 0].matshow(inter.numpy()) plt.colorbar(im, ax=axs[fig_obj_count, 0]) values = tf.math.sign(tf.nn.relu(interpolated + self.tol)) inter = tf.reshape(values, [self.resolution, self.resolution, self.resolution]) inter = tf.transpose(tf.reduce_max(inter, axis=a)) im = axs[fig_obj_count, 1].matshow(inter.numpy()) plt.colorbar(im, ax=axs[fig_obj_count, 1])
tensorflow.reshape
8,592
from tensorflow.python.ops import gen_nn_ops value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`, `int16`, `int8`, or `complex64`. bias: A 1-D `Tensor` with size matching the last dimension of `value`. Must be the same type as `value` unless `value` is a quantized type, in which case a different quantized type may be used. name: A name for the operation (optional). Returns: A `Tensor` with the same type as `value`. """ with ops.op_scope([value, bias], name, "BiasAddV1") as name: value = ops.convert_to_tensor(value, name="input") bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias") return gen_nn_ops._bias_add_v1(value, bias, name=name) ops.RegisterShape("BiasAddV1")(common_shapes.bias_add_shape) ops.RegisterShape("BiasAddGradV1")(common_shapes.bias_add_grad_shape) def relu6(features, name=None): """Computes Rectified Linear 6: `min(max(features, 0), 6)`.
tensorflow.python.ops.gen_nn_ops._bias_add_v1
8,593
import tensorflow as tf lambda: 0.) # On the first step, prev_log_r = 0. log_r = tf.cond( tf.less(t + 1, self.max_seq_len), lambda: self.tilt(rnn_out, latent_encoded, self.targets_ta.read(t+1)), lambda: 0.) # On the last step, log_r = 0. log_r *= tf.to_float(t < self.seq_lengths - 1) weights += log_r - prev_log_r new_state = TrainableVRNNState(rnn_state=next_rnn_state, rnn_out=rnn_out, latent_encoded=latent_encoded) return weights, new_state _DEFAULT_INITIALIZERS = {"w": tf.contrib.layers.xavier_initializer(), "b": tf.zeros_initializer()} def create_vrnn( data_size, latent_size, emission_class, rnn_hidden_size=None, fcnet_hidden_sizes=None, encoded_data_size=None, encoded_latent_size=None, sigma_min=0.0, raw_sigma_bias=0.25,
tensorflow.contrib.layers.xavier_initializer
8,594
import tensorflow as tf ) # Zero out embeddings of pad value masks = tf.not_equal(self.inputs, pad_value, name='masks') word_embeddings *= tf.cast(
tensorflow.not_equal
8,595
import tensorflow as tf fc_size1 = 384 fc_size2 = 192 # convolutional layers with tf.variable_scope('conv1'): layer1, weights1 = new_conv_layer(x, name="conv1", num_input_channels=3, num_filters=64, filter_size=5, ac_fun=tf.nn.relu, pool_ksize=[1, 3, 3, 1]) with tf.variable_scope('conv2'): layer2, weights2 = new_conv_layer(input=layer1, name="conv2", num_input_channels=64, num_filters=64, filter_size=5, ac_fun=tf.nn.relu, pool_ksize=[1, 3, 3, 1]) with tf.name_scope('flatten'): layer3, num_features = flatten_layer(layer2) # fully connected layers with tf.variable_scope('fc1'):
tensorflow.variable_scope
8,596
import tensorflow as tf # In the demo, we are doing a simple classification task on the entire # segment. # # If you want to use the token-level output, use model.get_sequence_output() # 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)
tensorflow.truncated_normal_initializer
8,597
import tensorflow as tf enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test with state_is_tuple=False. with tf.variable_scope("no_tuple"): cell = tf.nn.rnn_cell.BasicLSTMCell(2, state_is_tuple=False) dec, mem = tf.nn.seq2seq.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([tf.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = tf.get_variable("proj_w", [2, 5]) b = tf.get_variable("proj_b", [5])
tensorflow.nn.seq2seq.embedding_attention_seq2seq
8,598
import tensorflow as tf depth_f = tf.to_float(depth) height_f = tf.to_float(height) width_f = tf.to_float(width) # Number of disparity interpolated. out_depth = out_size[0] out_height = out_size[1] out_width = out_size[2] zero = tf.zeros([], dtype='int32') # 0 <= z < depth, 0 <= y < height & 0 <= x < width. max_z = tf.to_int32(tf.shape(im)[1] - 1) max_y = tf.to_int32(tf.shape(im)[2] - 1) max_x = tf.to_int32(tf.shape(im)[3] - 1) # Converts scale indices from [-1, 1] to [0, width/height/depth]. x = (x + 1.0) * (width_f) / 2.0 y = (y + 1.0) * (height_f) / 2.0 z = (z + 1.0) * (depth_f) / 2.0
tensorflow.shape
8,599