seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf return self_attention def self_all_attention(facts, ATTENTION_SIZE, mask, stag='null'): if len(facts.get_shape().as_list()) == 2: facts = tf.expand_dims(facts, 1) def cond(batch, output, i): return tf.less(i, tf.shape(batch)[1])
tensorflow.expand_dims
12,700
import tensorflow as tf bh = tf.get_variable("bh", [nh*4], initializer=tf.constant_initializer(0.0)) b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0)) gc = tf.get_variable("gc", [nh], initializer=tf.constant_initializer(1.0)) bc = tf.get_variable("bc", [nh], initializer=tf.constant_initializer(0.0)) c, h = tf.split(axis=1, num_or_size_splits=2, value=s) for idx, (x, m) in enumerate(zip(xs, ms)): c = c*(1-m) h = h*(1-m) z = _ln(tf.matmul(x, wx), gx, bx) + _ln(tf.matmul(h, wh), gh, bh) + b i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(_ln(c, gc, bc)) xs[idx] = h s = tf.concat(axis=1, values=[c, h]) return xs, s
tensorflow.split
12,701
import tensorflow as tf (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)
tensorflow.reduce_mean
12,702
import tensorflow as tf # assume square patch n_row,n_col,n_channel = x.shape n_patch = n_row*n_col // (self.size**2) patches = tf.image.extract_patches(tf.expand_dims(x,0),sizes=[1,self.size,self.size,1],strides=[1,self.size,self.size,1],rates=[1, 1, 1, 1],padding='VALID') patches = tf.reshape(patches,[n_patch,self.size,self.size,n_channel]) patches = tf.random.shuffle(patches) # rand_idx = tf.reshape(tf.random.shuffle(tf.range(0,n_patch)),[n_patch]) # patches = tf.gather(patches, rand_idx, axis=0) rows = tf.split(patches,n_col//self.size,axis=0) rows = [tf.concat(tf.unstack(x),axis=1) for x in rows]
tensorflow.random.shuffle
12,703
import tensorflow as tf tensor1 = dataset1.make_one_shot_iterator().get_next()["targets"] tensor2 = dataset2.make_one_shot_iterator().get_next()["targets"] with tf.Session() as sess: self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20)) @test_utils.run_in_graph_and_eager_modes()
tensorflow.Session
12,704
import tensorflow as tf 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.nn.softmax
12,705
import tensorflow as tf if encoder.attend_inputs: encoder_outputs.append(encoder_inputs_) elif encoder.attend_both: encoder_outputs.append(tf.concat([encoder_inputs_, encoder_outputs_], axis=2)) else: encoder_outputs.append(encoder_outputs_)
tensorflow.concat
12,706
import tensorflow as tf else: return tf.reshape(tf.stack(values=h, axis=1), [-1]) def lstm(xs, s, scope, nh, init_scale=1.0): nbatch, nin = [v.value for v in xs[0].get_shape()] nsteps = len(xs) with tf.variable_scope(scope): wx = tf.get_variable("wx", [nin, nh*4], initializer=ortho_init(init_scale)) wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale)) b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0)) c, h = tf.split(axis=1, num_or_size_splits=2, value=s) for idx, x in enumerate(xs): c = c h = h z = tf.matmul(x, wx) + tf.matmul(h, wh) + b i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(c)
tensorflow.split
12,707
import tensorflow as tf [5, 8], minval=-10, maxval=10.0, dtype=tf.float32) distances1 = isu.inputs_distances_to_centers(inputs, centers) num_centers = tf.shape(centers)[0] inputs_reshaped = tf.tile(tf.expand_dims(inputs, axis=1), tf.stack([1, num_centers, 1])) distances2 = tf.reduce_sum(tf.square(inputs_reshaped - centers), axis=2) self.assertAllClose(distances1.numpy(), distances2.numpy(), atol=0.001) def test_pairwise_iou_matrix(self): mask0 = tf.constant([[1, 0], [0, 1]], dtype=tf.float32) mask1 = tf.constant([[1, 1], [0, 1]], dtype=tf.float32) mask2 = tf.constant([[1, 0], [1, 1]], dtype=tf.float32) mask3 = tf.constant([[1, 1], [1, 1]], dtype=tf.float32) mask4 = tf.constant([[0, 0], [0, 0]], dtype=tf.float32) mask5 = tf.constant([[1, 0], [1, 0]], dtype=tf.float32) masks1 = tf.stack([mask0, mask1, mask2]) masks2 = tf.stack([mask3, mask4, mask5]) ious = isu.get_pairwise_iou_matrix(masks1, masks2) expected_ious = tf.constant([[0.5, 0.0, 1.0/3.0], [0.75, 0.0, 0.25],
tensorflow.constant
12,708
import tensorflow as tf q_func_ph = tf.gather_nd(self.Q_vals, tf.stack([tf.range(tf.shape(self.Q_vals)[0]), self.act_t_ph], axis=1)) target_q_ph = q_func(obs_tp1_float, self.num_actions, 'target_q_func', reuse = tf.AUTO_REUSE) if double_q: target_index = tf.math.argmax(q_func(obs_tp1_float, self.num_actions, 'q_func', reuse = tf.AUTO_REUSE), axis = 1, output_type = tf.int32) target_v_ph = tf.gather_nd(target_q_ph, tf.stack([tf.range(tf.shape(target_q_ph)[0]), target_index], axis=1)) else: target_v_ph = tf.math.reduce_max(target_q_ph, axis = 1) backup_ph = self.rew_t_ph + (1 - self.done_mask_ph) * (gamma * target_v_ph) self.total_error = tf.math.reduce_mean(huber_loss(q_func_ph - backup_ph)) q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_func') target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_q_func')
tensorflow.math.reduce_max
12,709
import tensorflow as tf pos_feats = tf.to_float(tf.stack([src_pos, trg_pos, src_len], axis=2)) pos_feats = tf.log(1 + pos_feats) 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)
tensorflow.stack
12,710
from tensorflow.python.framework import ops # statically, then we are unlikely to know the shape of the # gradients either. return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("DepthwiseConv2dNativeBackpropFilter") def _DepthwiseConv2dNativeBackpropFilterShape(op): """Shape function for the DepthwiseConv2dNativeBackpropFilter op.""" filter_shape = tensor_util.constant_value(op.inputs[1]) if filter_shape is not None: return [tensor_shape.TensorShape(filter_shape.tolist())] else: return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("DepthwiseConv2dNativeBackpropInput") def _DepthwiseConv2dNativeBackpropInputShape(op): """Shape function for the DepthwiseConv2dNativeBackpropInput op.""" input_shape = tensor_util.constant_value(op.inputs[0]) if input_shape is not None: return [tensor_shape.TensorShape(input_shape.tolist())] else: return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("MaxPoolGrad") @ops.RegisterShape("MaxPoolGradWithArgmax") def _MaxPoolGradShape(op): """Shape function for the MaxPoolGrad op.""" orig_input_shape = op.inputs[0].get_shape().with_rank(4)
tensorflow.python.framework.ops.RegisterShape
12,711
import tensorflow as tf def resnet_bottleneck_v1(self, depth, depth_bottleneck, stride, input_layer=None, in_size=None): if input_layer is None: input_layer = self.top_layer if in_size is None: in_size = self.top_size name = 'resnet_v1' + str(self.counts['resnet_v1']) self.counts['resnet_v1'] += 1 with tf.variable_scope(name): if depth == in_size: if stride == 1: shortcut = input_layer else: shortcut = self.mpool( 1, 1, stride, stride, input_layer=input_layer, num_channels_in=in_size) else:
tensorflow.variable_scope
12,712
from tensorflow.python.platform import gfile # Restore "v0" from that checkpoint. save.restore(sess, name) self.assertEqual(v0.eval(), 2.0) class CheckpointStateTest(tf.test.TestCase): def _TestDir(self, test_name): test_dir = os.path.join(self.get_temp_dir(), test_name) if os.path.exists(test_dir): shutil.rmtree(test_dir) gfile.MakeDirs(test_dir) return test_dir def testAbsPath(self): save_dir = self._TestDir("abs_paths") abs_path = os.path.join(save_dir, "model-0") ckpt = tf.train.generate_checkpoint_state_proto(save_dir, abs_path) self.assertEqual(ckpt.model_checkpoint_path, abs_path) self.assertTrue(os.path.isabs(ckpt.model_checkpoint_path)) self.assertEqual(len(ckpt.all_model_checkpoint_paths), 1) self.assertEqual(ckpt.all_model_checkpoint_paths[-1], abs_path)
tensorflow.python.platform.gfile.MakeDirs
12,713
import tensorflow as tf def neural_net(self, X, weights, biases): num_layers = len(weights) + 1 H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0 for l in range(0,num_layers-2): W = weights[l] b = biases[l] H = tf.tanh(tf.add(tf.matmul(H, W), b)) W = weights[-1] b = biases[-1] Y = tf.add(tf.matmul(H, W), b) return Y def fwd_gradients_0(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0] return tf.gradients(g, self.dummy_x0_tf)[0] def fwd_gradients_1(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0] return tf.gradients(g, self.dummy_x1_tf)[0]
tensorflow.matmul
12,714
import tensorflow as tf for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf) Args: features: 2-D `tensor` [batch_size, feature_length], input features label: 1-D `tensor` [batch_size], input label alpha: center loss parameter num_classes: a `int` numof classes for training Returns: a `float`, center loss """ with tf.variable_scope(name): num_features = features.get_shape()[1] centers = tf.get_variable( 'centers', [num_classes, num_features], dtype=tf.float32, initializer=tf.constant_initializer(0), trainable=False) label = tf.reshape(label, [-1]) centers_batch = tf.gather(centers, label) diff = (1 - alpha) * (centers_batch - features) centers = tf.scatter_sub(centers, label, diff)
tensorflow.variable_scope
12,715
from tensorflow.python.ops import random_ops """ with ops.op_scope([x], name, "dropout") as name: x = ops.convert_to_tensor(x, name="x") if isinstance(keep_prob, float) and not 0 < keep_prob <= 1: raise ValueError("keep_prob must be a scalar tensor or a float in the " "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) # uniform [keep_prob, 1.0 + keep_prob) random_tensor = keep_prob random_tensor += random_ops.random_uniform( noise_shape, seed=seed, dtype=x.dtype) # 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob) binary_tensor = math_ops.floor(random_tensor) ret = x * math_ops.inv(keep_prob) * binary_tensor ret.set_shape(x.get_shape()) return ret def top_k(input, k=1, sorted=True, name=None): """Finds values and indices of the `k` largest entries for the last dimension. If the input is a vector (rank-1), finds the `k` largest entries in the vector
tensorflow.python.ops.random_ops.random_uniform
12,716
import tensorflow as tf with tf.variable_scope("bw_{}".format(layer)): inputs_bw = tf.reverse_sequence(
tensorflow.reverse_sequence
12,717
import tensorflow as tf raise ValueError("`token_type_ids` must be specified if" "`use_token_type` is True.") token_type_table = tf.get_variable( name=token_type_embedding_name, shape=[token_type_vocab_size, width], initializer=create_initializer(initializer_range)) # This vocab will be small so we always do one-hot here, since it is always # faster for a small vocabulary. flat_token_type_ids = tf.reshape(token_type_ids, [-1]) one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size) token_type_embeddings = tf.matmul(one_hot_ids, token_type_table) token_type_embeddings = tf.reshape(token_type_embeddings, [batch_size, seq_length, width]) output += token_type_embeddings if use_position_embeddings: assert_op = tf.assert_less_equal(seq_length, max_position_embeddings) with tf.control_dependencies([assert_op]):
tensorflow.one_hot
12,718
import tensorflow as tf # Must have `strides[0] = strides[3] = 1 `. # For the most common case of the same horizontal and vertices strides, `strides = [1, stride, stride, 1] `. return tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME', name='conv_2d')
tensorflow.nn.conv2d
12,719
import tensorflow as tf # CNN cnn_output = feats_audio if do_cnn: layer_last = feats_audio nfilt_last = audio_nchannels for i, ((ntime, nband, nfilt), (ptime, pband)) in enumerate(zip(cnn_filter_shapes, cnn_pool)): layer_name = 'cnn_{}'.format(i) with tf.variable_scope(layer_name): filters = tf.get_variable('filters', [ntime, nband, nfilt_last, nfilt], initializer=cnn_init, dtype=dtype) biases = tf.get_variable('biases', [nfilt], initializer=tf.constant_initializer(0.1), dtype=dtype) if cnn_rnn_zack: padding = 'SAME' else: padding = 'VALID' conv = tf.nn.conv2d(layer_last, filters, [1, 1, 1, 1], padding=padding)
tensorflow.get_variable
12,720
from tensorflow.python.framework import tensor_shape def _SelectShape(op): # All three inputs must have the same shape. return [op.inputs[0].get_shape() .merge_with(op.inputs[1].get_shape()) .merge_with(op.inputs[2].get_shape())] @ops.RegisterShape("ArgMax") @ops.RegisterShape("ArgMin") def _ArgOpShape(op): """Common shape function for arg-reduction ops.""" dimension_shape = op.inputs[1].get_shape() dimension_shape.assert_is_compatible_with(tensor_shape.scalar()) input_shape = op.inputs[0].get_shape() if input_shape.ndims is None: return [tensor_shape.unknown_shape()] elif input_shape.ndims <= 1: return [tensor_shape.scalar()] dimension = tensor_util.ConstantValue(op.inputs[1]) if dimension is None: return [tensor_shape.unknown_shape(ndims=input_shape.ndims - 1)] elif 0 <= dimension and dimension < input_shape.ndims: returned_shape = []
tensorflow.python.framework.tensor_shape.scalar
12,721
import tensorflow as tf nbatch, nin = [v.value for v in xs[0].get_shape()] nsteps = len(xs) with tf.variable_scope(scope): wx = tf.get_variable("wx", [nin, nh*4], initializer=ortho_init(init_scale)) wh = tf.get_variable("wh", [nh, nh*4], initializer=ortho_init(init_scale)) b = tf.get_variable("b", [nh*4], initializer=tf.constant_initializer(0.0)) c, h = tf.split(axis=1, num_or_size_splits=2, value=s) for idx, x in enumerate(xs): c = c h = h z = tf.matmul(x, wx) + tf.matmul(h, wh) + b i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z) i = tf.nn.sigmoid(i) f = tf.nn.sigmoid(f) o = tf.nn.sigmoid(o) u = tf.tanh(u) c = f*c + i*u h = o*tf.tanh(c) xs[idx] = h s = tf.concat(axis=1, values=[c, h]) return xs, s def ortho_init(scale=1.0): def _ortho_init(shape, dtype, partition_info=None): #lasagne ortho init for tf shape = tuple(shape) if len(shape) == 2: flat_shape = shape
tensorflow.nn.sigmoid
12,722
import tensorflow as tf use_tpu=FLAGS.use_tpu, bsz=FLAGS.predict_batch_size) checkpoint_path = os.path.join(FLAGS.output_dir, "model.ckpt-best") result = estimator.predict( input_fn=predict_input_fn, checkpoint_path=checkpoint_path) output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv") output_submit_file = os.path.join(FLAGS.output_dir, "submit_results.tsv") with tf.gfile.GFile(output_predict_file, "w") as pred_writer,\ tf.gfile.GFile(output_submit_file, "w") as sub_writer: sub_writer.write("index" + "\t" + "prediction\n") num_written_lines = 0 tf.logging.info("***** Predict results *****") for (i, (example, prediction)) in\ enumerate(zip(predict_examples, result)): probabilities = prediction["probabilities"] if i >= num_actual_predict_examples: break output_line = "\t".join( str(class_probability)
tensorflow.gfile.GFile
12,723
import tensorflow as tf chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps perturbed_stochastic_actions = tf.where(chose_random, random_actions, perturbed_deterministic_actions) stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions) perturbed_output_actions = tf.cond(stochastic_ph, lambda: perturbed_stochastic_actions, lambda: deterministic_actions) output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions) update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps)) updates = [ update_eps_expr, tf.cond(reset_ph, lambda: perturb_vars(original_scope="model", perturbed_scope="perturbed_model/model"), lambda: tf.group(*[])),
tensorflow.cond
12,724
from tensorflow.python.ops import math_ops with variable_scope.variable_scope(name, 'sensitivity_at_specificity', [predictions, labels]): kepsilon = 1e-7 # to account for floating point imprecisions thresholds = [(i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds-2)] thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon] (tp, fn, tn, fp, tp_update_op, fn_update_op, tn_update_op, fp_update_op) = _tp_fn_tn_fp(predictions, labels, thresholds, weights) assert array_ops.squeeze(fp).get_shape().as_list()[0] == num_thresholds def compute_sensitivity_at_specificity(name): specificities = math_ops.div(tn, tn + fp + kepsilon) tf_index = math_ops.argmin(math_ops.abs(specificities - specificity), 0) tf_index = math_ops.cast(tf_index, dtypes.int32) # Now, we have the implicit threshold, so compute the sensitivity: return math_ops.div(tp[tf_index], tp[tf_index] + fn[tf_index] + kepsilon, name) sensitivity = compute_sensitivity_at_specificity('value') with ops.control_dependencies( [tp_update_op, fn_update_op, tn_update_op, fp_update_op]): update_op = compute_sensitivity_at_specificity('update_op') if metrics_collections: ops.add_to_collections(metrics_collections, sensitivity)
tensorflow.python.ops.math_ops.cast
12,725
import tensorflow as tf labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels. label_smoothing: a float, used to smooth the labels for better generalization if greater than 0 then smooth the labels. y_pow: int, to whcih the labels should be raised; useful if model diverge. e.g. y_pow=2 num_ratings: numbers of rater to used, typically num_classes of the model batch_size: batch_size of the training or validation ops log_scale: a float, used to multiply the clipped log loss, e.g: 0.5 log_offset:a float minimum log loss offset to substract from original log loss; e.g. 0.50 name: Optional scope/name for op_scope. Returns: A tensor with the kappa log loss. """ with tf.name_scope(name): num_classes = labels.get_shape()[-1].value labels = tf.cast(labels, predictions.dtype) if label_smoothing > 0: smooth_positives = 1.0 - label_smoothing smooth_negatives = label_smoothing / num_classes labels = labels * smooth_positives + smooth_negatives log_loss_res = log_loss(predictions, labels) kappa_loss_res = kappa_loss( predictions, labels, y_pow=y_pow, num_ratings=num_classes, batch_size=batch_size) return kappa_loss_res + log_scale * (log_loss_res - log_offset)
tensorflow.name_scope
12,726
from tensorflow.python.framework import ops strides: A list of ints that has length >= 4. The stride of the sliding window for each dimension of the input tensor. padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm. data_format: A string. 'NHWC' and 'NCHW" are supported. name: Optional name for the operation. Returns: A `Tensor` with type `tf.float32`. The max pooled output tensor. """ with ops.op_scope([value], name, "MaxPool") as name: value = ops.convert_to_tensor(value, name="input") return gen_nn_ops._max_pool(value, ksize=ksize, strides=strides, padding=padding, data_format=data_format, name=name) ops.RegisterShape("Relu")(common_shapes.unchanged_shape) ops.RegisterShape("Relu6")(common_shapes.unchanged_shape) ops.RegisterShape("Elu")(common_shapes.unchanged_shape)
tensorflow.python.framework.ops.convert_to_tensor
12,727
from tensorflow.contrib.eager.python.examples.spinn import data f.write("%s " % word) for j in range(data.WORD_VECTOR_LEN): f.write("%.5f" % (i * 0.1)) if j < data.WORD_VECTOR_LEN - 1: f.write(" ") else: f.write("\n") return fake_train_file def testInferSpinnWorks(self): """Test inference with the spinn model.""" 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"), inference_sentences=("( foo ( bar . ) )", "( bar ( foo . ) )")) logits = spinn.train_or_infer_spinn( embed, word2index, None, None, None, config) self.assertEqual(tf.float32, logits.dtype) 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)
tensorflow.contrib.eager.python.examples.spinn.data.load_vocabulary
12,728
import tensorflow as tf gtboxes_and_label_h, gtboxes_and_label_q = tf.py_func(self.get_gtboxes_and_label, inp=[inputs_list[i][1], inputs_list[i][2], inputs_list[i][3]], Tout=[tf.float32, tf.float32]) gtboxes_and_label_h = tf.reshape(gtboxes_and_label_h, [cfgs.BATCH_SIZE, -1, 5]) # Unnecessary, if you have already sorted when making tfrecord and no data augmentation. gtboxes_and_label_q = tf.py_func(func=re_order, inp=[tf.reshape(gtboxes_and_label_q, [-1, 9]), True], Tout=[tf.float32]) gtboxes_and_label_q = tf.reshape(gtboxes_and_label_q, [cfgs.BATCH_SIZE, -1, 9]) img = inputs_list[i][0] img_shape = inputs_list[i][-2:] h_crop = tf.reduce_max(img_shape[0]) w_crop = tf.reduce_max(img_shape[1]) img = tf.image.crop_to_bounding_box(image=img, offset_height=0,
tensorflow.reshape
12,729
from tensorflow.python.platform import test if __name__ == "__main__": test.main()
tensorflow.python.platform.test.main
12,730
from tensorflow.python.framework import ops logits = self._logits(features, is_training=True) if self._enable_centered_bias: centered_bias_step = [self._centered_bias_step(targets, features)] else: centered_bias_step = [] with ops.control_dependencies(centered_bias_step): loss = self._target_column.loss(logits, targets, features) logging_ops.scalar_summary("loss", loss) linear_train_step = self._linear_model.get_train_step(loss) dnn_train_step = (self._dnn_model.get_train_step(loss) if self._dnn_model else []) with ops.control_dependencies(linear_train_step + dnn_train_step): with ops.get_default_graph().colocate_with(global_step): return state_ops.assign_add(global_step, 1).op, loss def _get_eval_ops(self, features, targets, metrics=None): raise NotImplementedError def _get_predict_ops(self, features): """See base class.""" features = self._get_feature_dict(features) logits = self._logits(features) return self._target_column.logits_to_predictions(logits, proba=True) def _get_feature_ops_from_example(self, examples_batch): column_types = layers.create_feature_spec_for_parsing((
tensorflow.python.framework.ops.get_default_graph
12,731
import tensorflow as tf inp=[gtboxes_and_label_r[:, -2], cfgs.ANGLE_RANGE, cfgs.OMEGA, cfgs.ANGLE_MODE], Tout=tf.float32) img = inputs_list[i][0] img_shape = inputs_list[i][-2:] img = tf.image.crop_to_bounding_box(image=img, offset_height=0, offset_width=0, target_height=tf.cast(img_shape[0], tf.int32), target_width=tf.cast(img_shape[1], tf.int32)) outputs = r3det_dcl.build_whole_detection_network(input_img_batch=img, gtboxes_batch_h=gtboxes_and_label_h, gtboxes_batch_r=gtboxes_and_label_r, gt_encode_label=gt_encode_label, gpu_id=i) gtboxes_in_img_h = self.drawer.draw_boxes_with_categories(img_batch=img,
tensorflow.cast
12,732
import tensorflow as tf if self.hidden_init == 'identity': l1_h2 = tf.identity(x) l2_h2 = tf.zeros(l2_shape, dtype=self.dtype) l3_h2 = tf.zeros(l3_shape, dtype=self.dtype) elif self.hidden_init == 'random': l1_h2 = tf.random_normal(x_shape, dtype=self.dtype) l2_h2 = tf.random_normal(l2_shape, dtype=self.dtype) l3_h2 = tf.random_normal(l3_shape, dtype=self.dtype) elif self.hidden_init == 'zeros': l1_h2 = tf.zeros(x_shape, dtype=self.dtype) l2_h2 = tf.zeros(l2_shape, dtype=self.dtype) l3_h2 = tf.zeros(l3_shape, dtype=self.dtype) else: raise RuntimeError # While loop elems = [ i0,
tensorflow.zeros
12,733
import tensorflow as tf w_z0_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) * (z1_f - z) * x0_valid * y1_valid * z1_valid), 1) w_z0_y1_x0 = tf.expand_dims(((x1_f - x) * (y - y0_f) * (z1_f - z) * x1_valid * y0_valid * z1_valid), 1) w_z0_y1_x1 = tf.expand_dims(((x - x0_f) * (y - y0_f) * (z1_f - z) * x0_valid * y0_valid * z1_valid), 1) w_z1_y0_x0 = tf.expand_dims(((x1_f - x) * (y1_f - y) * (z - z0_f) * x1_valid * y1_valid * z0_valid), 1) w_z1_y0_x1 = tf.expand_dims(((x - x0_f) * (y1_f - y) * (z - z0_f) * x0_valid * y1_valid * z0_valid), 1) w_z1_y1_x0 = tf.expand_dims(((x1_f - x) * (y - y0_f) * (z - z0_f) * x1_valid * y0_valid * z0_valid), 1) w_z1_y1_x1 = tf.expand_dims(((x - x0_f) * (y - y0_f) * (z - z0_f) * x0_valid * y0_valid * z0_valid), 1) output = tf.add_n([ w_z0_y0_x0 * i_z0_y0_x0, w_z0_y0_x1 * i_z0_y0_x1, w_z0_y1_x0 * i_z0_y1_x0, w_z0_y1_x1 * i_z0_y1_x1, w_z1_y0_x0 * i_z1_y0_x0, w_z1_y0_x1 * i_z1_y0_x1, w_z1_y1_x0 * i_z1_y1_x0, w_z1_y1_x1 * i_z1_y1_x1 ]) return output
tensorflow.expand_dims
12,734
import tensorflow as tf def cls_loss(ratio=3): def _cls_loss(y_true, y_pred): # y_true [batch_size, num_anchor, num_classes+1] # y_pred [batch_size, num_anchor, num_classes] labels = y_true anchor_state = y_true[:, :, -1] # -1 是需要忽略的, 0 是背景, 1 是存在目标 classification = y_pred # 找出存在目标的先验框 indices_for_object = tf.where(keras.backend.equal(anchor_state, 1)) labels_for_object = tf.gather_nd(labels, indices_for_object) classification_for_object = tf.gather_nd(classification, indices_for_object) cls_loss_for_object = keras.backend.binary_crossentropy(labels_for_object, classification_for_object) # 找出实际上为背景的先验框 indices_for_back = tf.where(keras.backend.equal(anchor_state, 0)) labels_for_back = tf.gather_nd(labels, indices_for_back) classification_for_back = tf.gather_nd(classification, indices_for_back) # 计算每一个先验框应该有的权重 cls_loss_for_back = keras.backend.binary_crossentropy(labels_for_back, classification_for_back) # 标准化,实际上是正样本的数量
tensorflow.gather_nd
12,735
import tensorflow as tf scope.reuse_variables() print('D in:', X.get_shape().as_list()) rate = [2, 3, 4] X = atrous_convs(X, "d_atrous_0", rate = rate, depth=256, reuse=reuse) X = tf.nn.leaky_relu(X, 0.2) X = self.conv('d_1', X, 512, size=1, stride=1, padding="SAME") X = tf.nn.leaky_relu(X, 0.2) X = self.conv('d_2', X, 512, size=1, stride=1, padding="SAME") X = tf.nn.leaky_relu(X, 0.2) X = self.conv('d_3', X, 512, size=1, stride=1, padding="SAME")
tensorflow.nn.leaky_relu
12,736
import tensorflow as tf target_y = tf.cast(target_y64, tf.int32) adversarial_sample = attacks.jsma.jsma(models, images, hps, RCE_train, target_y,epochs=epoch_jsma, eps=eps, clip_min=-0.5, clip_max=0.5, pair=False, min_proba=0.0) elif method=='smda': print('Attacking method is smda') if target_labels==None: print('Target label is the argmin label') model_target_y = models(hps, images, FLAGS.RCE_train, logits=False) target_y64 = tf.argmin(model_target_y,axis=1) else: target_y64=target_labels target_y = tf.cast(target_y64, tf.int32) adversarial_sample = attacks.smda.smda(models, images, hps, RCE_train, target_y, epochs=epoch_jsma, eps=eps, clip_min=-0.5, clip_max=0.5, min_proba=0.0) else: print('Not recognized method') adversarial_sample = None return adversarial_sample def tSNE_visual(hps,num_batch): # Construct graph images, labels = input_name.build_input(
tensorflow.cast
12,737
import tensorflow as tf batch_size = tf.shape(targets)[0] time_steps = tf.shape(targets)[1] logits_ = tf.reshape(logits, tf.stack([time_steps * batch_size, logits.get_shape()[2].value])) targets_ = tf.reshape(targets, tf.stack([time_steps * batch_size])) crossent = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_, labels=targets_) crossent = tf.reshape(crossent, tf.stack([batch_size, time_steps])) if rewards is not None: crossent *= tf.stop_gradient(rewards) log_perp = tf.reduce_sum(crossent * weights, axis=1) if average_across_timesteps: total_size = tf.reduce_sum(weights, axis=1) total_size += 1e-12 # just to avoid division by 0 for all-0 weights log_perp /= total_size cost = tf.reduce_sum(log_perp) if average_across_batch: return cost / tf.to_float(batch_size) else: return cost def reinforce_baseline(decoder_states, reward): """ Center the reward by computing a baseline reward over decoder states.
tensorflow.reduce_sum
12,738
import tensorflow as tf FLAGS.enable_check_numerics = False with self.session(): tf.global_variables_initializer().run() self.assertFalse(has_nan_or_inf.eval())
tensorflow.global_variables_initializer
12,739
import tensorflow as tf def _MergeOneToken(tokens, i): return tf.expand_dims( self._MergeTokens((tokens[i], tokens[i + 1])), axis=-1) def _MergeCandidates(tokens, candidates): """Merge in the reverse binary tree.""" best_id = tf.argmin(candidates, output_type=tf.int32) # Perform the merge at position best_id. tokens = tf.concat( [tokens[:best_id], [candidates[best_id]], tokens[best_id + 2:]], axis=0) # Recompute the merge candidates. # Only the neighbors of best_id need to be recomputed. empty = tf.zeros([0], dtype=candidates.dtype) def _MergeLeft():
tensorflow.concat
12,740
import tensorflow as tf if hparams.predict_linear: tf.summary.scalar("linear_loss", model.linear_loss) for i in range(hparams.tacotron_num_gpus): tf.summary.histogram("mel_outputs %d" % i, model.tower_linear_outputs[i]) tf.summary.histogram("mel_targets %d" % i, model.tower_linear_targets[i]) tf.summary.scalar("regularization_loss", model.regularization_loss) tf.summary.scalar("stop_token_loss", model.stop_token_loss) tf.summary.scalar("loss", model.loss) tf.summary.scalar("learning_rate", model.learning_rate) # Control learning rate decay speed if hparams.tacotron_teacher_forcing_mode == "scheduled": tf.summary.scalar("teacher_forcing_ratio", model.ratio) # Control teacher forcing # ratio decay when mode = "scheduled" gradient_norms = [tf.norm(grad) for grad in model.gradients] tf.summary.histogram("gradient_norm", gradient_norms) tf.summary.scalar("max_gradient_norm", tf.reduce_max(gradient_norms)) # visualize # gradients (in case of explosion) return tf.summary.merge_all() def add_eval_stats(summary_writer, step, linear_loss, before_loss, after_loss, stop_token_loss, loss):
tensorflow.summary.scalar
12,741
import tensorflow as tf # dimensional representation of the segment. with tf.variable_scope("pooler"): # We "pool" the model by simply taking the hidden state corresponding # to the first token. We assume that this has been pre-trained first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1) self.pooled_output = tf.layers.dense( first_token_tensor, config.hidden_size,
tensorflow.squeeze
12,742
import tensorflow as tf flat_with_target = tf.concat([flat, tgt], axis=0) new_features = {} new_features['image'] = flat_with_target predict_image_weight = predict_image_train_weight if training else 0.0 mask_begin = tf.ones_like(flat) mask_begin = tf.cast(mask_begin, tf.float32) * predict_image_weight mask_end = tf.cast(tf.ones_like(tgt), tf.float32) new_features['mask'] = tf.concat([mask_begin, mask_end], axis=0) return new_features, flat_with_target
tensorflow.cast
12,743
from tensorflow.python.ops import math_ops ``` where digamma(alpha) is the digamma function.""") def _entropy(self): return (self.alpha + math_ops.log(self.beta) + math_ops.lgamma(self.alpha) - (1. + self.alpha) * math_ops.digamma(self.alpha)) @distribution_util.AppendDocstring(
tensorflow.python.ops.math_ops.log
12,744
import tensorflow as tf tf.compat.v2.summary.scalar( name="relabel_task_optimal", data=relabel_opt_frac, step=global_step) # What are the average Q values of the original tasks? if batch_size == num_tasks: indices = tf.transpose(tf.stack([orig_indices, orig_indices], axis=0)) orig_q_vals = tf.gather_nd(logits_vec, indices) tf.compat.v2.summary.scalar( name="orig_q_vals", data=tf.reduce_mean(orig_q_vals), step=global_step, ) # What are the average Q values of the relabelled tasks? indices = tf.transpose( tf.stack([orig_indices, tf.squeeze(relabel_indices)], axis=0)) relabel_q_vals = tf.gather_nd(logits_vec, indices) tf.compat.v2.summary.scalar( name="relabel_q_vals", data=tf.reduce_mean(relabel_q_vals), step=global_step, ) max_q = tf.reduce_max(logits_vec, axis=1) tf.compat.v2.summary.scalar( name="max_q", data=tf.reduce_mean(max_q), step=global_step) ### End metrics # For both state-centric and goal-centric relabelling, the implementation of
tensorflow.squeeze
12,745
import tensorflow as tf if name in config.heads and name not in config.gradient_heads: features = tf.stop_gradient(raw_features)
tensorflow.stop_gradient
12,746
from tensorflow.contrib.layers.python.layers import feature_column as contrib_feature_column def testThatLeafIndexIsInPredictions(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1 model_dir = tempfile.mkdtemp() config = run_config.RunConfig() classifier = estimator.GradientBoostedDecisionTreeClassifier( learner_config=learner_config, num_trees=1, examples_per_layer=3, model_dir=model_dir, config=config, feature_columns=[contrib_feature_column.real_valued_column("x")], output_leaf_index=True) classifier.fit(input_fn=_train_input_fn, steps=15) result_iter = classifier.predict(input_fn=_eval_input_fn) for prediction_dict in result_iter: self.assertTrue("leaf_index" in prediction_dict) self.assertTrue("logits" in prediction_dict) def testFitAndEvaluateDontThrowExceptionWithCoreForEstimator(self): learner_config = learner_pb2.LearnerConfig() learner_config.num_classes = 2 learner_config.constraints.max_tree_depth = 1
tensorflow.contrib.layers.python.layers.feature_column.real_valued_column
12,747
import tensorflow as tf 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)
tensorflow.unstack
12,748
import tensorflow as tf # outputs, state = tf.contrib.rnn.static_rnn(cell, inputs, # initial_state=self._initial_state) outputs = [] with tf.variable_scope("RNN"): for time_step in range(self.num_steps): if time_step > 0: tf.get_variable_scope().reuse_variables() (cell_output, state) = cell(inputs[:, time_step, :], state) outputs.append(cell_output) output = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size]) return output, state def assign_lr(self, session, lr_value): session.run(self._lr_update, feed_dict={self._new_lr: lr_value}) def export_ops(self, name): """Exports ops to collections."""
tensorflow.concat
12,749
import tensorflow as tf prev_c = [tf.zeros([1, self.lstm_size], tf.float32) for _ in range(self.lstm_num_layers)] prev_h = [tf.zeros([1, self.lstm_size], tf.float32) for _ in range(self.lstm_num_layers)] inputs = self.g_emb for layer_id in range(2): next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm) prev_c, prev_h = next_c, next_h anchors = anchors.write(layer_id, tf.zeros_like(next_h[-1])) anchors_w_1 = anchors_w_1.write( layer_id, tf.matmul(next_h[-1], self.w_attn_1)) def _condition(layer_id, *args): return tf.less(layer_id, self.num_cells + 2) def _body(layer_id, inputs, prev_c, prev_h, anchors, anchors_w_1, arc_seq, entropy, log_prob): indices = tf.range(0, layer_id, dtype=tf.int32) start_id = 4 * (layer_id - 2) prev_layers = [] for i in range(2): # index_1, index_2
tensorflow.matmul
12,750
from tensorflow.python.ops import array_ops values = math_ops.mul(values, weights) num_values = math_ops.reduce_sum(_broadcast_weights(weights, values)) else: num_values = math_ops.to_float(array_ops.size(values)) total_compute_op = state_ops.assign_add(total, math_ops.reduce_sum(values))
tensorflow.python.ops.array_ops.size
12,751
import tensorflow as tf if options.use_coverage: with variable_scope.variable_scope("coverage"): w_c = variable_scope.get_variable("w_c", [options.attention_vec_size]) w_c = tf.expand_dims(tf.expand_dims(w_c, axis=0), axis=0) # For each step, dec_input => lstm_output => vocab_score
tensorflow.expand_dims
12,752
from tensorflow.python.ops import math_ops def get_weight_tensor(self, features): if not self._weight_column_name: return None else: return array_ops.reshape( math_ops.to_float(features[self._weight_column_name]), shape=(-1,)) def loss(self, logits, target, features): """Returns loss tensor for this head.
tensorflow.python.ops.math_ops.to_float
12,753
import tensorflow as tf # tf.losses.add_loss(mse_loss) # Add weight decay to the loss. We exclude the batch norm variables because # doing so leads to a small improvement in accuracy. loss = mse_loss + params['weight_decay'] * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name]) total_loss = tf.identity(loss, name='total_loss') tf.summary.scalar('loss', total_loss) if mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics) if mode == tf.estimator.ModeKeys.TRAIN: global_step = tf.train.get_or_create_global_step() lr_values = [params['warmup_learning_rate']] + [base_learning_rate * decay for decay in params['lr_decay_factors']] learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32), [params['warmup_steps']] + [int(float(ep)*params['steps_per_epoch']) for ep in params['decay_boundaries']], lr_values) truncated_learning_rate = tf.maximum(learning_rate, tf.constant(params['end_learning_rate'], dtype=learning_rate.dtype), name='learning_rate') tf.summary.scalar('lr', truncated_learning_rate) optimizer = tf.train.MomentumOptimizer(learning_rate=truncated_learning_rate, momentum=params['momentum'])
tensorflow.train.get_or_create_global_step
12,754
import tensorflow as tf dtype=_x.dtype) input_shape = list(_x.get_shape()) reduction_axes = list(range(len(input_shape))) del reduction_axes[axis] broadcast_shape = [1] * len(input_shape) broadcast_shape[axis] = input_shape[axis] # case: train mode (uses stats of the current batch) mean = tf.reduce_mean(_x, axis=reduction_axes) brodcast_mean = tf.reshape(mean, broadcast_shape) std = tf.reduce_mean(tf.square(_x - brodcast_mean) + epsilon, axis=reduction_axes) std = tf.sqrt(std) brodcast_std = tf.reshape(std, broadcast_shape) x_normed = (_x - brodcast_mean) / (brodcast_std + epsilon) # x_normed = tf.layers.batch_normalization(_x, center=False, scale=False) x_p = tf.sigmoid(x_normed)
tensorflow.reduce_mean
12,755
from tensorflow.python.training import adagrad linear_feature_columns=(bucketized_feature,), linear_optimizer=ftrl.FtrlOptimizer(learning_rate=0.1), dnn_feature_columns=(cont_feature,), dnn_hidden_units=(3, 3), dnn_optimizer=adagrad.AdagradOptimizer(learning_rate=0.1)) input_fn = test_data.iris_input_logistic_fn metrics = classifier.fit(input_fn=input_fn, steps=_ITERS).evaluate(
tensorflow.python.training.adagrad.AdagradOptimizer
12,756
import tensorflow as tf slim = tf.contrib.slim global first first = True classnum=12 testnum = tf.placeholder(tf.int32) trainnum = tf.placeholder(tf.int32) validnum = tf.placeholder(tf.int32) learnrate = tf.placeholder(tf.float32) def getinputs(path): filename_queue=tf.train.string_input_producer([path]) reader=tf.TFRecordReader() _,serialized_example=reader.read(filename_queue) features=tf.parse_single_example(serialized_example, features={ 'label':tf.FixedLenFeature([], tf.int64),
tensorflow.placeholder
12,757
import tensorflow as tf def _train_batch_sizes(self): """Shamelessly copied from `resnet50_test.py`. Note: This is targeted towards ImageNet. CIFAR-10 should allow more aggressive batch sizes. Returns: A tuple of possible batch sizes """ for device in device_lib.list_local_devices(): if tf.DeviceSpec.from_string(device.name).device_type == "GPU": if "K20" in device.physical_device_desc: return (16,) if "P100" in device.physical_device_desc: return (16, 32, 64) if tf.DeviceSpec.from_string(device.name).device_type == "TPU": return (32,) return (16, 32) def _force_device_sync(self): """Shamelessly copied from `resnet50_test.py`."""
tensorflow.DeviceSpec.from_string
12,758
import tensorflow as tf """ Test RNN graph single layer """ def test_rnn_kstep(test_data_x,test_data_y, preds, rnn_outputs, g, checkpoint, input_prob, output_prob, state_prob, num_test, kstep = 3): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) result= {} "read the trained graph"
tensorflow.Session
12,759
from tensorflow.python.framework import ops metric = math_ops.div(tp, math_ops.add(tp, fn), name=scope) update = math_ops.div( tp_update, math_ops.add(tp_update, fn_update), name='update') if metrics_collections: ops.add_to_collections(metrics_collections, metric) if updates_collections: ops.add_to_collections(updates_collections, update) return metric, update
tensorflow.python.framework.ops.add_to_collections
12,760
import tensorflow as tf return tf.nn.relu(layer) with tf.variable_scope('norm_layer_%s%d' % (prefix, id)) as vs: if norm_type == 'batch_norm': if is_training: try: layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True, scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs) # updates_collections=None except ValueError: layer = tf.contrib.layers.batch_norm(layer, is_training=True, center=True, scale=False, decay=decay, activation_fn=activation_fn, updates_collections=None, scope=vs, reuse=True) # updates_collections=None
tensorflow.contrib.layers.batch_norm
12,761
import tensorflow as tf regularizer=regularizer) b = tf.get_variable('b', [2048], initializer=tf.constant_initializer(1.0)) out = tf.matmul(self.fc1, w) + b self.fc2 = tf.nn.relu(out) # fc3 with tf.variable_scope('fc3'): w = tf.get_variable('w', [self.fc2.get_shape()[1], num_classes], initializer=initializer, regularizer=regularizer) b = tf.get_variable('b', [num_classes], initializer=tf.constant_initializer(1.0)) self.fc3 = tf.matmul(self.fc2, w) + b # Calculate Mean cross-entropy loss with tf.name_scope("loss"): self.predictions = tf.argmax(self.fc3, 1, name="predictions") losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.fc3, labels=self.input_y) regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) self.loss = tf.reduce_mean(losses) + sum(regularization_losses) # Accuracy with tf.name_scope("accuracy"): correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1)) self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
tensorflow.name_scope
12,762
import tensorflow as tf 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
tensorflow.get_default_graph
12,763
import tensorflow as tf tf.expand_dims(tf.nn.softmax(logits2), axis=1)) outer = tf.matrix_band_part(outer, 0, config.ans_limit) self.yp1 = tf.argmax(tf.reduce_max(outer, axis=2), axis=1) self.yp2 = tf.argmax(tf.reduce_max(outer, axis=1), axis=1) losses = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits1, labels=self.y1) losses2 = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits2, labels=self.y2) self.loss = tf.reduce_mean(losses + losses2) if config.l2_norm is not None: variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) l2_loss = tf.contrib.layers.apply_regularization(regularizer, variables) self.loss += l2_loss if config.decay is not None: self.var_ema = tf.train.ExponentialMovingAverage(config.decay) ema_op = self.var_ema.apply(tf.trainable_variables()) with tf.control_dependencies([ema_op]): self.loss = tf.identity(self.loss) self.assign_vars = []
tensorflow.get_collection
12,764
import tensorflow as tf """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" tf.logging.info("*** Features ***") for name in sorted(features.keys()): tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) input_ids = features["input_ids"] input_mask = features["input_mask"] segment_ids = features["segment_ids"] label_ids = features["label_ids"] is_real_example = None
tensorflow.logging.info
12,765
import tensorflow as tf qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) x = np.arange(-100, 100, 2).astype(dtype) tf.initialize_all_variables().run() proba = qdist.log_prob(x) grads = tf.gradients(proba, [mu, sigma]) self._assert_all_finite(proba.eval()) self._assert_all_finite(grads[0].eval()) self._assert_all_finite(grads[1].eval()) def test_prob_and_grad_gives_finite_results_for_common_events(self): with self.test_session(): mu = tf.Variable(0.0, name="mu")
tensorflow.gradients
12,766
import tensorflow as tf ni = len(cell_inputs + blocks) b = len(blocks) # Count usage of inputs block_uses = [] for bi in range(b): idx1 = cell_arch[bi][0] idx2 = cell_arch[bi][2] block_use = tf.one_hot(idx1, ni, dtype=tf.int32) + tf.one_hot(idx2, ni, dtype=tf.int32) block_uses.append(block_use) block_uses = tf.add_n(block_uses) unused_indices = tf.reshape(tf.cast(tf.where(tf.equal(block_uses, 0)), tf.int32), [-1]) num_out_blocks = tf.size(unused_indices) # Select only unused blocks with tf.variable_scope('select'):
tensorflow.one_hot
12,767
from tensorflow.python.platform import gfile self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Exercise the third helper. # Adding s2 again (but helper is unaware of previous s2) s2 = save3.save(sess, os.path.join(save_dir, "s2")) self.assertEqual([s2], save3.last_checkpoints) # Created by the first helper. self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) # Deleted by the first helper. self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) # Adding s1 (s3 should not be deleted because helper is unaware of it) s1 = save3.save(sess, os.path.join(save_dir, "s1")) self.assertEqual([s2, s1], save3.last_checkpoints) self.assertFalse(gfile.Exists(s3)) self.assertFalse(gfile.Exists(save._MetaGraphFilename(s3))) self.assertTrue(gfile.Exists(s2)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s2))) self.assertTrue(gfile.Exists(s1)) self.assertTrue(gfile.Exists(save._MetaGraphFilename(s1))) def testSharded(self):
tensorflow.python.platform.gfile.Exists
12,768
import tensorflow as tf length=histories_vocabulary_length, size=histories_embedding_size, name='encoder_embedding' ) with tf.name_scope("UtterancesEncoder"): conv3 = encoder_embedding # conv3 = dropout(conv3, pow_1(self.dropout_keep_prob, 2)) conv3 = conv2d_bn( input=conv3,
tensorflow.name_scope
12,769
from tensorflow.python.platform import gfile self.assertEqual(ckpt.all_model_checkpoint_paths[-1], rel_path) self.assertEqual(ckpt.all_model_checkpoint_paths[0], abs_path) class MetaGraphTest(tf.test.TestCase): def _TestDir(self, test_name): test_dir = os.path.join(self.get_temp_dir(), test_name) if os.path.exists(test_dir): shutil.rmtree(test_dir) gfile.MakeDirs(test_dir) return test_dir def testAddCollectionDef(self): test_dir = self._TestDir("good_collection") filename = os.path.join(test_dir, "metafile") with self.test_session(): # Creates a graph. v0 = tf.Variable(10.0, name="v0") var = tf.Variable(tf.constant(0, dtype=tf.int64))
tensorflow.python.platform.gfile.MakeDirs
12,770
import tensorflow as tf divider = tf.constant(resample, dtype=tf.float32) def sample_compute(cur_loss, i): batch1 = tf.gather(batch, tf.random.shuffle(index)) batch2 = tf.gather(batch, tf.random.shuffle(index)) pred1 = tf.slice(batch1, [0, 0], [num_sam, 1]) pred2 = tf.slice(batch2, [0, 0], [num_sam, 1]) tgt1 = tf.slice(batch1, [0, 1], [num_sam, 1]) tgt2 = tf.slice(batch2, [0, 1], [num_sam, 1]) loss = cur_loss + compute_contra_loss(pred1, pred2, tgt1, tgt2) print(loss) return (loss, i + 1) # def sample_compute(i):
tensorflow.slice
12,771
import tensorflow as tf 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) 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, logits, probabilities) def model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator."""
tensorflow.nn.log_softmax
12,772
import tensorflow as tf mean_z = tf.reduce_mean(labeled_poses[1][:, 2]) samples_world = grid.generate( (mean_x - 0.5, 0.0, mean_z - 0.5), (mean_x + 0.5, 1.0, mean_z + 0.5), [self.resolution, self.resolution, self.resolution]) samples_world = tf.reshape(samples_world, [-1, 3]) status = False if status: _, axs = plt.subplots(3, 3) fig_obj_count = 0 # Do the same for the ground truth and predictions num_collisions = 0 prev_intersection = 0 sdf_values = tf.zeros_like(samples_world)[:, 0:1] for classes, sdfs, poses in [(predicted_classes, predicted_sdfs, predicted_poses)]: for i in range(classes.shape[0]): sdf = tf.expand_dims(sdfs[i], -1) sdf = sdf * -1.0 # inside positive, outside zero samples_object = centernet_utils.transform_pointcloud( tf.reshape(samples_world, [1, 1, -1, 3]), tf.reshape(poses[2][i], [1, 1, 3]), tf.reshape(poses[0][i], [1, 1, 3, 3]), tf.reshape(poses[1][i], [1, 1, 3]), inverse=True) * 2.0 samples_object = (samples_object * (29.0/32.0) / 2.0 + 0.5) * 32.0 - 0.5 samples = tf.squeeze(samples_object)
tensorflow.zeros_like
12,773
import tensorflow as tf length: a tensor of shape [1] or an integer, indicating the first dimension of the input tensor t after padding, assuming length <= t.shape[0]. Returns: padded_t: the padded tensor, whose first dimension is length. If the length is an integer, the first dimension of padded_t is set to length statically. """ t_rank = tf.rank(t) t_shape = tf.shape(t) t_d0 = t_shape[0] pad_d0 = tf.expand_dims(length - t_d0, 0) pad_shape = tf.cond( tf.greater(t_rank, 1), lambda: tf.concat([pad_d0, t_shape[1:]], 0), lambda: tf.expand_dims(length - t_d0, 0)) padded_t = tf.concat([t, tf.zeros(pad_shape, dtype=t.dtype)], 0) if not _is_tensor(length): padded_t = _set_dim_0(padded_t, length)
tensorflow.shape
12,774
import tensorflow as tf unfiltered_vocabulary_size: A tf.int64 tensor containing the unfiltered vocab size. filtered_vocabulary_size: A tf.int64 tensor containing the filtered vocab size. """ if not common.IS_ANNOTATIONS_PB_AVAILABLE: return from tensorflow_transform import annotations_pb2 # pylint: disable=g-import-not-at-top message_type = annotations_pb2.VocabularyMetadata.DESCRIPTOR.full_name unfiltered_vocabulary_size = tf.expand_dims(unfiltered_vocabulary_size, 0) filtered_vocabulary_size = tf.expand_dims(filtered_vocabulary_size, 0) file_name = tf.convert_to_tensor([vocab_filename]) descriptor_source = descriptor_pb2.FileDescriptorSet() annotations_pb2.VocabularyMetadata.DESCRIPTOR.file.CopyToProto( descriptor_source.file.add()) descriptor_source_str = b'bytes://' + descriptor_source.SerializeToString() message_proto = tf_utils._encode_proto( # pylint: disable=protected-access { 'unfiltered_vocabulary_size': unfiltered_vocabulary_size, 'filtered_vocabulary_size': filtered_vocabulary_size, 'file_name': file_name,
tensorflow.expand_dims
12,775
import tensorflow as tf 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) with tf.name_scope('LossB'): recon_loss_B = tf.reduce_mean(tf.abs(B - BAB), name='recon_loss') G_loss_B, D_loss_B = LSGAN_losses(B_dis_real, B_dis_fake) LAMBDA = 10.0 self.g_loss = tf.add((G_loss_A + G_loss_B), (recon_loss_A + recon_loss_B) * LAMBDA, name='G_loss_total') self.d_loss = tf.add(D_loss_A, D_loss_B, name='D_loss_total') self.collect_variables('gen', 'discrim') add_moving_summary(recon_loss_A, recon_loss_B, self.g_loss, self.d_loss) def _get_optimizer(self): lr = tf.get_variable('learning_rate', initializer=2e-4, trainable=False) return tf.train.AdamOptimizer(lr, beta1=0.5, epsilon=1e-3) def get_data(datadir, isTrain=True):
tensorflow.add
12,776
import tensorflow as tf scope = tf.get_variable_scope() with tf.variable_scope(scope): if self._max_diffusion_step == 0: 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)
tensorflow.reshape
12,777
import tensorflow as tf 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()) 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) label_ids = tf.reshape(label_ids, [-1]) label_weights = tf.reshape(label_weights, [-1]) one_hot_labels = tf.one_hot( label_ids, depth=bert_config.vocab_size, dtype=tf.float32)
tensorflow.matmul
12,778
import tensorflow as tf if w_init is None: w_init = tf.contrib.layers.variance_scaling_initializer() if b_init is None: b_init = tf.constant_initializer() w = tf.get_variable('W', filter_shape, initializer=w_init) b = None if use_bias: b = tf.get_variable('b', [out_channel], initializer=b_init) if split == 1: conv = tf.nn.conv2d(inputdata, w, strides, padding, data_format=data_format) else: inputs = tf.split(inputdata, split, channel_axis) kernels = tf.split(w, split, 3) outputs = [tf.nn.conv2d(i, k, strides, padding, data_format=data_format) for i, k in zip(inputs, kernels)]
tensorflow.get_variable
12,779
import tensorflow as tf super(TweetSeqModel, self).__init__(batch_size, max_sequence_len, out_vocab_size, c2v, dropout_keep_prob) weights = tf.constant(weights, dtype=tf.float32, name='class_weights') def GetCell(): """Creates an LSTM cell with dropout.""" c = tf.nn.rnn_cell.LSTMCell(hidden_size, use_peepholes=model_params['peepholes'], num_proj=proj_size) if dropout_keep_prob is not None: c = tf.nn.rnn_cell.DropoutWrapper(c, input_keep_prob=dropout_keep_prob) return c # Create the bi-directional LSTM with tf.variable_scope('wordrnn'): with tf.variable_scope('fw'): cell_fw = GetCell() with tf.variable_scope('bw'): cell_bw = GetCell() rnnout, _, _ = tf.nn.bidirectional_rnn(cell_fw, cell_bw, self._inputs, dtype=tf.float32, sequence_length=self.seq_lens)
tensorflow.nn.rnn_cell.DropoutWrapper
12,780
import tensorflow as tf def xavier_init(self, size): in_dim = size[0] out_dim = size[1] xavier_stddev = np.sqrt(2/(in_dim + out_dim)) return tf.Variable(tf.truncated_normal([in_dim, out_dim], stddev=xavier_stddev), dtype=tf.float32) def neural_net(self, X, weights, biases): num_layers = len(weights) + 1 H = 2.0*(X - self.lb)/(self.ub - self.lb) - 1.0 for l in range(0,num_layers-2): W1, W2 = weights[l] b = biases[l] H1 = tf.add(tf.matmul(H, W1), b) H2 = tf.matmul(H, W2) H = tf.tanh(tf.add(H1 * H2, H1)) W1, W2 = weights[-1] b = biases[-1] H1 = tf.add(tf.matmul(H, W1), b) H2 = tf.matmul(H, W2) Y = tf.add(H1 * H2, H1) return Y def fwd_gradients_0(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x0_tf)[0] return tf.gradients(g, self.dummy_x0_tf)[0] def fwd_gradients_1(self, U, x): g = tf.gradients(U, x, grad_ys=self.dummy_x1_tf)[0] return tf.gradients(g, self.dummy_x1_tf)[0]
tensorflow.add
12,781
import tensorflow as tf self.Dale_out, name="in_2"), transpose_b=True, name="3")\ + self.b_out else: new_output = tf.matmul(tf.nn.relu(new_state), self.W_out * self.output_Connectivity, transpose_b=True, name="3") + self.b_out return new_output def compute_predictions(self):
tensorflow.nn.relu
12,782
import tensorflow as tf x_batch_minus_min, x_batch_max = tf_utils.reduce_batch_minus_min_and_max( x, reduce_instance_dims) minus_x_min, x_max = _numeric_combine( # pylint: disable=unbalanced-tuple-unpacking inputs=[x_batch_minus_min, x_batch_max], fn=combine_fn, default_accumulator_value=default_accumulator_value, reduce_instance_dims=reduce_instance_dims) return tf.cast(0 - minus_x_min, output_dtype), tf.cast(x_max, output_dtype) def _min_and_max_per_key( x: common_types.TensorType, key: common_types.TensorType, reduce_instance_dims: bool = True, key_vocabulary_filename: Optional[str] = None,
tensorflow.cast
12,783
import tensorflow as tf images=tf.cast(images,tf.float32)/255.0 l1 = tf.matmul(images, self.w1)+self.b1 l1=tf.nn.relu(l1) l2 = tf.matmul(l1, self.w2)+self.b2 l2=tf.nn.relu(l2) l3=tf.matmul(l2, self.w3)+self.b3
tensorflow.matmul
12,784
import tensorflow as tf lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu*cfgs.BATCH_SIZE) tf.summary.scalar('lr', lr)
tensorflow.summary.scalar
12,785
import tensorflow as tf initializer=tf.constant_initializer(0.0)) layer_out = tf.nn.dropout(tf.matmul(prev_x, weights) + biases, dropout_keep_prob) if activation == 'relu': layer_out = tf.nn.relu(layer_out) elif activation == 'sigmoid': layer_out = tf.nn.sigmoid(layer_out) elif activation == 'tanh': layer_out = tf.nn.tanh(layer_out) else: raise NotImplementedError('activation not recognized') prev_node = hidden_layers_node[i]
tensorflow.nn.sigmoid
12,786
import tensorflow as tf # Initializing the variables init = tf.initialize_all_variables() # Add ops to save and restore all the variables. saver = tf.train.Saver() best_accuracy = 0.0 # sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=False)) if (FLAG == 'train') : # If it is the training mode with tf.Session() as sess: # tf.initialize_all_variables().run() sess.run(init) # .run() f.write("---Save model \n") # Start training for each batch and loop epochs for i in range(config.training_epochs): for start, end in zip(range(0, config.train_count, config.batch_size), # (0, 7352, 1500)
tensorflow.Session
12,787
import tensorflow as tf 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))
tensorflow.identity
12,788
import tensorflow as tf 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.reshape
12,789
import tensorflow as tf Returns: TensorTrain object containing a TT-tensor """ shape = np.array(shape) _validate_input_parameters(is_tensor=True, shape=shape) num_dims = shape.size tt_rank = np.ones(num_dims + 1) tt_cores = num_dims * [None] with tf.name_scope(name): for i in range(num_dims): curr_core_shape = (1, shape[i], 1) tt_cores[i] = tf.zeros(curr_core_shape, dtype=dtype) return TensorTrain(tt_cores, shape, tt_rank) def eye(shape, dtype=tf.float32, name='t3f_eye'):
tensorflow.name_scope
12,790
from tensorflow.python.framework import ops monitor.set_estimator(estimator) if deprecated_monitors: hooks.append(RunHookAdapterForMonitors(deprecated_monitors)) return hooks def _as_graph_element(obj): """Retrieves Graph element.""" graph = ops.get_default_graph() if not isinstance(obj, six.string_types): if not hasattr(obj, "graph") or obj.graph != graph: raise ValueError("Passed %s should have graph attribute that is equal " "to current graph %s." % (obj, graph)) return obj if ":" in obj: element = graph.as_graph_element(obj) else: element = graph.as_graph_element(obj + ":0")
tensorflow.python.framework.ops.get_default_graph
12,791
import tensorflow as tf def format_number(n): """Formats number with thousands commas.""" locale.setlocale(locale.LC_ALL, 'en_US') return locale.format('%d', n, grouping=True) def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [atoi(c) for c in re.split(r'(\d+)', text)] def read_text_lines(filepath): with tf.gfile.Open(filepath, 'r') as f: lines = f.readlines() lines = [l.rstrip() for l in lines] return lines
tensorflow.gfile.Open
12,792
import tensorflow as tf img = tf.image.crop_to_bounding_box(image=img, offset_height=0, offset_width=0, target_height=tf.cast(h_crop, tf.int32), target_width=tf.cast(w_crop, tf.int32)) outputs = fcos.build_whole_detection_network(input_img_batch=img, gtboxes_batch_h=gtboxes_and_label_h, gtboxes_batch_r=gtboxes_and_label_q, gpu_id=i) gtboxes_in_img_q = self.drawer.draw_boxes_with_categories( img_batch=tf.expand_dims(img[0, :, :, :], axis=0), boxes=gtboxes_and_label_q[0, :, :-1], labels=gtboxes_and_label_q[0, :, -1], method=2) tf.summary.image('Compare/gtboxes_q_gpu:%d' % i, gtboxes_in_img_q) gtboxes_in_img_h = self.drawer.draw_boxes_with_categories( img_batch=tf.expand_dims(img[0, :, :, :], axis=0), boxes=gtboxes_and_label_h[0, :, :-1], labels=gtboxes_and_label_h[0, :, -1], method=0)
tensorflow.expand_dims
12,793
import tensorflow as tf loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True) def _train_step(inputs, labels, training): logit, embedding_vector = tf_sparse_demo(inputs, training=training) loss = loss_fn(labels, logit) grads = tf.gradients(loss, tf_sparse_demo.trainable_variables, colocate_gradients_with_ops=True, unconnected_gradients=tf.UnconnectedGradients.NONE) train_op = optimizer.apply_gradients(zip(grads, tf_sparse_demo.trainable_variables)) with tf.control_dependencies([train_op]): loss = tf.identity(loss) return loss, embedding_vector dataset = utils.tf_dataset(*random_samples, batchsize=args.global_batch_size, to_sparse_tensor=True, repeat=1) train_iterator = dataset.make_initializable_iterator() iterator_init = train_iterator.initializer
tensorflow.identity
12,794
import tensorflow as tf def __init__(self, wpm_filepath, merge_prob=1.): """Create a WPM encoder. Args: wpm_filepath: a path to the file containing the vocabulary. merge_prob: the probability of merging tokens while encoding. """ # Load vocabulary file. self._pieces = [] with tf.gfile.Open(wpm_filepath, 'r') as f: for line in f.readlines(): line = line.decode('utf-8') piece = line.strip().split('\t')[0] self._pieces.append(piece) self._merge_prob = merge_prob def _TokenToString(self, token): return py_x_ops.vocab_id_to_token(token, vocab=self._pieces)
tensorflow.gfile.Open
12,795
import tensorflow as tf input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(tf.gfile.Glob(input_pattern)) tf.logging.info("*** Input Files ***")
tensorflow.gfile.Glob
12,796
import tensorflow as tf def _double_factorial_loop_body(n, result, two): result = tf.where(tf.greater_equal(n, two), result * n, result) return n - two, result, two def _double_factorial_loop_condition(n, result, two): return tf.cast(tf.math.count_nonzero(tf.greater_equal(n, two)), tf.bool) def double_factorial(n: TensorLike) -> TensorLike: n = tf.convert_to_tensor(value=n) two = tf.ones_like(n) * 2 result = tf.ones_like(n) _, result, _ = tf.while_loop( cond=_double_factorial_loop_condition, body=_double_factorial_loop_body, loop_vars=[n, result, two]) return result def factorial(n: TensorLike) -> TensorLike: n = tf.convert_to_tensor(value=n) return tf.exp(tf.math.lgamma(n + 1)) def generate_l_m_permutations( max_band: int,
tensorflow.while_loop
12,797
import tensorflow as tf 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 # Mask if mask is not None: # key_masks = tf.sequence_mask(facts_length, tf.shape(facts)[1]) # [B, T]
tensorflow.shape
12,798
import tensorflow as tf image_pyramid=[image_scale], is_training=False, fine_tune_batch_norm=False) if add_flipped_images: with tf.variable_scope(tf.get_variable_scope(), reuse=True): outputs_to_scales_to_logits_reversed = multi_scale_logits( tf.reverse_v2(images, [2]), model_options=model_options, image_pyramid=[image_scale],
tensorflow.get_variable_scope
12,799