seed
stringlengths
25
2.89k
seed_api
stringlengths
14
102
index
int64
0
14.8k
import tensorflow as tf base: Base of the representation. Returns: Corresponding number expressed in base. """ x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1)) x_labels = [] for i in range(num_bits): x_labels.append( tf.floormod( tf.floordiv(tf.to_int32(x_l), tf.to_int32(base)**i), tf.to_int32(base))) res = tf.concat(x_labels, axis=-1) return tf.to_float(res) def embed(self, x): """Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck.
tensorflow.to_int32
4,400
import tensorflow as tf encoder_inputs_ = tf.reshape(flat_inputs, tf.stack([batch_size, time_steps, flat_inputs.get_shape()[1].value])) if pos_embeddings is not None: pos_inputs_ = tf.range(time_steps, dtype=tf.int32) pos_inputs_ = tf.nn.embedding_lookup(pos_embeddings, pos_inputs_) pos_inputs_ = tf.tile(tf.expand_dims(pos_inputs_, axis=0), [batch_size, 1, 1]) encoder_inputs_ = tf.concat([encoder_inputs_, pos_inputs_], axis=2) if other_inputs is not None: encoder_inputs_ = tf.concat([encoder_inputs_, other_inputs], axis=2)
tensorflow.expand_dims
4,401
from tensorflow.python.framework import ops (prev_count * batch_count / update_count)) update_comoment = state_ops.assign_add(comoment, delta_comoment) covariance = _safe_div(comoment, count - 1, 'covariance') with ops.control_dependencies([update_comoment]): update_op = _safe_div(comoment, count - 1, 'update_op') if metrics_collections:
tensorflow.python.framework.ops.control_dependencies
4,402
import tensorflow as tf 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 l3=tf.nn.relu(l3) out=tf.matmul(l3, self.w4)+self.b4 return out def valid_inference(self,images): images=tf.cast(images,tf.float32)/255.0
tensorflow.matmul
4,403
import tensorflow as tf tf.logging.info("label: %s (id = %d)" % (example.label, label_id)) feature = InputFeatures( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id) return feature def file_based_convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, output_file): """Convert a set of `InputExample`s to a TFRecord file.""" writer = tf.python_io.TFRecordWriter(output_file) for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.logging.info("Writing example %d of %d" % (ex_index, len(examples))) feature = convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer) def create_int_feature(values): f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return f features = collections.OrderedDict()
tensorflow.python_io.TFRecordWriter
4,404
import tensorflow as tf kernel_initializer=initializer) start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0]) start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask start_log_probs = tf.nn.log_softmax(start_logits_masked, -1) # logit of the end position with tf.variable_scope("end_logits"): if is_training: # during training, compute the end logits based on the # ground truth of the start position start_positions = tf.reshape(features["start_positions"], [-1]) start_index = tf.one_hot(start_positions, depth=seq_len, axis=-1, dtype=tf.float32) start_features = tf.einsum("lbh,bl->bh", output, start_index) start_features = tf.tile(start_features[None], [seq_len, 1, 1]) end_logits = tf.layers.dense( tf.concat([output, start_features], axis=-1), xlnet_config.d_model, kernel_initializer=initializer, activation=tf.tanh, name="dense_0") end_logits = tf.contrib.layers.layer_norm( end_logits, begin_norm_axis=-1)
tensorflow.reshape
4,405
import tensorflow as tf num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """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"] masked_lm_positions = features["masked_lm_positions"] masked_lm_ids = features["masked_lm_ids"] masked_lm_weights = features["masked_lm_weights"] next_sentence_labels = features["next_sentence_labels"]
tensorflow.logging.info
4,406
import tensorflow as tf # Layers with auxiliary heads # Aux heads speed up training of good feature repsentations early in the network # Add aux heads only if enabled and downsampling width can happen 3 times aux_head_layers = [] if use_aux_head and w % (2 << 3) == 0: aux_head_layers.append(reduction_layers[-1] + 1) with tf.variable_scope('model', reuse=(not is_train)): # "Stem" convolution layer (layer -1) with tf.variable_scope('layer_stem'): X = self._do_conv(X, w, h, in_ch, stem_ch, filter_size=3, no_relu=True, is_train=is_train) # 3x3 convolution stem = (X, w, h, stem_ch) # Core layers of cells block_ch = initial_block_ch aux_logits_list = [] # Stores list of logits from aux heads layers = [stem, stem] # Stores previous layers. layers[i] = (<layer (i + 1)>, <width>, <height>, <channels>) for l in range(L + 2): utils.logger.log('Building layer {}...'.format(l))
tensorflow.variable_scope
4,407
import tensorflow as tf A1 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2)
tensorflow.expand_dims
4,408
import tensorflow as tf # Summarize losses with tf.name_scope("losses"):
tensorflow.name_scope
4,409
import tensorflow as tf kernel_initializer=modeling.create_initializer( bert_config.initializer_range)) input_tensor = modeling.layer_norm(input_tensor) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. output_bias = tf.get_variable( "output_bias", shape=[bert_config.vocab_size], initializer=tf.zeros_initializer()) 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) # The `positions` tensor might be zero-padded (if the sequence is too # short to have the maximum number of predictions). The `label_weights`
tensorflow.nn.bias_add
4,410
import tensorflow as tf dec_inp_dict2["1"] = [ tf.constant(0, tf.int32, shape=[2]) for _ in range(4)]
tensorflow.constant
4,411
import tensorflow as tf hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases) # Linear with tf.name_scope("softmax_linear"): weights = tf.Variable( tf.truncated_normal([32, 10], stddev=1.0 / math.sqrt(float(32))), name="weights") biases = tf.Variable(tf.zeros([10]), name="biases") logits = tf.matmul(hidden2, weights) + biases tf.add_to_collection("logits", logits) # Runs to logit. tf.initialize_all_variables().run()
tensorflow.zeros
4,412
import tensorflow as tf Returns ------- A tensor. """ if axis < 0: dims = get_ndim(tensors[0]) if dims: axis = axis % dims else: axis = 0 try: return tf.concat_v2([x for x in tensors], axis) except AttributeError: return tf.concat(axis=axis, values=[x for x in tensors]) def _normalize_axis(axis, ndim): if isinstance(axis, tuple): axis = list(axis) if isinstance(axis, list): for i, a in enumerate(axis): if a is not None and a < 0: axis[i] = a % ndim
tensorflow.concat_v2
4,413
import tensorflow as tf padding="same" ) shortcut = self.__batch_norm("bn{}".format(shortcut_name_post), shortcut) x = self.__conv2d( name="{}2a".format(conv_name_base), inputs=inputs, filter_depth=filter_depth1, kernel_size=1, stride=stride, padding="same", ) x = self.__batch_norm("{}2a".format(bn_name_base), x) x = tf.nn.relu(x) x = self.__conv2d( name="{}2b".format(conv_name_base), inputs=x, filter_depth=filter_depth2, kernel_size=kernel_size, padding="same", stride=1 ) x = self.__batch_norm("{}2b".format(bn_name_base), x) x = tf.nn.relu(x) x = self.__conv2d( name="{}2c".format(conv_name_base),
tensorflow.nn.relu
4,414
import tensorflow as tf def file_based_input_fn_builder(input_file, seq_length, is_training, drop_remainder): """Creates an `input_fn` closure to be passed to TPUEstimator.""" name_to_features = { "input_ids": tf.FixedLenFeature([seq_length], tf.int64), "input_mask": tf.FixedLenFeature([seq_length], tf.int64), "segment_ids": tf.FixedLenFeature([seq_length], tf.int64), "label_ids": tf.FixedLenFeature([], tf.int64), "is_real_example": tf.FixedLenFeature([], tf.int64), } def _decode_record(record, name_to_features): """Decodes a record to a TensorFlow example."""
tensorflow.FixedLenFeature
4,415
import tensorflow.contrib.graph_editor as ge fwd_ops = [op for op in fwd_ops if not '/Assign' in op.name] fwd_ops = [op for op in fwd_ops if not '/read' in op.name] ts_all = ge.filter_ts(fwd_ops, True) # get the tensors ts_all = [t for t in ts_all if '/read' not in t.name]
tensorflow.contrib.graph_editor.filter_ts
4,416
import tensorflow as tf 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)
tensorflow.reduce_mean
4,417
from tensorflow.python.framework import ops self.event_ndims): ndims = tensor_util.constant_value(ndims) sample_ndims = (ndims - self._batch_ndims_static - self._event_ndims_static) if sample_ndims < 0: raise ValueError( "expected batch_ndims(%d) + event_ndims(%d) <= ndims(%d)" % (self._batch_ndims_static, self._event_ndims_static, ndims)) return ops.convert_to_tensor(sample_ndims, name="sample_ndims") else: with ops.name_scope(name="sample_ndims"): sample_ndims = ndims - self.batch_ndims - self.event_ndims if self.validate_args: sample_ndims = control_flow_ops.with_dependencies( [check_ops.assert_non_negative(sample_ndims)], sample_ndims) return sample_ndims def get_dims(self, x, name="get_dims"): """Returns dimensions indexing `sample_shape`, `batch_shape`, `event_shape`.
tensorflow.python.framework.ops.name_scope
4,418
import tensorflow as tf feed_dict={net.data: blobs['data'], net.im_info: blobs['im_info'], net.keep_prob: 1.0} else: feed_dict={net.data: blobs['data'], net.rois: blobs['rois'], net.keep_prob: 1.0} run_options = None run_metadata = None if cfg.TEST.DEBUG_TIMELINE: run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() #theta_tensor = tf.get_default_graph().get_tensor_by_name('spt_trans_theta') cls_score, cls_prob, bbox_pred, rois = sess.run([net.get_output('cls_score'), net.get_output('cls_prob'), net.get_output('bbox_pred'), net.get_output('rois')], feed_dict=feed_dict, options=run_options, run_metadata=run_metadata)
tensorflow.RunMetadata
4,419
import tensorflow as tf click_feature[i] = tf.expand_dims(tf.ones_like(self.labels[i]) , -1) # click_feature[list_size:]=[tf.expand_dims(tf.zeros_like(self.labels[i]) , -1) for _ in range(3*list_size)] click_feature[list_size:list_size+i] =[tf.expand_dims(self.labels[k] , -1) for k in range(i-1,-1,-1)] click_feature[2*list_size:2*list_size+i+1]=[tf.expand_dims(self.types[k] , -1) for k in range(i,-1,-1)] click_feature[3*list_size:3*list_size+list_size-i-1]=[tf.expand_dims(self.types[k] , -1) for k in range(i+1,list_size)] # Predict propensity with a simple network output_propensity_list.append(propensity_network(tf.concat(click_feature, 1), i)) self.click_show=[click_feature[h][0] for h in range(4*list_size)] return tf.concat(output_propensity_list,1) def step(self, session, input_feed, forward_only): """Run a step of the model feeding the given inputs.
tensorflow.concat
4,420
import tensorflow as tf with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): n_out = x.get_shape().as_list()[-1] beta = tf.get_variable('beta', initializer=tf.constant(0.0, shape=[n_out])) gamma = tf.get_variable('gamma', initializer=tf.constant(1.0, shape=[n_out])) batch_mean, batch_var = tf.nn.moments(x, [0], name='moments') ema = tf.train.ExponentialMovingAverage(decay=0.9) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var)
tensorflow.train.ExponentialMovingAverage
4,421
import tensorflow as tf 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.control_dependencies
4,422
import tensorflow as tf tf.set_random_seed(93820985) p = self._testParams() p.train.lr_schedule = ( schedule.ContinuousLearningRateSchedule.Params().Set( start_step=350000, half_life_steps=45000)) mdl = p.Instantiate() mdl.FPropDefaultTheta() mdl.BProp() tf.global_variables_initializer().run() test_utils.CompareToGoldenSingleFloat(self, 4.472597, mdl.loss.eval()) mdl.train_op.run() def testAllLayerParams(self): with self.session(use_gpu=False, graph=tf.Graph()): p = self._testParams() mdl = p.Instantiate()
tensorflow.global_variables_initializer
4,423
import tensorflow as tf loss=total_loss, eval_metrics=eval_metrics, scaffold_fn=scaffold_fn) else: output_spec = tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={"probabilities": probabilities}, scaffold_fn=scaffold_fn)
tensorflow.contrib.tpu.TPUEstimatorSpec
4,424
from tensorflow.python.platform import tf_logging as logging # The code should probably use the step from the checkpoint, because # that's what is being evaluated. if self._estimator is None: raise ValueError("Missing call to set_estimator.") # Check that we are not running evaluation on the same checkpoint. latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir) if latest_path is None: logging.debug("Skipping evaluation since model has not been saved yet " "at step %d.", step) return False if latest_path is not None and latest_path == self._latest_path: logging.debug("Skipping evaluation due to same checkpoint %s for step %d " "as for step %d.", latest_path, step, self._latest_path_step) return False self._latest_path = latest_path self._latest_path_step = step # Run evaluation and log it. validation_outputs = self._estimator.evaluate( x=self.x, y=self.y, input_fn=self.input_fn, batch_size=self.batch_size, steps=self.eval_steps, metrics=self.metrics, name=self.name)
tensorflow.python.platform.tf_logging.debug
4,425
import tensorflow as tf def body(batch, output, i): self_attention_tmp = din_fcn_attention(batch[:, i, :], batch, ATTENTION_SIZE, mask, softmax_stag=1, stag=stag, mode='LIST') self_attention_tmp = tf.reduce_sum(self_attention_tmp, 1) output = output.write(i, self_attention_tmp) return batch, output, i + 1 output_ta = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True, element_shape=(facts[:, 0, :].get_shape())) _, output_op, _ = tf.while_loop(cond, body, [facts, output_ta, 0]) self_attention = output_op.stack() self_attention = tf.transpose(self_attention, perm = [1, 0, 2]) return self_attention def din_fcn_shine(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = tf.concat(facts, 2) if time_major: # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2])
tensorflow.while_loop
4,426
import tensorflow as tf mdl = p.Instantiate() mdl.FPropDefaultTheta() var_grads = py_utils.ComputeGradients(mdl.loss, mdl.vars) summary_utils.CollectVarHistogram(var_grads) def testGradientMult(self): with self.session(use_gpu=False, graph=tf.Graph()): p = self._testParams() mdl = p.Instantiate() mdl.FPropDefaultTheta() var_grads = py_utils.ComputeGradients(mdl.loss, mdl.vars) py_utils.ApplyGradMultiplier(var_grads, -1.1) def testLRDecay(self): with self.session(use_gpu=False, graph=tf.Graph()) as sess: p = self._testParams() tp = p.train tp.lr_schedule.boundaries = [300000, 400000, 500000] tp.lr_schedule.values = [1.0, 0.1, 0.01, 0.001] lrs = tp.lr_schedule.Instantiate() steps = [299999, 300001, 399999, 400001, 499999, 500001] fetches = [lrs.Value(_) for _ in steps] values = sess.run(fetches) self.assertAllClose([1.0, 0.1, 0.1, 0.01, 0.01, 0.001], values) def testBatchSplit(self): def Run(num_splits):
tensorflow.Graph
4,427
import tensorflow as tf output_stride=model_options.output_stride, depth_multiplier=model_options.depth_multiplier, divisible_by=model_options.divisible_by, weight_decay=weight_decay, reuse=reuse, is_training=is_training, preprocess_images=model_options.preprocess_images, preprocessed_images_dtype=model_options.preprocessed_images_dtype, fine_tune_batch_norm=fine_tune_batch_norm, nas_architecture_options=model_options.nas_architecture_options, nas_training_hyper_parameters=nas_training_hyper_parameters, use_bounded_activation=model_options.use_bounded_activation) if model_options.dense_prediction_cell_config is not None: tf.logging.info('Using dense prediction cell config.') dense_prediction_layer = dense_prediction_cell.DensePredictionCell( config=model_options.dense_prediction_cell_config, hparams={ 'conv_rate_multiplier': 16 // model_options.output_stride, }) concat_logits = dense_prediction_layer.build_cell( features, output_stride=model_options.output_stride, crop_size=model_options.crop_size, image_pooling_crop_size=model_options.image_pooling_crop_size, weight_decay=weight_decay, reuse=reuse, is_training=is_training,
tensorflow.logging.info
4,428
import tensorflow as tf self._lr_update = tf.assign(self._lr, self._new_lr) self.saver = tf.train.Saver(tf.global_variables())
tensorflow.global_variables
4,429
import tensorflow as tf A tensor with the kappa loss. """ with tf.name_scope(name): labels = tf.to_float(labels)
tensorflow.name_scope
4,430
from tensorflow.contrib.layers.python.ops import sparse_feature_cross_op hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[83]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_hashed_output_v1_has_collision(self): """Tests the old version of the fingerprint concatenation has collisions. """ # The last 10 bits of 359 and 1024+359 are identical. # As a result, all the crosses collide. t1 = constant_op.constant([[359], [359 + 1024]]) t2 = constant_op.constant([list(range(10)), list(range(10))]) cross = sparse_feature_cross_op.sparse_feature_cross( [t2, t1], hashed_output=True, num_buckets=1024) cross_dense = sparse_ops.sparse_tensor_to_dense(cross) with session.Session(): values = cross_dense.eval() self.assertTrue(numpy.equal(values[0], values[1]).all()) def test_hashed_output_v2_has_no_collision(self): """Tests the new version of the fingerprint concatenation has no collisions. """ # Although the last 10 bits of 359 and 1024+359 are identical. # As a result, all the crosses shouldn't collide. t1 = constant_op.constant([[359], [359 + 1024]])
tensorflow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_cross
4,431
import tensorflow as tf t_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/target_net') e_params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/eval_net') e_params += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/mixing_net' + '/eval_hyper') t_params += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.name + '/mixing_net' + '/target_hyper') with tf.variable_scope('soft_replacement'): self.target_replace_op = [tf.assign(t, e) for t, e in zip(t_params, e_params)] self.sess = tf.Session() self.sess.run(tf.global_variables_initializer())
tensorflow.variable_scope
4,432
import tensorflow as tf self.compute_shape(x_shape[2], self.ff_pool_strides[0][1]), self.compute_shape(x_shape[3], self.ff_pool_strides[0][2]), final_dim] l3_shape = [ x_shape[0], self.compute_shape(l2_shape[1], self.ff_pool_strides[1][0]), self.compute_shape(l2_shape[2], self.ff_pool_strides[1][1]), self.compute_shape(l2_shape[3], self.ff_pool_strides[1][2]), final_dim] else: l2_shape = tf.identity(x_shape) # Initialize hidden layer activities 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
tensorflow.identity
4,433
from tensorflow.keras.layers import Dense, Conv2D, MaxPool2D, Flatten ''' w_init = tf.contrib.layers.variance_scaling_initializer() # glimpse1 = tf.image.extract_glimpse(inputs, [glimpse_size1,glimpse_size1], self.prev_loc, centered=True, normalized=True) # glimpse2 = tf.image.extract_glimpse(inputs, [glimpse_size2,glimpse_size2], self.prev_loc, centered=True, normalized=True) # glimpse2 = tf.image.resize(glimpse2, [glimpse_size1,glimpse_size1]) # glimpse3 = tf.image.extract_glimpse(inputs, [glimpse_size3,glimpse_size3], self.prev_loc, centered=True, normalized=True) # glimpse3 = tf.image.resize(glimpse3, [glimpse_size1,glimpse_size1]) # self.glimpses = tf.concat([glimpse1,glimpse2,glimpse3],axis=-1) # 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) conv2b = 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)(conv2a) conv2c = 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)(conv2b) pool2 = MaxPool2D(pool_size=[2,2])(conv2c) # Block 3 conv3a = Conv2D(padding="same", filters=RNN_SIZE//2, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(pool2) conv3b = Conv2D(padding="same", filters=RNN_SIZE//2, kernel_size=[3, 3], strides=1, data_format='channels_last', kernel_initializer=w_init,activation=tf.nn.relu)(conv3a)
tensorflow.keras.layers.Conv2D
4,434
import tensorflow as tf print("------------------list-------------------") print(outputs) # Get last time step's output feature for a "many to one" style classifier, # as in the image describing RNNs at the top of this page lstm_last_output = outputs[-1] # Get the last element of the array: [?, 32] print("------------------last outputs-------------------") print (lstm_last_output) # Linear activation return tf.matmul(lstm_last_output, config.W['output']) + config.biases['output'] pred_Y = LSTM_Network(X, config) # shape[?,6] print("------------------pred_Y-------------------") print(pred_Y) # Loss,train_step,evaluation l2 = config.lambda_loss_amount * \ sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) # Softmax loss and L2 cost = tf.reduce_mean(
tensorflow.matmul
4,435
import tensorflow as tf
tensorflow.concat
4,436
import tensorflow as tf encoder_outputs.append(encoder_outputs_) encoder_states.append(encoder_state_) new_encoder_input_length.append(encoder_input_length_) encoder_state = tf.concat(encoder_states, 1) return encoder_outputs, encoder_state, new_encoder_input_length def compute_energy(hidden, state, encoder, time=None, input_length=None, prev_weights=None, **kwargs): batch_size = tf.shape(hidden)[0] time_steps = tf.shape(hidden)[1] if encoder.attn_keep_prob is not None: state_noise_shape = [1, tf.shape(state)[1]] if encoder.pervasive_dropout else None state = tf.nn.dropout(state, keep_prob=encoder.attn_keep_prob, noise_shape=state_noise_shape) hidden_noise_shape = [1, 1, tf.shape(hidden)[2]] if encoder.pervasive_dropout else None hidden = tf.nn.dropout(hidden, keep_prob=encoder.attn_keep_prob, noise_shape=hidden_noise_shape) if encoder.mult_attn: state = dense(state, encoder.attn_size, use_bias=False, name='state') hidden = dense(hidden, encoder.attn_size, use_bias=False, name='hidden') return tf.einsum('ijk,ik->ij', hidden, state) y = dense(state, encoder.attn_size, use_bias=not encoder.layer_norm, name='W_a') y = tf.expand_dims(y, axis=1) if encoder.layer_norm: y = tf.contrib.layers.layer_norm(y, scope='layer_norm_state') hidden = tf.contrib.layers.layer_norm(hidden, center=False, scope='layer_norm_hidden')
tensorflow.nn.dropout
4,437
import tensorflow as tf if encoder.final_state == 'concat_last': # concats last states of all backward layers (full LSTM states) encoder_state_ = tf.concat(encoder_states_, axis=1) elif encoder.final_state == 'average':
tensorflow.concat
4,438
import tensorflow as tf def build_anet(self, state_in, name, reuse=False): reg = tf.contrib.layers.l2_regularizer(1e-3) with tf.variable_scope(name, reuse=reuse): layer_a1 = tf.layers.dense(state_in, 512, tf.nn.relu, kernel_regularizer=reg) layer_a2 = tf.layers.dense(layer_a1, 256, tf.nn.relu, kernel_regularizer=reg) mu = tf.layers.dense(layer_a2, self.a_dim, tf.nn.tanh, kernel_regularizer=reg) sigma = tf.layers.dense(layer_a2, self.a_dim, tf.nn.softplus, kernel_regularizer=reg) # sigma = tf.get_variable(name='pi_sigma', shape=self.a_dim, initializer=tf.constant_initializer(0.5)) sigma = tf.clip_by_value(sigma, 0.0, 1.0) norm_dist = tf.distributions.Normal(loc=mu * self.a_bound, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return norm_dist, params class PPO_LSTM(Base): def __init__(self, env, summary_dir='./', gpu=False): self.LR = 1e-4 self.MINIBATCH = 64 self.EPOCHS = 8
tensorflow.get_collection
4,439
import tensorflow as tf 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)) count_up_to = var.count_up_to(3) input_queue = tf.FIFOQueue(30, tf.float32, shared_name="collection_queue") qr = tf.train.QueueRunner(input_queue, [count_up_to]) tf.initialize_all_variables() # Creates a saver. save = tf.train.Saver({"v0": v0}) # Adds a set of collections. tf.add_to_collection("int_collection", 3) tf.add_to_collection("float_collection", 3.5) tf.add_to_collection("string_collection", "hello") tf.add_to_collection("variable_collection", v0)
tensorflow.train.QueueRunner
4,440
import tensorflow as tf matrices: A list of Tensors with shape [..., N_i, M_i] (i.e. a list of matrices with the same batch dimension). dtype: Data type to use. The Tensors in `matrices` must match this dtype. Returns: A matrix with the input matrices stacked along its main diagonal, having shape [..., \sum_i N_i, \sum_i M_i]. """ matrices = [tf.convert_to_tensor(matrix, dtype=dtype) for matrix in matrices] blocked_rows = tf.Dimension(0) blocked_cols = tf.Dimension(0) batch_shape = tf.TensorShape(None) for matrix in matrices: full_matrix_shape = matrix.get_shape().with_rank_at_least(2) batch_shape = batch_shape.merge_with(full_matrix_shape[:-2]) blocked_rows += full_matrix_shape[-2]
tensorflow.convert_to_tensor
4,441
import tensorflow as tf step = tf.to_float(global_step) warmup_steps = tf.to_float(params.warmup_steps) multiplier = params.hidden_size ** -0.5 decay = multiplier * tf.minimum((step + 1) * (warmup_steps ** -1.5), (step + 1) ** -0.5) return learning_rate * decay elif params.learning_rate_decay == "new_warmup_rsqrt_decay": step = tf.to_float(global_step) warmup_steps = tf.to_float(params.warmup_steps) multiplier = params.hidden_size ** -0.5 decay = params.r0 * multiplier * tf.minimum((step + 1) * (warmup_steps ** -1.0) * (warmup_steps ** -0.5), (step + 1) ** -0.5) return learning_rate * decay elif params.learning_rate_decay == "rnnplus_warmup_decay": step = tf.to_float(global_step) n = float(len(params.device_list)) warmup_steps = tf.to_float(params.warmup_steps) decay = tf.minimum(1 + step * (n - 1) / (n * warmup_steps), tf.minimum(n, n * ((2*n) ** ((params.s - n * step) / (params.e - params.s))))) return tf.maximum(learning_rate * decay, 5e-6)
tensorflow.minimum
4,442
import tensorflow as tf print(pred_Y) # Loss,train_step,evaluation l2 = config.lambda_loss_amount * \ sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) # Softmax loss and L2 cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(pred_Y, Y)) + l2 train_step = tf.train.AdamOptimizer( learning_rate=config.learning_rate).minimize(cost) correct_prediction = tf.equal(tf.argmax(pred_Y, 1), tf.argmax(Y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32))
tensorflow.nn.softmax_cross_entropy_with_logits
4,443
from tensorflow.python.framework import ops ops.RegisterShape("Sin")(common_shapes.unchanged_shape) ops.RegisterShape("Sqrt")(common_shapes.unchanged_shape)
tensorflow.python.framework.ops.RegisterShape
4,444
import tensorflow as tf cifar10.LEARNING_RATE_DECAY_FACTOR, staircase=True) # Create an optimizer that performs gradient descent. opt = tf.train.GradientDescentOptimizer(lr) # Calculate the gradients for each model tower. tower_grads = [] with tf.variable_scope(tf.get_variable_scope()): for i in xrange(FLAGS.num_gpus): with tf.device('/gpu:%d' % i): with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope: # Calculate the loss for one tower of the CIFAR model. This function # constructs the entire CIFAR model but shares the variables across # all towers. loss = tower_loss(scope) # Reuse variables for the next tower. tf.get_variable_scope().reuse_variables()
tensorflow.device
4,445
import tensorflow as tf trainable=False) batch_action_arguments = tf.Variable(data.batch_actions_arguments, name='actions_arguments', trainable=False) histories = tf.gather(batch_histories, self.batch_idx) actions_template = tf.gather(batch_actions_template, self.batch_idx) actions_arguments = tf.gather(batch_action_arguments, self.batch_idx) with tf.name_scope('model'): encoder_embedding = embedding( input=histories, length=histories_vocabulary_length,
tensorflow.gather
4,446
import tensorflow as tf y_permute_dim = [y_permute_dim.pop(-2)] + y_permute_dim xt = tf.reshape(x, [-1, x_shape[-1]]) yt = tf.reshape(tf.transpose(y, perm=y_permute_dim), [y_shape[-2], -1]) return tf.reshape( tf.matmul(xt, yt), x_shape[:-1] + y_shape[:-2] + y_shape[-1:]) out = tf.matmul(x, y) return out def get_ndim(x):
tensorflow.matmul
4,447
import tensorflow as tf # values: [batch_size, step_size, vocab_size] # answers: [batch_size, step_size] def _mask_and_accuracy(values, answers, loss_weights): values = tf.argmax(values,axis=2) x = tf.cast(values, dtype=tf.int32) y = tf.cast(answers, dtype=tf.int32) res = tf.equal(x, y) res = tf.cast(res, dtype=tf.float32) res = tf.multiply(res, loss_weights)
tensorflow.cast
4,448
import tensorflow as tf v_diff = state_ops.assign(vstar, mu_t * (var - vstar), use_locking=self._use_locking) with ops.control_dependencies([v_diff]): # run v_diff operation before scatter_add scaled_grad = scatter_add(vstar, indices, grad) var_update = state_ops.assign_sub(var, lr_t * (scaled_grad + gold)) return control_flow_ops.group(*[var_update, ]) def _apply_sparse(self, grad, var): # sparse grad (only for the shakespeare model) return self._apply_sparse_shared( grad.values, var, grad.indices, lambda x, i, v: state_ops.scatter_add(x, i, v)) def set_params(self, cog, avg_gradient, client): with client.model.graph.as_default(): all_vars = tf.trainable_variables() for variable, value in zip(all_vars, cog): vstar = self.get_slot(variable, "vstar") vstar.load(value, client.model.sess) # get old gradient _, gprev = client.get_grads() # Find g_t - F'(old) gdiff = [g1 - g2 for g1, g2 in zip(avg_gradient, gprev)] with client.model.graph.as_default(): all_vars = tf.trainable_variables() for variable, grad in zip(all_vars, gdiff):
tensorflow.trainable_variables
4,449
import tensorflow as tf def get_initial_state(name='initial_state'): if encoder.train_initial_states: initial_state = get_variable(name, initializer=tf.zeros(cell_state_size)) return tf.tile(tf.expand_dims(initial_state, axis=0), [batch_size, 1])
tensorflow.zeros
4,450
import tensorflow as tf segment_ids = features["segment_ids"] label_ids = features["label_ids"] is_real_example = None if "is_real_example" in features: is_real_example = tf.cast(features["is_real_example"], dtype=tf.float32) else: is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)
tensorflow.cast
4,451
import tensorflow as tf predict_input_fn = input_fn_builder( features=features, seq_length=FLAGS.max_seq_length, max_predictions_per_seq=FLAGS.max_predictions_per_seq) result = estimator.predict(input_fn=predict_input_fn) output_predict_file = os.path.join(FLAGS.output_dir, FLAGS.input_file.split('.')[0] + ".json") parse_result(result, all_tokens, output_predict_file) if __name__ == "__main__": tf.app.run()
tensorflow.app.run
4,452
import tensorflow as tf """Build the inference graph using canonical LSTM cells.""" # Slightly better results can be obtained with forget gate biases # initialized to 1 but the hyperparameters of the model would need to be # different than reported in the paper. cell = self._get_lstm_cell(config, is_training) if is_training and config.keep_prob < 1: cell = tf.contrib.rnn.DropoutWrapper( cell, output_keep_prob=config.keep_prob) cell = tf.contrib.rnn.MultiRNNCell( [cell for _ in range(config.num_layers)], state_is_tuple=True)
tensorflow.contrib.rnn.DropoutWrapper
4,453
import tensorflow as tf # (T,B,D) => (B,T,D) facts = tf.array_ops.transpose(facts, [1, 0, 2]) # Trainable parameters 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] query = tf.layers.dense(query, facts_size, activation=None, name='f1_trans_shine' + stag) query = prelu(query) 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, facts_size, activation=tf.nn.sigmoid, name='f1_shine_att' + stag) d_layer_2_all = tf.layers.dense(d_layer_1_all, facts_size, activation=tf.nn.sigmoid, name='f2_shine_att' + stag) d_layer_2_all = tf.reshape(d_layer_2_all, tf.shape(facts)) output = d_layer_2_all return output
tensorflow.layers.dense
4,454
import tensorflow as tf os.makedirs(model_version_dir) except OSError as ex: pass # ignore existing dir with tf.Session() as sess: input0_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_INPUT0:0") input1_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_INPUT1:0") output0_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_OUTPUT0:0") output1_tensor = tf.get_default_graph().get_tensor_by_name( "TENSOR_OUTPUT1:0") tf.saved_model.simple_save(sess, model_version_dir + "/model.savedmodel", inputs={ "INPUT0": input0_tensor, "INPUT1": input1_tensor }, outputs={ "OUTPUT0": output0_tensor, "OUTPUT1": output1_tensor }) def create_savedmodel_modelconfig(models_dir, max_batch, model_version,
tensorflow.saved_model.simple_save
4,455
import tensorflow as tf optimizer, n_iters=hparams.n_warmup_iters, n_samples=hparams.n_samples, step_fn=step_fn) # Training samples = tf.random_normal( shape=[hparams.n_samples, hparams.x_dim], dtype=tf.float32) start_time = time.time() fit(dynamics, samples, optimizer,
tensorflow.random_normal
4,456
import tensorflow as tf log("Checkpoint path: {}".format(checkpoint_fpath)) log("Loading training data from: {}".format(metadat_fpath)) log("Using model: Tacotron") log(hparams_debug_string()) # Start by setting a seed for repeatability tf.set_random_seed(hparams.tacotron_random_seed) # Set up data feeder coord = tf.train.Coordinator() with tf.variable_scope("datafeeder") as scope: feeder = Feeder(coord, metadat_fpath, hparams) # Set up model: global_step = tf.Variable(0, name="global_step", trainable=False) model, stats = model_train_mode(args, feeder, hparams, global_step) eval_model = model_test_mode(args, feeder, hparams, global_step) # Embeddings metadata char_embedding_meta = os.path.join(meta_folder, "CharacterEmbeddings.tsv") if not os.path.isfile(char_embedding_meta): with open(char_embedding_meta, "w", encoding="utf-8") as f: for symbol in symbols: if symbol == " ": symbol = "\\s" # For visual purposes, swap space with \s f.write("{}\n".format(symbol))
tensorflow.Variable
4,457
from tensorflow.python.framework import ops self._saved_model_loader_value = None self._loaded_saved_model_graph = None # TODO(b/160294509): Use tf.compat.v1 when we stop supporting TF 1.15. if ops.executing_eagerly_outside_functions(): _check_tensorflow_version() # The model must be tracked by assigning to an attribute of the Keras
tensorflow.python.framework.ops.executing_eagerly_outside_functions
4,458
import tensorflow as tf if input_type == InputType.TENSOR: self.input = tf.placeholder(tf.float32, shape=[None, 224, 224, 3], name="input") self.input_tensor = self.input elif input_type == InputType.BASE64_JPEG: from image_utils import load_base64_tensor self.input = tf.placeholder(tf.string, shape=(None,), name="input") self.input_tensor = load_base64_tensor(self.input) else: raise ValueError("invalid input type '{}'".format(input_type)) x = self.input_tensor x = tf.pad(x, [[0, 0], [3, 3], [3, 3], [0, 0]], 'CONSTANT')
tensorflow.placeholder
4,459
import tensorflow as tf vf_old, vf_old_params = self.build_cnet(batch['state'], 'oldvf') self.vf, vf_params = self.build_cnet(batch['state'], 'vf') self.vf_eval, _ = self.build_cnet(self.state, 'vf', reuse=True) self.sample_action = tf.squeeze(pi_eval.sample(1), axis=0) self.eval_action = pi_eval.mode() self.global_step = tf.train.get_or_create_global_step() self.saver = tf.train.Saver() # Loss functions and training epsilon_decay = tf.train.polynomial_decay(self.EPSILON, self.global_step, self.EPS_LEN, 0.1, power=0) ratio = tf.maximum(pi.prob(batch['actions']), 1e-6) / tf.maximum(pi_old.prob(batch['actions']), 1e-6) ratio = tf.clip_by_value(ratio, 0, 10) surr1 = batch['advantage'] * ratio surr2 = batch['advantage'] * tf.clip_by_value(ratio, 1 - epsilon_decay, 1 + epsilon_decay) loss_pg = - 2.0 * tf.reduce_mean(tf.minimum(surr1, surr2)) loss_vf = 0.5 * tf.reduce_mean(tf.square(batch['rewards'] - self.vf)) loss_entropy = - 0.01 * tf.reduce_mean(pi.entropy()) loss = loss_pg + loss_vf + loss_entropy opt = tf.train.AdamOptimizer(self.LR)
tensorflow.train.polynomial_decay
4,460
import tensorflow as tf ValueError: If scale is negative or if scale is not a float. """ if isinstance(scale, numbers.Integral): raise ValueError('scale cannot be an integer: %s' % (scale,)) if isinstance(scale, numbers.Real): if scale < 0.: raise ValueError('Setting a scale less than 0 on a regularizer: %g.' % scale) if scale == 0.: return lambda _: None def l2(weights, name='l2_regularizer'): """Applies l2 regularization to weights.""" with tf.name_scope(name): my_scale = tf.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') return tf.multiply(my_scale, nn.l2_loss(weights), name=name) return l2 def discretized_mix_logistic_loss(inputs, predictions, sum_all=True, name='disretized_mix_logistic_loss'): """log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to.
tensorflow.convert_to_tensor
4,461
import tensorflow as tf layer_c2 = tf.layers.dense(layer_c1, 256, tf.nn.relu, kernel_regularizer=reg) vf = tf.layers.dense(layer_c2, 1, kernel_regularizer=reg) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return vf, params
tensorflow.get_collection
4,462
import tensorflow as tf axis = _normalize_axis(axis, get_ndim(x)) if x.dtype.base_dtype == tf.bool: x = tf.cast(x, tf.float32) m = tf.reduce_mean(x, axis=axis, keep_dims=True) devs_squared = tf.square(x - m) return tf.reduce_mean(devs_squared, axis=axis, keep_dims=keepdims)
tensorflow.reduce_mean
4,463
import tensorflow as tf attention_states[0] += attns elif chaining_strategy in ('map_attns', 'map_states', 'map_outputs'): if chaining_strategy == 'map_attns': x = attns elif chaining_strategy == 'map_outputs': x = decoder_outputs else: x = states shape = [x.get_shape()[-1], attention_states[0].get_shape()[-1]] w = tf.get_variable("map_attns/matrix", shape=shape) b = tf.get_variable("map_attns/bias", shape=shape[-1:]) x = tf.einsum('ijk,kl->ijl', x, w) + b if chaining_non_linearity: x = tf.nn.tanh(x) attention_states[0] += x outputs, attention_weights, _, _, samples, beam_fun, initial_data = attention_decoder( attention_states=attention_states, initial_state=encoder_state,
tensorflow.get_variable
4,464
import tensorflow as tf conv6 = utils.conv2d_basic(pool5, W6, b6) relu6 = tf.nn.relu(conv6, name="relu6")
tensorflow.nn.relu
4,465
import tensorflow as tf q_tp1_best_masked = (1.0 - done_mask_ph) * q_tp1_best # compute RHS of bellman equation q_t_selected_target = rew_t_ph + gamma * q_tp1_best_masked # compute the error (potentially clipped) td_error = q_t_selected - tf.stop_gradient(q_t_selected_target) errors = U.huber_loss(td_error) weighted_error = tf.reduce_mean(importance_weights_ph * errors) # compute optimization op (potentially with gradient clipping) if grad_norm_clipping is not None:
tensorflow.stop_gradient
4,466
import tensorflow as tf concat = tf.concat([flat1b, loc_layer2],1) # goal_layer2 h1 = Dense(units=RNN_SIZE)(concat) h2 = Dense(units=RNN_SIZE)(h1) self.h3 = tf.nn.relu(h2+concat) #Recurrent network for temporal dependencies lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(RNN_SIZE,state_is_tuple=True) c_init = np.zeros((1, lstm_cell.state_size.c), np.float32) h_init = np.zeros((1, lstm_cell.state_size.h), np.float32) state_init = [c_init, h_init] c_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.c]) h_in = tf.placeholder(tf.float32, [1, lstm_cell.state_size.h]) state_in = (c_in, h_in) rnn_in = tf.expand_dims(self.h3, [0]) step_size = tf.shape(inputs)[:1] state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in) lstm_outputs, lstm_state = tf.nn.dynamic_rnn( lstm_cell, rnn_in, initial_state=state_in, sequence_length=step_size, time_major=False) lstm_c, lstm_h = lstm_state state_out = (lstm_c[:1, :], lstm_h[:1, :]) self.rnn_out = tf.reshape(lstm_outputs, [-1, RNN_SIZE])
tensorflow.placeholder
4,467
import tensorflow as tf # pylint: disable=no-value-for-parameter,unexpected-keyword-arg """LSTM layers.""" import tensorflow as tf from deepr.layers import base @base.layer(n_in=2, n_out=3) def LSTM(tensors, num_units: int, bidirectional: bool = False, **kwargs): """LSTM layer.""" words, nwords = tensors t = tf.transpose(words, perm=[1, 0, 2]) lstm_cell_fw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs) outputs_fw, (hidden_fw, output_fw) = lstm_cell_fw(t, dtype=tf.float32, sequence_length=nwords) if bidirectional: lstm_cell_bw = tf.contrib.rnn.LSTMBlockFusedCell(num_units=num_units, **kwargs) lstm_cell_bw = tf.contrib.rnn.TimeReversedFusedRNN(lstm_cell_bw) outputs_bw, (hidden_bw, output_bw) = lstm_cell_bw(t, dtype=tf.float32, sequence_length=nwords) outputs = tf.concat([outputs_fw, outputs_bw], axis=-1) hidden = tf.concat([hidden_fw, hidden_bw], axis=-1) output = tf.concat([output_fw, output_bw], axis=-1) else: outputs = outputs_fw hidden = hidden_fw
tensorflow.contrib.rnn.LSTMBlockFusedCell
4,468
import tensorflow as tf return lambda z: tf.maximum(tf.minimum(z, 1), 0) else: raise NotImplementedError(nl_type) def update_params(self, kwargs): """Update the class attributes with kwargs.""" if kwargs is not None: for k, v in kwargs.iteritems(): setattr(self, k, v) def symmetric_weights(self, w, name): """Apply symmetric weight sharing.""" conv_w_t = tf.transpose(w, (2, 3, 0, 1)) conv_w_symm = 0.5 * (conv_w_t + tf.transpose(conv_w_t, (1, 0, 2, 3))) conv_w = tf.transpose(conv_w_symm, (2, 3, 0, 1), name=name) return conv_w def prepare_tensors(self): """ Prepare recurrent/forward weight matrices. (np.prod([h, w, k]) / 2) - k params in the surround filter """ # FEEDFORWARD AND FEEDBACK KERNELS lower_feats = self.in_k for idx, (higher_feats, ff_dhw, fb_dhw) in enumerate(
tensorflow.transpose
4,469
import tensorflow as tf inputs = tf.TensorArray(dtype=tf.int64, size=time_steps).unstack(tf.to_int64(tf.transpose(decoder_inputs))) states = tf.TensorArray(dtype=tf.float32, size=time_steps) weights = tf.TensorArray(dtype=tf.float32, size=time_steps) attns = tf.TensorArray(dtype=tf.float32, size=time_steps) initial_symbol = inputs.read(0) # first symbol is BOS initial_input = embed(initial_symbol) initial_pos = tf.zeros([batch_size], tf.float32) initial_weights = tf.zeros(tf.shape(attention_states[align_encoder_id])[:2]) zero_context = tf.zeros(shape=tf.shape(attention_states[align_encoder_id][:,0])) # FIXME with tf.variable_scope('decoder_{}'.format(decoder.name)): initial_context, _ = look(0, initial_output, initial_input, pos=initial_pos, prev_weights=initial_weights, context=zero_context) initial_data = tf.concat([initial_state, initial_context, tf.expand_dims(initial_pos, axis=1), initial_weights], axis=1) context_size = initial_context.shape[1].value def get_logits(state, ids, time): # for beam-search decoding
tensorflow.shape
4,470
from tensorflow.contrib.layers.python.layers import feature_column for k, v in metrics.items() if k in _METRIC_KEYS}) def benchmarkMatrixData(self): iris = test_data.prepare_iris_data_for_logistic_regression() cont_feature = feature_column.real_valued_column('feature', dimension=4) bucketized_feature = feature_column.bucketized_column( cont_feature, test_data.get_quantile_based_buckets(iris.data, 10))
tensorflow.contrib.layers.python.layers.feature_column.real_valued_column
4,471
import tensorflow as tf with tf.variable_scope(scope):
tensorflow.variable_scope
4,472
import tensorflow as tf self.rnn_nunroll = rnn_nunroll self.do_rnn = do_rnn self.target_weight_strategy = target_weight_strategy def assign_lr(self, sess, lr_new): assert self.mode == 'train' sess.run(tf.assign(self._lr, lr_new)) return sess.run(self._lr_summary) def prepare_train_batch(self, charts, randomize_charts=False, **kwargs): # process kwargs exclude_kwarg_names = ['exclude_onset_neighbors', 'exclude_pre_onsets', 'exclude_post_onsets', 'include_onsets']
tensorflow.assign
4,473
from tensorflow.python.ops import math_ops class_id) fn = set_ops.set_size(set_ops.set_difference(predictions_idx, labels, aminusb=False)) fn = math_ops.to_double(fn) if weights is not None: weights = math_ops.to_double(weights) fn = math_ops.mul(fn, weights)
tensorflow.python.ops.math_ops.to_double
4,474
import tensorflow as tf 'zero_debias_moving_mean': True, 'fused': fused_batch_norm, } inputs.get_shape().assert_has_rank(2) if log(final_size, 2) != int(log(final_size, 2)): raise ValueError('`final_size` (%i) must be a power of 2.' % final_size) if final_size < 8: raise ValueError('`final_size` (%i) must be greater than 8.' % final_size) end_points = {} num_layers = int(log(final_size, 2)) - 1 with tf.compat.v1.variable_scope(scope, values=[inputs], reuse=reuse) as scope: with slim.arg_scope([normalizer_fn], **normalizer_fn_args): with slim.arg_scope([slim.conv2d_transpose], normalizer_fn=normalizer_fn, stride=2, kernel_size=4): net = tf.expand_dims(tf.expand_dims(inputs, 1), 1) # First upscaling is different because it takes the input vector. current_depth = depth * 2 ** (num_layers - 1) scope = 'deconv1' net = slim.conv2d_transpose(
tensorflow.compat.v1.variable_scope
4,475
import tensorflow as tf with tf.variable_scope('fw'): cell_fw = GetCell() with tf.variable_scope('bw'): cell_bw = GetCell()
tensorflow.variable_scope
4,476
import tensorflow as tf if y is None: y = silverman_rule_of_thumb(N) K = 1/(2*D-3) A1 = euclidean_norm_squared(tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)), axis=2) A = (1/(N**2)) * tf.reduce_sum((1/tf.sqrt(y + K*A1))) B1 = euclidean_norm_squared(X, axis=1) B = (2/N)*tf.reduce_sum((1/tf.sqrt(y + 0.5 + K*B1))) return (1/tf.sqrt(1+y)) + A - B def cw_choose(z_dim: int): if z_dim == 1: return cw_1d elif z_dim == 2: return cw_2d elif z_dim >= 20: return cw else:
tensorflow.sqrt
4,477
from tensorflow.python.ops import variable_scope tuple. """ with variable_scope.variable_scope(name, 'recall', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions(
tensorflow.python.ops.variable_scope.variable_scope
4,478
import tensorflow as tf k = tf.transpose(k, [0, 2, 1, 3]) v = tf.transpose(v, [0, 2, 1, 3]) if attention_mask is not None: attention_mask = tf.reshape( attention_mask, [batch_size, 1, to_seq_length, 1]) # 'new_embeddings = [B, N, F, H]' new_embeddings = dot_product_attention(q, k, v, attention_mask, attention_probs_dropout_prob) return tf.transpose(new_embeddings, [0, 2, 1, 3]) def attention_ffn_block(layer_input, hidden_size=768, attention_mask=None, num_attention_heads=1, attention_head_size=64, attention_probs_dropout_prob=0.0,
tensorflow.transpose
4,479
import tensorflow as tf Kuu = feat.Kuu(kern, jitter=settings.numerics.jitter_level) # M x M Luu = tf.cholesky(Kuu) # M x M if not white: q_mu = tf.matrix_triangular_solve(Luu, q_mu, lower=True) Luu_tiled = tf.tile(Luu[None, :, :], [num_func, 1, 1]) # remove line once issue 216 is fixed q_sqrt_r = tf.matrix_triangular_solve(Luu_tiled, q_sqrt_r, lower=True) Li_eKuf = tf.matrix_triangular_solve(Luu, eKuf, lower=True) # M x N fmean = tf.matmul(Li_eKuf, q_mu, transpose_a=True) eKff = expectation(pXnew, kern) # N (psi0) eKuffu = expectation(pXnew, (kern, feat), (kern, feat)) # N x M x M (psi2) Luu_tiled = tf.tile(Luu[None, :, :], [num_data, 1, 1]) # remove this line, once issue 216 is fixed Li_eKuffu = tf.matrix_triangular_solve(Luu_tiled, eKuffu, lower=True) Li_eKuffu_Lit = tf.matrix_triangular_solve(Luu_tiled, tf.matrix_transpose(Li_eKuffu), lower=True) # N x M x M cov = tf.matmul(q_sqrt_r, q_sqrt_r, transpose_b=True) # D x M x M if mean_function is None or isinstance(mean_function, mean_functions.Zero): e_related_to_mean = tf.zeros((num_data, num_func, num_func), dtype=settings.float_type) else: # Update mean: \mu(x) + m(x) fmean = fmean + expectation(pXnew, mean_function) # Calculate: m(x) m(x)^T + m(x) \mu(x)^T + \mu(x) m(x)^T, # where m(x) is the mean_function and \mu(x) is fmean e_mean_mean = expectation(pXnew, mean_function, mean_function) # N x D x D Lit_q_mu = tf.matrix_triangular_solve(Luu, q_mu, adjoint=True)
tensorflow.matrix_triangular_solve
4,480
import tensorflow as tf 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)
tensorflow.nn.softmax
4,481
import tensorflow as tf init_sd = 1.0 / np.sqrt(self.embedding_size) # Embedding variables entity_var_shape = [entity_cnt, self.embedding_size] rel_var_shape = [rel_cnt, self.embedding_size] entity_init = tf.truncated_normal(entity_var_shape, stddev=init_sd) rel_init = tf.truncated_normal(rel_var_shape, stddev=init_sd) # Ensure maxnorm constraints are initially satisfied entity_init = dense_maxnorm(entity_init, self.maxnorm) self.entity_embedding_vars = tf.Variable(entity_init) self.rel_embedding_vars = tf.Variable(rel_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.head_input) tail_embed = tf.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input) rel_embed = tf.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input) # Relationship vector acts as a translation in entity embedding space diff_vec = tail_embed - (head_embed + rel_embed)
tensorflow.Variable
4,482
import tensorflow as tf 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(tf.float32), 'image/object/class/label': tf.io.VarLenFeature(tf.int64),
tensorflow.io.VarLenFeature
4,483
import tensorflow as tf output_1 = contrib.layers.fully_connected(dropout3_1, n_output_1, activation_fn=None, scope="output_1") output_2 = contrib.layers.fully_connected(dropout3_2, n_output_2, activation_fn=None, scope="output_2") with tf.variable_scope("loss"): loss_base_1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_1, logits=output_1)) loss_base_2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_2, logits=output_2)) reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) loss_total = loss_base_1 + loss_base_2 + tf.reduce_sum(reg_losses) with tf.variable_scope("evaluation"): accuracy_1 = tf.reduce_mean(tf.cast(tf.equal( tf.argmax(output_1, axis=-1), tf.argmax(y_1, axis=-1)), tf.float32), name="accuracy_1") accuracy_2 = tf.reduce_mean(tf.cast(tf.equal( tf.argmax(output_2, axis=-1), tf.argmax(y_2, axis=-1)), tf.float32), name="accuracy_2") accuracy = tf.divide(accuracy_1 + accuracy_2, 2.0, name="accuracy") with tf.variable_scope("train"): global_step = tf.get_variable("global_step", shape=(), dtype=tf.int32, trainable=False) train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss_total, global_step=global_step) with tf.variable_scope("summary"): summary_loss_total = tf.summary.scalar("loss_total", loss_total) summary_accuracy_test = tf.summary.scalar("accuracy_test", accuracy) summary_accuracy_train = tf.summary.scalar("accuracy_train", accuracy) # standardization train_X_reshaped = train_X.reshape([train_X.shape[0], -1]) train_X_means = np.mean(train_X_reshaped, axis=0, keepdims=True)
tensorflow.argmax
4,484
import tensorflow as tf # @1. split sequence with tf.variable_scope('split_seq'): block_num = tf.cast(tf.ceil(tf.divide(tf.cast(sl, tf.float32), tf.cast(block_len, tf.float32))), tf.int32) comp_len = block_num * block_len - sl rep_tensor_comp = tf.concat([rep_tensor, tf.zeros([bs, comp_len, input_dim], tf.float32)], 1) rep_mask_comp = tf.concat([rep_mask, tf.cast(tf.zeros([bs, comp_len], tf.int32), tf.bool)], 1) rep_tensor_split = tf.reshape(rep_tensor_comp, [bs, block_num, block_len, input_dim]) # bs,bn,bl,d rep_mask_split = tf.reshape(rep_mask_comp, [bs, block_num, block_len]) # bs,bn,bl # non-linear
tensorflow.zeros
4,485
import tensorflow as tf self.enqueue_op = queue.enqueue(self.queue_input_tensors) self.input_tensors = queue.dequeue() self.predictions, self.loss = self.get_predictions_and_loss(*self.input_tensors) self.global_step = tf.Variable(0, name="global_step", trainable=False) self.reset_global_step = tf.assign(self.global_step, 0) learning_rate = tf.train.exponential_decay(self.config["learning_rate"], self.global_step, self.config["decay_frequency"], self.config["decay_rate"], staircase=True) trainable_params = tf.trainable_variables() gradients = tf.gradients(self.loss, trainable_params) gradients, _ = tf.clip_by_global_norm(gradients, self.config["max_gradient_norm"]) optimizers = { "adam" : tf.train.AdamOptimizer, "sgd" : tf.train.GradientDescentOptimizer } optimizer = optimizers[self.config["optimizer"]](learning_rate) self.train_op = optimizer.apply_gradients(zip(gradients, trainable_params), global_step=self.global_step) def start_enqueue_thread(self, session): with open(self.config["train_path"]) as f:
tensorflow.clip_by_global_norm
4,486
import tensorflow as tf train_file, task_name) tf.logging.info("***** Running training *****")
tensorflow.logging.info
4,487
import tensorflow as tf batch_nums = tf.expand_dims(batch_nums, axis=1) # shape (batch_size, 1) batch_nums = tf.tile(batch_nums, [1, passage_length]) # shape (batch_size, passage_length) step_nums = tf.range(0, limit=passage_length) # [passage_length] step_nums = tf.expand_dims(step_nums, axis=0) # shape (1, passage_length) step_nums = tf.tile(step_nums, [batch_size, 1]) # shape (batch_size, passage_length) indices = tf.stack((batch_nums, step_nums, passage_word_idx), axis=2) # shape (batch_size, passage_length, 3) indices = tf.reshape(indices, [-1, 3]) #[batch_size * passage_length, 3] indices = tf.cast(indices, tf.int64) shape = [batch_size, passage_length, extended_vsize] shape = tf.cast(shape, tf.int64) attn_dist = tf.reshape(attn_dist, shape=[-1]) # [batch_size*passage_length] one_hot_spare_rep = tf.SparseTensor(indices=indices, values=attn_dist, dense_shape=shape) # [batch_size, passage_length, extended_vsize] if passage_mask is not None: passage_mask = tf.expand_dims(passage_mask, axis=-1) one_hot_spare_rep = one_hot_spare_rep * passage_mask one_hot_spare_rep = tf.sparse_reduce_sum(one_hot_spare_rep, axis=1) # [batch_size, extended_vsize] vocab_dist = tf.add(vocab_dist, one_hot_spare_rep) if self.options.add_first_word_prob_for_phrase: vocab_dist = tf.nn.softmax(vocab_dist) # normalize return vocab_dist # [batch_size, extended_vsize]
tensorflow.SparseTensor
4,488
import tensorflow as tf save_path = os.path.join(self.get_temp_dir(), "gpu") with tf.Session("", graph=tf.Graph()) as sess: with sess.graph.device("/gpu:0"): v0_1 = tf.Variable(123.45) save = tf.train.Saver({"v0": v0_1}) tf.initialize_all_variables().run() save.save(sess, save_path)
tensorflow.train.Saver
4,489
from tensorflow.python.framework import ops @ops.RegisterGradient("SparseScatter") def _sparse_scatter_grad(op, grad):
tensorflow.python.framework.ops.RegisterGradient
4,490
import tensorflow as tf scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tensorflow.train.init_from_checkpoint
4,491
import tensorflow as tf def pool(inp, name, kind, size, stride, padding='SAME'): assert kind in ['max', 'avg'] strides = [1, stride, stride, 1] sizes = [1, size, size, 1] with tf.variable_scope(name): if kind == 'max': out = tf.nn.max_pool(inp, sizes, strides=strides, padding=padding, name=kind) else: out = tf.nn.avg_pool(inp, sizes, strides=strides, padding=padding, name=kind) return out def ResNet18(inp, phase, num_outputs=1000, alpha=0.0): def residual_block(inp, phase, alpha=0.0,nom='a',increase_dim=False,last=False): input_num_filters = inp.get_shape().as_list()[3] if increase_dim: first_stride = [1, 2, 2, 1] out_num_filters = input_num_filters*2 else:
tensorflow.nn.avg_pool
4,492
import tensorflow as tf dec_inp_dict2 = {} dec_inp_dict2["0"] = [ tf.constant(0, tf.int32, shape=[2]) for _ in range(3)] dec_inp_dict2["1"] = [ tf.constant(0, tf.int32, shape=[2]) for _ in range(4)] with tf.variable_scope("other"): outputs_dict3, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=tf.constant(True)) sess.run([tf.global_variables_initializer()]) tf.get_variable_scope().reuse_variables() outputs_dict1, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=True) outputs_dict2, _ = tf.nn.seq2seq.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, cell, 2, dec_symbols_dict, embedding_size=2, feed_previous=True) res1 = sess.run(outputs_dict1["0"])
tensorflow.global_variables_initializer
4,493
import tensorflow as tf box_coder.decode(boxes, anchors).get() for boxes in tf.unstack(encoded_boxes)
tensorflow.unstack
4,494
import tensorflow as tf 'image/encoded': tf.io.FixedLenFeature((), tf.string), 'image/source_id': tf.io.FixedLenFeature((), tf.string), 'image/height': tf.io.FixedLenFeature((), tf.int64), 'image/width': tf.io.FixedLenFeature((), tf.int64), 'image/object/bbox/xmin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/xmax': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymin': tf.io.VarLenFeature(tf.float32), 'image/object/bbox/ymax': tf.io.VarLenFeature(tf.float32), 'image/object/class/label': tf.io.VarLenFeature(tf.int64),
tensorflow.io.VarLenFeature
4,495
import tensorflow as tf down1 = d_layer(image,self.df, norm=False,name='down1') #256x256 -> 128x128 #rint('down1',np.shape(down1)) down2 = d_layer(down1,self.df*2,name='down2') #128x128 -> 64x64 #rint('down2',np.shape(down2)) down3 = d_layer(down2,self.df*4,name='down3') #64x64 -> 32x32 #rint('down3',np.shape(down3)) down4 = d_layer(down3,self.df*8,name='down4') # 32x32 -> 16x16 #rint('down4',np.shape(down4)) down5 = tf.contrib.layers.conv2d(down4,1,kernel_size=4,stride=1,padding='valid') #rint('down5',np.shape(down5)) #rint(np.shape(down5)) #logits = tf.reduce_mean(down5, [1,2,3]) return down5 def build_network(self):
tensorflow.contrib.layers.conv2d
4,496
import tensorflow as tf ls = [-1] + l.get_shape().as_list()[1:] xs = ls[:-1] + [3] # unpack parameters logit_probs = l[:, :, :, :nr_mix] l = tf.reshape(l[:, :, :, nr_mix:], xs + [nr_mix * 3]) # sample mixture indicator from softmax sel = tf.one_hot(tf.argmax(logit_probs - tf.log(-tf.log(tf.random_uniform( tf.shape(logit_probs), minval=1e-5, maxval=1. - 1e-5))), 3), depth=nr_mix, dtype=tf.float32) sel = tf.reshape(sel, xs[:-1] + [1, nr_mix]) # select logistic parameters means = tf.reduce_sum(l[:, :, :, :, :nr_mix] * sel, 4) log_scales = tf.maximum(tf.reduce_sum( l[:, :, :, :, nr_mix:2 * nr_mix] * sel, 4), -7.) coeffs = tf.reduce_sum(tf.nn.tanh( l[:, :, :, :, 2 * nr_mix:3 * nr_mix]) * sel, 4) # sample from logistic & clip to interval
tensorflow.reshape
4,497
import tensorflow as tf """ kwargs = {**{self.input_arg: x}, **{k: 1.0 * w for k, w in self.qnode_weights.items()}} return self.qnode(**kwargs) def compute_output_shape(self, input_shape): """Computes the output shape after passing data of shape ``input_shape`` through the QNode. Args: input_shape (tuple or tf.TensorShape): shape of input data Returns: tf.TensorShape: shape of output data """ return tf.TensorShape([input_shape[0]]).concatenate(self.output_dim) def __str__(self): detail = "<Quantum Keras Layer: func={}>" return detail.format(self.qnode.func.__name__) __repr__ = __str__ _input_arg = "inputs" @property def input_arg(self): """Name of the argument to be used as the input to the Keras `Layer <https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer>`__. Set to
tensorflow.TensorShape
4,498
import tensorflow as tf variables. """ inputs = tf.placeholder(dtype=tf.int32, shape=[None, None])
tensorflow.placeholder
4,499