seed
stringlengths
25
1.88k
seed_api
stringlengths
14
102
index
int64
0
1.05k
from tensorflow.python.ops import gen_state_ops shape = shape.merge_with(input_tensor.get_shape()) if not shape.is_fully_defined(): # TODO(pbar): Make a version of assign_add that accepts an uninitialized # lvalue, and takes its shape from that? This would allow accumulate_n to # work in all situations that add_n currently works. raise ValueError("Cannot infer the shape of the accumulator for " "accumulate_n. Pass the shape argument, or set the shape " "of at least one of the inputs.") with ops.op_scope(inputs, name, "AccumulateN") as name: var = gen_state_ops._temporary_variable(shape=shape, dtype=tensor_dtype) var_name = var.op.name var = state_ops.assign(var, array_ops.zeros_like(inputs[0])) update_ops = [] for input_tensor in inputs: op = state_ops.assign_add(var, input_tensor, use_locking=True) update_ops.append(op) with ops.control_dependencies(update_ops): return gen_state_ops._destroy_temporary_variable(var,
tensorflow.python.ops.gen_state_ops._temporary_variable
600
import tensorflow as tf if (len(test_data.encoded_x) > 1 or test_data.decoded_x is not list(test_data.encoded_x.values())[0]): self.assertIn(encoding_stage.DECODE_SCOPE_SUFFIX, test_data.decoded_x.name) if is_adaptive_stage(stage): # The property should have keys matching those of state_update_tensors. self.assertSameElements(stage.state_update_aggregation_modes.keys(), test_data.state_update_tensors.keys()) for mode in six.itervalues(stage.state_update_aggregation_modes): self.assertIn(mode, encoding_stage.StateAggregationMode) for tensor in six.itervalues(test_data.initial_state): self.assertTrue(tf.is_tensor(tensor)) for tensor in six.itervalues(test_data.state_update_tensors): self.assertTrue(tf.is_tensor(tensor)) for tensor in six.itervalues(test_data.updated_state): self.assertTrue(tf.is_tensor(tensor)) # The state related Tensors should have appropriate substrings in their # names. for tensor in six.itervalues(test_data.initial_state): self.assertIn(encoding_stage.INITIAL_STATE_SCOPE_SUFFIX, tensor.name) for tensor in six.itervalues(test_data.updated_state): self.assertIn(encoding_stage.UPDATE_STATE_SCOPE_SUFFIX, tensor.name) for tensor in six.itervalues(test_data.state_update_tensors):
tensorflow.is_tensor
601
from tensorflow.python.platform import gfile except OSError: pass # Ignore gfile.MakeDirs(save_dir)
tensorflow.python.platform.gfile.MakeDirs
602
import tensorflow as tf options = self.options input_shape = tf.shape(encoder_states) batch_size = input_shape[0] passage_len = input_shape[1] with variable_scope.variable_scope("attention_decoder"): encoder_features = tf.expand_dims(encoder_states, axis=2) # now is shape [batch_size, passage_len, 1, encoder_dim] W_h = variable_scope.get_variable("W_h", [1, 1, encoder_dim, options.attention_vec_size]) self.W_h = W_h encoder_features = nn_ops.conv2d(encoder_features, W_h, [1, 1, 1, 1], "SAME") # [batch_size, passage_len, 1, attention_vec_size] encoder_features = tf.reshape(encoder_features, [batch_size, passage_len, options.attention_vec_size]) return encoder_features def decode_mode(self, word_vocab, beam_size, state_t_1, context_t_1, coverage_t_1, word_t, encoder_states, encoder_features, passage_word_idx, passage_mask): options = self.options with variable_scope.variable_scope("attention_decoder"): v = variable_scope.get_variable("v", [options.attention_vec_size]) v = tf.expand_dims(tf.expand_dims(v, axis=0), axis=0)
tensorflow.reshape
603
import tensorflow as tf global_mode(), feed_dict={tf.global_mode(): tf.estimator.ModeKeys.PREDICT}) # mode == tf.estimator.ModeKeys.PREDICT """ mode = tf.get_collection_ref(_GLOBAL_MODE_KEY) if len(mode) < 1: # mode_tensor = tf.placeholder(tf.string, name="global_mode") mode_tensor = tf.placeholder_with_default( input=tf.estimator.ModeKeys.TRAIN, shape=(), name="global_mode") # mode_tensor = tf.constant( # value=tf.estimator.ModeKeys.TRAIN, # dtype=tf.string,
tensorflow.placeholder_with_default
604
import tensorflow as tf sparse_map_op=st_handles.op, sparse_handles=st_handles) st_roundtrip_op = st_roundtrip.values.op st_serialized = tf.serialize_many_sparse(st) st_deserialized = tf.deserialize_many_sparse( st_serialized, dtype=values.dtype)
tensorflow.serialize_many_sparse
605
import tensorflow as tf def test_tensor_rearrange(): tensor_rearrange = TensorRearrange(seed=713) in_node_a = tensor_rearrange.get_placeholder("input_0") in_node_b = tensor_rearrange.get_placeholder("input_1") in_node_c = tensor_rearrange.get_placeholder("input_2") stitched = tf.dynamic_stitch([[1, 10], [[0, 7, 9], [5, 8, 3]], [[6], [4], [2]]], [in_node_a, in_node_b, in_node_c]) # should be 11,5,4 list_of_parts = tf.dynamic_partition(tf.transpose(stitched, perm=[1, 2, 0]), [[0, 1, 2, 3], [1, 0, 2, 3], [2, 3, 1, 0], [2, 1, 0, 3], [0, 1, 2, 3]], num_partitions=4) # after permute becomes 5,4,11, return all partitions 5,11 node_a = tf.div(list_of_parts[0], list_of_parts[1]) node_b = tf.divide(list_of_parts[2], list_of_parts[3]) trace_node = tf.trace(node_a) + node_b # there is a broadcast here out_node = tf.cast(tf.count_nonzero(trace_node), dtype=tf.float32) + tf.Variable(tf.random_normal(shape=(2, 3))) placeholders = [in_node_a, in_node_b, in_node_c] predictions = [out_node] # Run and persist tfp = TensorFlowPersistor(save_dir="partition_stitch_misc") tfp.set_placeholders(placeholders) \ .set_output_tensors(predictions) \ .set_test_data(tensor_rearrange.get_test_data()) \ .build_save_frozen_graph()
tensorflow.trace
606
import tensorflow as tf # add by wangxiao # define the inputs of signature def serving_input_fn(): label_ids = tf.placeholder(tf.int32, [None], name='label_ids') input_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_ids') input_mask = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='input_mask') segment_ids = tf.placeholder(tf.int32, [None, FLAGS.max_seq_length], name='segment_ids') input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn({ 'label_ids': label_ids, 'input_ids': input_ids, 'input_mask': input_mask, 'segment_ids': segment_ids, })() return input_fn
tensorflow.estimator.export.build_raw_serving_input_receiver_fn
607
import tensorflow as tf within the assets subdirectory, we will return a None. Args: vocab_filename: The vocabulary name to lookup. """ mapping_path = os.path.join(self._transformed_metadata_dir, self.ASSET_MAP) mapping = {} if tf.io.gfile.exists(mapping_path): with tf.io.gfile.GFile(mapping_path) as f: mapping = json.loads(f.read()) if vocab_filename in mapping: vocab_path = os.path.join(self.transform_savedmodel_dir, tf.saved_model.ASSETS_DIRECTORY, mapping[vocab_filename]) if tf.io.gfile.exists(vocab_path): return vocab_path prefix = os.path.join(self.transform_savedmodel_dir, tf.saved_model.ASSETS_DIRECTORY, sanitized_vocab_filename(filename=vocab_filename)) files = tf.io.gfile.glob(prefix) + tf.io.gfile.glob( '{}.tfrecord.gz'.format(prefix)) if not files: return None if len(files) != 1: raise ValueError('Found too many vocabulary files: {}'.format(files)) return files[0] def _vocabulary_size_from_annotations(self,
tensorflow.io.gfile.exists
608
import tensorflow as tf decoder = tf_example_decoder.TfExampleDecoder( load_instance_masks=False, num_additional_channels=predict_input_config.num_additional_channels) input_dict = transform_fn(decoder.decode(example)) images = tf.cast(input_dict[fields.InputDataFields.image], dtype=tf.float32) images = tf.expand_dims(images, axis=0) true_image_shape = tf.expand_dims( input_dict[fields.InputDataFields.true_image_shape], axis=0) return tf.estimator.export.ServingInputReceiver( features={ fields.InputDataFields.image: images, fields.InputDataFields.true_image_shape: true_image_shape}, receiver_tensors={SERVING_FED_EXAMPLE_KEY: example}) return _predict_input_fn
tensorflow.estimator.export.ServingInputReceiver
609
from tensorflow.python.ops import gen_resource_variable_ops def read_value(self): return self._read_variable_op() def assign(self, value, use_locking=None, name=None, read_value=False): del use_locking with _handle_graph(self.handle), self._assign_dependencies(): value_tensor = ops.convert_to_tensor(value, dtype=self.dtype) assign_op = gen_resource_variable_ops.assign_variable_op( self.handle, value_tensor, name=name) if read_value: return self._read_variable_op() return assign_op def assign_add(self, delta, use_locking=None, name=None, read_value=True): del use_locking
tensorflow.python.ops.gen_resource_variable_ops.assign_variable_op
610
import tensorflow as tf if checkpoint_state is None: return for checkpoint_path in checkpoint_state.all_model_checkpoint_paths: tf.compat.v1.train.remove_checkpoint(checkpoint_path) return
tensorflow.compat.v1.train.remove_checkpoint
611
import tensorflow as tf vec row, should agree with vecs in shape[0] Output: A tensor of shape (vec_dim) """ if reduction_mode == 'max': print('USING MAX POOLING FOR REDUCTION!') vecs_reduced = tf.segment_max(vecs, segment_inds) elif reduction_mode == 'mean': print('USING AVG POOLING FOR REDUCTION!') vecs_reduced = tf.segment_mean(vecs, segment_inds) vecs_reduced.set_shape([num_segments, vecs.get_shape()[1]]) return vecs_reduced
tensorflow.segment_mean
612
import tensorflow as tf def _split_string(string): """Splits a byte string into an array of character bytes.""" text = tf.compat.as_text(string) ret = np.empty(len(text), dtype=np.object) for i, char in enumerate(text): ret[i] = tf.compat.as_bytes(char) return ret def vocabulary(filename, max_size=None, num_oov_buckets=1):
tensorflow.compat.as_bytes
613
from tensorflow.contrib.layers.python.layers import feature_column 'language', hash_bucket_size=2e7) embedding_feature = feature_column.embedding_column(
tensorflow.contrib.layers.python.layers.feature_column.embedding_column
614
import tensorflow as tf features = {'member/name': tf.io.FixedLenFeature([], tf.string), 'member/encoded': tf.io.FixedLenFeature([], tf.string), 'member/age': tf.io.FixedLenFeature([], tf.int64), 'member/height': tf.io.VarLenFeature(tf.float32), 'member/prefer_prods': tf.io.VarLenFeature(tf.int64)} features = tf.io.parse_single_example(example_proto, features) images = tf.image.decode_png(features['member/encoded'], channels=3) # 注意png原本有4個channel,但執行到下面的處理會出錯,所以前一行先降成3個channel。 images = tf.image.random_brightness(images, 0.1) images = tf.image.random_saturation(images, 0.7, 1.3) images = tf.image.random_contrast(images, 0.6, 1.5) images = tf.image.random_flip_left_right(images)
tensorflow.image.decode_png
615
import tensorflow as tf # 2nd part of minimize: apply_gradient optimizer_step = self._optimizer.apply_gradients(clipped_grads_and_vars, global_step=self.global_step) update_ops = tf.group(*self.update_ops) self.training_op = tf.group(update_ops, optimizer_step) def set_check_ops(self): self._check_ops = 1 # TODO argo2 This is not working anymore with the new session #with self.sess.graph.as_default(): self._numerics_ops = tf.add_check_numerics_ops() def release(self): super().release() self.sess.close() tf.reset_default_graph() def set_summaries(self): """This function sets summaries and summaryFileWriters, it needs to be invoked before training to keep track of the summaries. (cannot be invoked in create_and_init_network because the FileWriter will corrupt data in the logfolder at each initialization) """
tensorflow.add_check_numerics_ops
616
import tensorflow as tf with tf.variable_scope('self_attention'): # @2.self-attention in block # mask generation sl_indices = tf.range(block_len, dtype=tf.int32) sl_col, sl_row = tf.meshgrid(sl_indices, sl_indices) if direction == 'forward': direct_mask = tf.greater(sl_row, sl_col) # bl,bl else: direct_mask = tf.greater(sl_col, sl_row) # bl,bl direct_mask_tile = tf.tile( tf.expand_dims(tf.expand_dims(direct_mask, 0), 0), [bs, bn, 1, 1]) # bs,bn,bl,bl rep_mask_tile_1 = tf.tile(tf.expand_dims(rep_mask_split, 2), [1, 1, bl, 1]) # bs,bn,bl,bl rep_mask_tile_2 = tf.tile(tf.expand_dims(rep_mask_split, 3), [1, 1, 1, bl]) # bs,bn,bl,bl rep_mask_tile = tf.logical_and(rep_mask_tile_1, rep_mask_tile_2) attn_mask = tf.logical_and(direct_mask_tile, rep_mask_tile, name='attn_mask') # bs,bn,bl,bl # attention f_bias = tf.get_variable('f_bias', [ivec], tf.float32, tf.constant_initializer(0.)) dependent_head = linear( rep_map, 2 * ivec, False, 0., 'linear_dependent_head', False, wd, keep_prob, is_train) # bs,bn,bl,2vec dependent, head = tf.split(dependent_head, 2, 3) dependent_etd = tf.expand_dims(dependent, 2) # bs,bn,1,bl,vec head_etd = tf.expand_dims(head, 3) # bs,bn,bl,1,vec logits = scaled_tanh(dependent_etd + head_etd + f_bias, 5.0) # bs,bn,bl,bl,vec logits_masked = exp_mask_for_high_rank(logits, attn_mask) attn_score = tf.nn.softmax(logits_masked, 3) # bs,bn,bl,bl,vec attn_score = mask_for_high_rank(attn_score, attn_mask) # bs,bn,bl,bl,vec self_attn_result = tf.reduce_sum(attn_score * rep_map_tile, 3) # bs,bn,bl,vec
tensorflow.logical_and
617
import tensorflow as tf # 50*50 # Step-wise contrastive loss even = [2 * i for i in range(25)] odd = [2 * i + 1 for i in range(25)] pred1 = tf.gather(pred, even) pred2 = tf.gather(pred, odd) tgt1 = tf.gather(tgt, even) tgt2 = tf.gather(tgt, odd) geq = tf.cast((tgt1 - tgt2) > 0, tf.bool) tgt_larg = tf.where(geq, tgt1, tgt2) tgt_small = tf.where(geq, tgt2, tgt1)
tensorflow.gather
618
import tensorflow as tf [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]), m2, m3 ], axis=3) centered_inputs = inputs - means inv_stdv = tf.exp(-log_scales) plus_in = inv_stdv * (centered_inputs + 1. / 255.) cdf_plus = tf.nn.sigmoid(plus_in) min_in = inv_stdv * (centered_inputs - 1. / 255.) cdf_min = tf.nn.sigmoid(min_in) log_cdf_plus = plus_in - tf.nn.softplus(plus_in) log_one_minus_cdf_min = -tf.nn.softplus(min_in) cdf_delta = cdf_plus - cdf_min mid_in = inv_stdv * centered_inputs log_pdf_mid = mid_in - log_scales - 2. * tf.nn.softplus(mid_in) log_probs = tf.select( inputs < -0.999, log_cdf_plus, tf.select( inputs > 0.999, log_one_minus_cdf_min, tf.select(cdf_delta > 1e-5, tf.log(tf.maximum(cdf_delta, 1e-12)), log_pdf_mid - np.log(127.5))))
tensorflow.nn.softplus
619
from tensorflow.contrib.learn.python.learn.estimators import estimator_test_utils 'accuracy/threshold_0.500000_mean', metrics) estimator_test_utils.assert_in_range( 0.9, 1.0, 'precision/positive_threshold_0.500000_mean', metrics) estimator_test_utils.assert_in_range( 0.9, 1.0, 'recall/positive_threshold_0.500000_mean', metrics) self._assertCommonMetrics(metrics) def _assertCommonMetrics(self, metrics): estimator_test_utils.assert_in_range(_ITERS, _ITERS + 5, 'global_step', metrics) estimator_test_utils.assert_in_range(0.9, 1.0, 'accuracy', metrics) estimator_test_utils.assert_in_range(0.0, 0.2, 'loss', metrics) self.report_benchmark( iters=metrics['global_step'], extras={k: v 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(
tensorflow.contrib.learn.python.learn.estimators.estimator_test_utils.assert_in_range
620
from tensorflow.contrib.losses.python.losses import loss_ops def __init__(self, label_name, weight_column_name): def loss_fn(logits, target): check_shape_op = control_flow_ops.Assert( math_ops.less_equal(array_ops.rank(target), 2), ["target's shape should be either [batch_size, 1] or [batch_size]"]) with ops.control_dependencies([check_shape_op]): target = array_ops.reshape( target, shape=[array_ops.shape(target)[0], 1]) return loss_ops.hinge_loss(logits, target) super(_BinarySvmTargetColumn, self).__init__( loss_fn=loss_fn, n_classes=2, label_name=label_name, weight_column_name=weight_column_name) def logits_to_predictions(self, logits, proba=False):
tensorflow.contrib.losses.python.losses.loss_ops.hinge_loss
621
import tensorflow as tf 512), max_steps = 1000) exporter = tf.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = tf.estimator.EvalSpec(read_dataset('valid.csv',
tensorflow.estimator.LatestExporter
622
from tensorflow.python.ops import variable_scope Returns: value_tensor: A tensor representing the current value of the metric. update_op: An operation that accumulates the error from a batch of data. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_scope( name, 'false_negatives', [predictions, labels]): predictions.get_shape().assert_is_compatible_with(labels.get_shape()) is_false_negative = math_ops.logical_and(math_ops.equal(labels, 1), math_ops.equal(predictions, 0)) return _count_condition(is_false_negative, weights, metrics_collections, updates_collections)
tensorflow.python.ops.variable_scope.variable_scope
623
import tensorflow as tf """ t_rank = tf.rank(t)
tensorflow.rank
624
import tensorflow as tf beam_width=beam_width, blank_index=blank_index, top_paths=1, blank_label=0) decoded = tf.sparse.SparseTensor(indices[0], values[0], shape[0]) decoded = tf.cast(tf.sparse.to_dense(decoded), tf.int32) decoded_u = tf.sparse.SparseTensor(indices_u[0], values_u[0], shape_u[0]) decoded_u = tf.cast(tf.sparse.to_dense(decoded_u), tf.int32) # Adjust event vals according to representation decoded = tf.where(tf.not_equal(decoded, 0), decoded+shift, decoded) decoded_u = tf.where(tf.not_equal(decoded_u, 0), decoded_u+shift, decoded_u) # Set default vals
tensorflow.sparse.to_dense
625
import tensorflow as tf
tensorflow.train.ExponentialMovingAverage
626
import tensorflow as tf 1, scope='feature_projection' + str(i))) # Resize to decoder_height/decoder_width. for j, feature in enumerate(decoder_features_list): decoder_features_list[j] = tf.image.resize_bilinear( feature, [decoder_height, decoder_width], align_corners=True) if is_training: decoder_features_list[j].set_shape(
tensorflow.image.resize_bilinear
627
import tensorflow as tf Total_loss = cost + l2_loss optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=momentum, use_nesterov=True) # Batch norm requires update_ops to be added as a train_op dependency.
tensorflow.train.MomentumOptimizer
628
import tensorflow as tf return tf.keras.utils.register_keras_serializable(package=package) else: return lambda cls: cls def _check_tensorflow_version(): """Check that we're using a compatible TF version. Raises a warning if either Tensorflow version is less that 2.0 or TF 2.x is not enabled. If TF 2.x is enabled, but version is < TF 2.3, raises a warning to indicate that resources may not be initialized. """ major, minor, _ = tf.version.VERSION.split('.') if not (int(major) >= 2 and tf2.enabled()): tf.compat.v1.logging.warning( 'Tensorflow version (%s) found. TransformFeaturesLayer is supported ' 'only for TF 2.x with TF 2.x behaviors enabled and may not work as ' 'intended.', tf.version.VERSION) elif int(major) == 2 and int(minor) < 3: # TODO(varshaan): Log a more specific warning. tf.compat.v1.logging.warning( 'Tensorflow version (%s) found. TransformFeaturesLayer may not work ' 'as intended if the SavedModel contains an initialization op.', tf.version.VERSION)
tensorflow.version.VERSION.split
629
import tensorflow as tf # resize y-z squeeze_b_x = tf.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx') resize_b_x = tf.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align) resume_b_x = tf.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx') # Reorient reoriented = tf.transpose(resume_b_x, [0, 3, 2, 1, 4]) # squeeze and 2d resize squeeze_b_z = tf.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz') resize_b_z = tf.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align) resume_b_z = tf.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz') output_tensor = tf.transpose(resume_b_z, [0, 3, 2, 1, 4]) return output_tensor def conv3d(x, kernel_size, filters, padding='SYMMETRIC', activation=None, initialization=None, use_bias=True): """ Based on: https://github.com/gitlimlab/CycleGAN-Tensorflow/blob/master/ops.py For tf padding, refer to: https://www.tensorflow.org/api_docs/python/tf/pad
tensorflow.compat.v1.image.resize_bilinear
630
from tensorflow.python.ops import parsing_ops 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(( self._get_linear_feature_columns() or []) + ( self._get_dnn_feature_columns() or [])) features = parsing_ops.parse_example(examples_batch, column_types) return features def _get_linear_feature_columns(self): if not self._linear_feature_columns: return None
tensorflow.python.ops.parsing_ops.parse_example
631
import tensorflow as tf elif validate_args: assertions += [tf.compat.v1.assert_rank(perm, 1, message=msg)] perm_ = tf.get_static_value(perm) msg = '`perm` must be a valid permutation vector.' if perm_ is not None: if not np.all(np.arange(np.size(perm_)) == np.sort(perm_)): raise ValueError(msg[:-1] + ', saw: {}.'.format(perm_)) elif validate_args: assertions += [ tf.compat.v1.assert_equal( tf.sort(perm), tf.range(tf.size(input=perm)), message=msg) ] return assertions
tensorflow.sort
632
import tensorflow as tf Args: * vars_list: list of variables Returns: * prune_ratio: overall pruning ratio of the given list of variables """ nb_params_nnz = tf.add_n([tf.count_nonzero(var) for var in vars_list]) nb_params_all = tf.add_n([tf.size(var) for var in vars_list]) prune_ratio = 1.0 - tf.cast(nb_params_nnz, tf.float32) / tf.cast(nb_params_all, tf.float32) return prune_ratio
tensorflow.count_nonzero
633
import tensorflow as tf """Preprocess a single raw image.""" image = tf.image.decode_image(encoded_image, channels=shape[-1]) image.set_shape(shape) return tf.cast(image, dtype) def serving_input_receiver_fn(): image_bytes_list = tf.placeholder( shape=[None], dtype=tf.string, ) images = tf.map_fn( _preprocess_image, image_bytes_list, back_prop=False, dtype=dtype) return tf.estimator.export.TensorServingInputReceiver( features=images, receiver_tensors=image_bytes_list) return serving_input_receiver_fn def _encode_image(image_array, fmt='PNG'): """encodes an (numpy) image array to string. Args: image_array: (numpy) image array fmt: image format to use
tensorflow.estimator.export.TensorServingInputReceiver
634
from tensorflow.python.framework import ops # allowing instances of the class to be used as tensors. def _tensor_conversion(var, dtype=None, name=None, as_ref=False): return var._dense_var_to_tensor(dtype=dtype, name=name, as_ref=as_ref) # pylint: disable=protected-access ops.register_tensor_conversion_function(ReplicatedVariable, _tensor_conversion) if not TF_23: ops.register_dense_tensor_like_type(ReplicatedVariable)
tensorflow.python.framework.ops.register_tensor_conversion_function
635
import tensorflow as tf alpha_mean = tf.get_variable('alpha_mean_layer'+str(h), shape=[1, 1, n_basis, n_out], initializer=tf.random_normal_initializer()) alpha_logstd = tf.get_variable('alpha_logstd_layer'+str(h), shape=[1, 1, n_basis, n_out], initializer=tf.random_normal_initializer()) alpha_std = tf.exp(alpha_logstd) # Compute epsilon from {n_samples} standard Gaussian # epsilon = tf.random_normal([n_samples, 1, n_out*2, n_out]) epsilon = tf.random_uniform([n_samples, 1, n_basis, n_out]) hyp_params = tf.get_variable('hyp_params_layer'+str(h), shape=[2], initializer=tf.random_normal_initializer()) l1, l2 = tf.nn.sigmoid(hyp_params[0]), tf.exp(hyp_params[1]) epsilon = tf.sinh(epsilon*l2)/tf.cosh(epsilon*l2)**l1/l2 # Compute A_{h+1} A = tf.tile(alpha_mean+epsilon*alpha_std, [1, tf.shape(X)[0], 1, 1]) # Compute z_{h}A_{h+1} Z1 = tf.matmul(Z, A[:,:,:n_basis//2,:])/tf.sqrt(n_basis*.5) Z2 = tf.matmul(Z, A[:,:,n_basis//2:,:])/tf.sqrt(n_basis*.5) # Compute u_{h+1} and v_{h+1} U, V = tf.cos(Z1)+tf.cos(Z2), tf.sin(Z1)+tf.sin(Z2) Z = tf.concat([U, V], 3)/tf.sqrt(n_out*1.) KL += tf.reduce_mean(alpha_std**2+alpha_mean**2-2*alpha_logstd-1)/2. # Output layer else: F = tf.squeeze(tf.layers.dense(Z, n_out), [2]) return F, KL
tensorflow.cosh
636
import tensorflow as tf kernel_size = 5, mask = self.c_mask, num_filters = d, num_heads = nh, seq_len = self.c_len, scope = "Model_Encoder", bias = False, reuse = True if i > 0 else None, dropout = self.dropout) ) with tf.variable_scope("Output_Layer"): start_logits = tf.squeeze(conv(tf.concat([self.enc[1], self.enc[2]],axis = -1),1, bias = False, name = "start_pointer"),-1) end_logits = tf.squeeze(conv(tf.concat([self.enc[1], self.enc[3]],axis = -1),1, bias = False, name = "end_pointer"), -1) self.logits = [mask_logits(start_logits, mask = self.c_mask), mask_logits(end_logits, mask = self.c_mask)] logits1, logits2 = [l for l in self.logits] outer = tf.matmul(tf.expand_dims(tf.nn.softmax(logits1), axis=2), 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)
tensorflow.concat
637
from tensorflow.python.ops import clip_ops global_step: Optional global_step. If provided, `decay = decay*n/(n+1)`. This provides a quicker adaptation of the mean for the first steps. report_summary: If `True`, will add histogram summaries of the `max_norm`. epsilon: Small value chosen to avoid zero variance. name: The name for this operation is used to scope operations and summaries. Returns: A function for applying gradient clipping. """ def gradient_clipping(grads_and_vars): """Internal function for adaptive clipping.""" grads, variables = zip(*grads_and_vars) norm = clip_ops.global_norm(grads) max_norm, log_mean = _adaptive_max_norm(norm, std_factor, decay, global_step, epsilon, name) # reports the max gradient norm for debugging if report_summary: summary.scalar("global_norm/adaptive_max_gradient_norm", max_norm) # factor will be 1. if norm is smaller than max_norm factor = array_ops.where(norm < max_norm, array_ops.ones_like(norm), math_ops.exp(log_mean) / norm) if static_max_norm is not None:
tensorflow.python.ops.clip_ops.global_norm
638
import tensorflow as tf loss = tf.maximum(0.0, (tgt_larg - tgt_small) - (pred_larg - pred_small) + margin)
tensorflow.maximum
639
import tensorflow as tf net : :class:`Layer` Previous layer with output shape of (batch, width, r). """ # with tf.name_scope(name): # self.outputs = self._apply_activation(self._PS(self.inputs, r=scale)) outputs = self.act(self._PS(inputs, r=self.scale)) return outputs @private_method def _PS(self, I, r): X = tf.transpose(I, [2, 1, 0]) # (r, w, b) X = tf.batch_to_space_nd(X, [r], [[0, 0]]) # (1, r*w, b) X = tf.transpose(X, [2, 1, 0]) return X
tensorflow.batch_to_space_nd
640
from tensorflow.python.ops import math_ops # For SparseTensor, calculate separate count for each row. if isinstance(labels, (ops.SparseTensor, ops.SparseTensorValue)): labels_sizes = set_ops.set_size(labels) return math_ops.minimum(labels_sizes, k, name=scope) # For dense Tensor, calculate scalar count based on last dimension, and # tile across labels shape. labels_shape = array_ops.shape(labels) labels_size = labels_shape[-1] num_relevant_scalar = math_ops.minimum(labels_size, k) return array_ops.fill(labels_shape[0:-1], num_relevant_scalar, name=scope) def expand_and_tile(tensor, multiple, dim=0, name=None): """Slice `tensor` shape in 2, then tile along the sliced dimension. A new dimension is inserted in shape of `tensor` before `dim`, then values are tiled `multiple` times along the new dimension.
tensorflow.python.ops.math_ops.minimum
641
from tensorflow.python.framework import tensor_shape def batch_runner_fn(self): return _scheduled_stamp_resource_op_runner def _move_tensors(tensors, device): """Moves a list of tensors to a device by concatenating/splitting them.""" # Reset the device setting to avoid weird interactions with device merging # logic. with ops.device(None): if all(tensor.shape == tensor_shape.scalar() for tensor in tensors): with ops.device(tensors[0].device): values = array_ops.stack(tensors) with ops.device(device): return array_ops.unstack(values) else: with ops.device(tensors[0].device): sizes = array_ops.stack( [array_ops.shape(tensor)[0] for tensor in tensors]) values = array_ops.concat(tensors, axis=0)
tensorflow.python.framework.tensor_shape.scalar
642
from tensorflow.python.layers import convolutional as conv_layers if input_layer is None: input_layer = self.top_layer if num_channels_in is None: num_channels_in = self.top_size name = 'conv' + str(self.counts['conv']) self.counts['conv'] += 1 with tf.variable_scope(name): strides = [1, d_height, d_width, 1] if self.data_format == 'NCHW': strides = [strides[0], strides[3], strides[1], strides[2]] if mode != 'SAME_RESNET': conv = conv_layers.conv2d( input_layer, num_out_channels, [k_height, k_width], strides=[d_height, d_width], padding=mode, data_format=self.channel_pos, use_bias=False) else: # Special padding mode for ResNet models if d_height == 1 and d_width == 1: conv = conv_layers.conv2d( input_layer,
tensorflow.python.layers.convolutional.conv2d
643
import tensorflow as tf sok_saver = sok.Saver() restore_op = list() for i, embedding_layer in enumerate(sok_sparse_demo.embedding_layers): control_inputs = [restore_op[-1]] if restore_op else None with tf.control_dependencies(control_inputs): if args.restore_params: filepath = r"./embedding_variables" op = sok_saver.restore_from_file(embedding_layer.embedding_variable, filepath) else: op = sok_saver.load_embedding_values(embedding_layer.embedding_variable, init_tensors[i]) restore_op.append(op) loss_fn = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction="none") def _replica_loss(labels, logits): loss = loss_fn(labels, logits) return tf.nn.compute_average_loss(loss, global_batch_size=args.global_batch_size) def _train_step(inputs, labels, training): def _step_fn(inputs, labels): logit, embedding_vector = sok_sparse_demo(inputs, training=training) loss = _replica_loss(labels, logit) emb_var, other_var = sok.split_embedding_variable_from_others(sok_sparse_demo.trainable_variables) grads = tf.gradients(loss, emb_var + other_var, colocate_gradients_with_ops=True, unconnected_gradients=tf.UnconnectedGradients.NONE) emb_grads, other_grads = grads[:len(emb_var)], grads[len(emb_var):] if "plugin" in args.optimizer: emb_train_op = emb_opt.apply_gradients(zip(emb_grads, emb_var)) else: with sok.OptimizerScope(emb_var): emb_train_op = emb_opt.apply_gradients(zip(emb_grads, emb_var))
tensorflow.nn.compute_average_loss
644
from tensorflow.python.training import training as train Raises: ValueError: if: * `loss` is an invalid type or shape. * `global_step` is an invalid type or shape. * `learning_rate` is an invalid type or value. * `optimizer` has the wrong type. * `clip_gradients` is neither float nor callable. * `learning_rate` and `learning_rate_decay_fn` are supplied, but no `global_step` is available. * `gradients` is empty. """ loss = ops.convert_to_tensor(loss) contrib_framework.assert_scalar(loss) if global_step is None: global_step = train.get_global_step() else: train.assert_global_step(global_step) with vs.variable_scope(name, "OptimizeLoss", [loss, global_step]): # Update ops take UPDATE_OPS collection if not provided. if update_ops is None: update_ops = set(ops.get_collection(ops.GraphKeys.UPDATE_OPS)) # Make sure update ops are ran before computing loss. if update_ops: loss = control_flow_ops.with_dependencies(list(update_ops), loss) # Learning rate variable, with possible decay. lr = None if learning_rate is not None:
tensorflow.python.training.training.get_global_step
645
import tensorflow as tf else: # 创建worker两个网络的具体步骤 with tf.variable_scope(scope): # 这里的scope传入的是worker的名字 self.global_step = globalAC.global_step self.obs_space = N_S self.act_space = N_A self.k = 16 self.g_dim = 256 self.c = 10 self.vf_hidden_size = 128 # for value function network self.alpha = 0.5 # for build loss self.batch_processor = FeudalBatchProcessor(self.c) self.build_model() # build feudal policy model with tf.name_scope('local_grad'): grads = tf.gradients(self.loss, self.var_list) grads, _ = tf.clip_by_global_norm(grads, 40) with tf.name_scope('sync'): # worker和global的同步过程 with tf.name_scope('pull'): # 获取global参数,复制到local—net self.pull_params_op = tf.group(*[v1.assign(v2) for v1, v2 in zip(self.var_list, globalAC.var_list)]) with tf.name_scope('push'): # 将参数传送到gloabl中去 self.update_params_op = OPT.apply_gradients(zip(grads, globalAC.var_list)) # 其中传送的是local—net的actor和critic的参数梯度grads,具体计算在上面定义 # apply_gradients是tf.train.Optimizer中自带的功能函数,将求得的梯度参数更新到global中 self.inc_step = self.global_step.assign_add(tf.shape(self.obs)[0]) self.train_op = tf.group(self.update_params_op, self.inc_step) # GLOBALE_STEP += tf.shape(self.obs)[0]
tensorflow.gradients
646
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 # we don't actually round to the nearest 8bit value when sampling u = tf.random_uniform(tf.shape(means), minval=1e-5, maxval=1. - 1e-5) x = means + tf.exp(log_scales) * (tf.log(u) - tf.log(1. - u)) x0 = tf.minimum(tf.maximum(x[:, :, :, 0], -1.), 1.) x1 = tf.minimum(tf.maximum( x[:, :, :, 1] + coeffs[:, :, :, 0] * x0, -1.), 1.) x2 = tf.minimum(tf.maximum( x[:, :, :, 2] + coeffs[:, :, :, 1] * x0 + coeffs[:, :, :, 2] * x1, -1.), 1.) return tf.concat([tf.reshape(x0, xs[:-1] + [1]), tf.reshape(x1, xs[:-1] + [1]), tf.reshape(x2, xs[:-1] + [1])], 3)
tensorflow.nn.tanh
647
import tensorflow as tf # Trainable parameters w1 = tf.Variable(tf.random_normal([hidden_size, attention_size], stddev=0.1)) w2 = tf.Variable(tf.random_normal([input_size, attention_size], stddev=0.1)) b = tf.Variable(tf.random_normal([attention_size], stddev=0.1)) v = tf.Variable(tf.random_normal([attention_size], stddev=0.1)) with tf.name_scope('v'): # Applying fully connected layer with non-linear activation to each of the B*T timestamps; # the shape of `tmp` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size tmp1 = tf.tensordot(facts, w1, axes=1) tmp2 = tf.tensordot(query, w2, axes=1) tmp2 = tf.reshape(tmp2, [-1, 1, tf.shape(tmp2)[-1]]) tmp = tf.tanh((tmp1 + tmp2) + b) # For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector v_dot_tmp = tf.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape key_masks = mask # [B, 1, T] # key_masks = tf.expand_dims(mask, 1) # [B, 1, T] paddings = tf.ones_like(v_dot_tmp) * (-2 ** 32 + 1) v_dot_tmp = tf.where(key_masks, v_dot_tmp, paddings) # [B, 1, T] alphas = tf.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape # Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape #output = tf.reduce_sum(facts * tf.expand_dims(alphas, -1), 1) output = facts * tf.expand_dims(alphas, -1) output = tf.reshape(output, tf.shape(facts)) # output = output / (facts.get_shape().as_list()[-1] ** 0.5) if not return_alphas: return output else:
tensorflow.tensordot
648
import tensorflow as tf z_t_len = tf.strings.length(z_t) z_t = tf.string_split([z_t], delimiter='').values for i in tf.range(start=0, limit=x_t_len - self._p + 1, delta=1, dtype=None, name='range'): u = tf.string_join(x_t[i:i + self._p], '') vx_keys, r = tf.cond( tf.greater(vx.lookup(u), -1), true_fn=lambda: (vx_keys, tf.add(vx.lookup(u), 1)), false_fn=lambda: (tf.concat([vx_keys, tf.reshape(u, (-1, 1))], axis=0), tf.constant(1, dtype=tf.int64, name='constant')) ) vx.insert(u, r) for i in tf.range(start=0, limit=z_t_len - self._p + 1, delta=1, dtype=None, name='range'): u = tf.string_join(z_t[i:i + self._p], '') vz_keys, r = tf.cond( tf.greater(vz.lookup(u), -1), true_fn=lambda: (vz_keys, tf.add(vz.lookup(u), 1)), false_fn=lambda: ( tf.concat([vz_keys, tf.reshape(u, (-1, 1))], axis=0), tf.constant(1, dtype=tf.int64)) ) vz.insert(u, r) kk = tf.Variable(0, dtype=tf.int64) for i in tf.range(start=0, limit=tf.size(vx_keys), delta=1, dtype=None, name='range'): for j in tf.range(start=0, limit=tf.size(vz_keys), delta=1, dtype=None, name='range'): to_add = tf.cond( tf.greater(vz.lookup(vx_keys[i]), -1),
tensorflow.string_join
649
import tensorflow as tf # for each key I get the collection of summary nodes # I set up a filewriter for each summary node self.summary_nodes = {sk: tf.get_collection(sk) for sk in self.summary_keys} for sk in self.summary_keys: self.summary_writers[sk] = [tf.compat.v1.summary.FileWriter(self._tensorboard_dir+sn.name) for sn in self.summary_nodes[sk]] def create_hooks(self, config):
tensorflow.compat.v1.summary.FileWriter
650
import tensorflow as tf self.dropout_mask = [] for layer in range(num_layers): input_size_ = input_size if layer == 0 else 2 * num_units gru_fw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units) gru_bw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units) init_fw = tf.tile(tf.Variable( tf.zeros([1, 1, num_units])), [1, batch_size, 1]) init_bw = tf.tile(tf.Variable(
tensorflow.contrib.cudnn_rnn.CudnnGRU
651
from tensorflow.contrib.framework import tensor_util pearson_r: A tensor representing the current Pearson product-moment correlation coefficient, the value of `cov(predictions, labels) / sqrt(var(predictions) * var(labels))`. update_op: An operation that updates the underlying variables appropriately. Raises: ValueError: If `labels` and `predictions` are of different sizes, or if `weights` is the wrong size, or if either `metrics_collections` or `updates_collections` are not a `list` or `tuple`. """ with variable_scope.variable_scope(name, 'pearson_r', [predictions, labels]): predictions, labels = tensor_util.remove_squeezable_dimensions( predictions, labels) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) cov, update_cov = streaming_covariance( predictions, labels, weights=weights, name='covariance') var_predictions, update_var_predictions = streaming_covariance( predictions, predictions, weights=weights, name='variance_predictions') var_labels, update_var_labels = streaming_covariance( labels, labels, weights=weights, name='variance_labels') pearson_r = _safe_div(
tensorflow.contrib.framework.tensor_util.remove_squeezable_dimensions
652
import tensorflow as tf if task_name not in processors: raise ValueError("Task not found: %s" % (task_name)) processor = processors[task_name]() label_list = processor.get_labels() tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR']) is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 run_config = tf.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps, tpu_config=tf.contrib.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores,
tensorflow.contrib.cluster_resolver.TPUClusterResolver
653
import tensorflow as tf with tf.name_scope('validate'): x, y = self._build_data_pipeline() y_hat, loss = self._build_validation_model(x, y) with tf.control_dependencies([update_op]): return tf.print('expect', loss, y, y_hat, summarize=50) class DataOwner: BATCH_SIZE = 30
tensorflow.print
654
import tensorflow as tf mvalid = PTBModel(is_training=False, config=config, input_=valid_input) tf.summary.scalar("Validation Loss", mvalid.cost) with tf.name_scope("Test"): test_input = PTBInput( config=eval_config, data=test_data, name="TestInput") with tf.variable_scope("Model", reuse=True, initializer=initializer): mtest = PTBModel(is_training=False, config=eval_config, input_=test_input) models = {"Train": m, "Valid": mvalid, "Test": mtest} for name, model in models.iteritems(): model.export_ops(name) metagraph = tf.train.export_meta_graph() if tf.__version__ < "1.1.0" and FLAGS.num_gpus > 1: raise ValueError("num_gpus > 1 is not supported for TensorFlow versions " "below 1.1.0") soft_placement = False if FLAGS.num_gpus > 1: soft_placement = True util.auto_parallel(metagraph, m) with tf.Graph().as_default(): tf.train.import_meta_graph(metagraph) for model in models.values(): model.import_ops()
tensorflow.train.export_meta_graph
655
from tensorflow.contrib.eager.python.examples.spinn import data inference_sentences=("( foo ( bar . ) )", None)) with self.assertRaises(ValueError): spinn.train_or_infer_spinn(embed, word2index, None, None, None, config) def testTrainSpinn(self): """Test with fake toy SNLI data and GloVe vectors.""" # 1. Create and load a fake SNLI data file and a fake GloVe embedding file. snli_1_0_dir = os.path.join(self._temp_data_dir, "snli/snli_1.0") fake_train_file = 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) train_data = data.SnliData(fake_train_file, word2index) dev_data = data.SnliData(fake_train_file, word2index) test_data = data.SnliData(fake_train_file, word2index) # 2. Create a fake config. config = _test_spinn_config( data.WORD_VECTOR_LEN, 4, logdir=os.path.join(self._temp_data_dir, "logdir")) # 3. Test training of a SPINN model. trainer = spinn.train_or_infer_spinn( embed, word2index, train_data, dev_data, test_data, config) # 4. Load train loss values from the summary files and verify that they # decrease with training. summary_file = glob.glob(os.path.join(config.logdir, "events.out.*"))[0]
tensorflow.contrib.eager.python.examples.spinn.data.SnliData
656
import tensorflow as tf logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) if task_name != "sts-b": probabilities = tf.nn.softmax(logits, axis=-1) predictions = tf.argmax(probabilities, axis=-1, output_type=tf.int32) log_probs = tf.nn.log_softmax(logits, axis=-1)
tensorflow.nn.softmax
657
import tensorflow as tf # define train_op gen_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.05) dis_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.05) # wrapper to make the optimizer work with TPUs if params['use_tpu']: gen_optimizer = tf.contrib.tpu.CrossShardOptimizer(gen_optimizer) dis_optimizer = tf.contrib.tpu.CrossShardOptimizer(dis_optimizer) gan_train_ops = tf.contrib.gan.gan_train_ops(gan_model, gan_loss, gen_optimizer, dis_optimizer) while_loop = tf.contrib.tpu.while_loop if params['use_tpu'] else tf.while_loop # train the discriminator 100 steps inputs = [tf.constant(0), tf.constant(0.0)] cond = lambda i, x: tf.less(i, 100) def body(i, x): return tf.add(i, 1), gan_train_ops.discriminator_train_op
tensorflow.contrib.gan.gan_train_ops
658
from tensorflow.python.ops import array_ops with self.cached_session(): embed_np = embeds[ids] embed_tf = ops.embedding_lookup(embeds, ids).eval() self.assertEqual(embed_np.shape, embed_tf.shape) self.assertAllClose(embed_np, embed_tf) def test_categorical_variable(self): random_seed.set_random_seed(42) with self.cached_session() as sess: cat_var_idx = array_ops.placeholder(dtypes.int64, [2, 2]) embeddings = ops.categorical_variable( cat_var_idx, n_classes=5, embedding_size=10, name="my_cat_var") sess.run(variables.global_variables_initializer()) emb1 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 1], [2, 3]]}) emb2 = sess.run(embeddings, feed_dict={cat_var_idx.name: [[0, 2], [1, 3]]}) self.assertEqual(emb1.shape, emb2.shape)
tensorflow.python.ops.array_ops.placeholder
659
import tensorflow as tf for name, tensor in predictions.items() }) return tf.estimator.EstimatorSpec( mode, predictions=predictions,
tensorflow.estimator.EstimatorSpec
660
import tensorflow as tf 'image/object/area': tf.io.VarLenFeature(tf.float32), 'image/object/is_crowd': tf.io.VarLenFeature(tf.int64), } if include_mask: self._keys_to_features.update({ 'image/object/mask': tf.io.VarLenFeature(tf.string), }) def _decode_image(self, parsed_tensors): """Decodes the image and set its static shape.""" image = tf.io.decode_image(parsed_tensors['image/encoded'], channels=3) image.set_shape([None, None, 3]) return image def _decode_boxes(self, parsed_tensors): """Concat box coordinates in the format of [ymin, xmin, ymax, xmax].""" xmin = parsed_tensors['image/object/bbox/xmin'] xmax = parsed_tensors['image/object/bbox/xmax'] ymin = parsed_tensors['image/object/bbox/ymin'] ymax = parsed_tensors['image/object/bbox/ymax'] return tf.stack([ymin, xmin, ymax, xmax], axis=-1) def _decode_masks(self, parsed_tensors):
tensorflow.io.decode_image
661
from tensorflow.python.util.deprecation import deprecated """ dim = 1 for d in variable.get_shape()[1:].as_list(): dim *= d return tf.reshape(variable, shape=[-1, dim], name=name) @deprecated("2018-06-30", "TensorLayer relies on TensorFlow to check naming.") def clear_layers_name(): logging.warning('this method is DEPRECATED and has no effect, please remove it from your code.') @deprecated("2018-06-30", "TensorLayer relies on TensorFlow to check name reusing.") def set_name_reuse(enable=True): logging.warning('this method is DEPRECATED and has no effect, please remove it from your code.') def initialize_rnn_state(state, feed_dict=None): """Returns the initialized RNN state. The inputs are `LSTMStateTuple` or `State` of `RNNCells`, and an optional `feed_dict`. Parameters ---------- state : RNN state.
tensorflow.python.util.deprecation.deprecated
662
import tensorflow as tf import numpy as np from google.protobuf import text_format import tensorflow as tf import preprocessing import datasets NUM_TEST_IMAGES = 50000 def load_graph(model_file): graph = tf.Graph() graph_def = tf.compat.v1.GraphDef() import os file_ext = os.path.splitext(model_file)[1] with open(model_file, "rb") as f: if file_ext == '.pbtxt': text_format.Merge(f.read(), graph_def) else:
tensorflow.Graph
663
import tensorflow as tf f_i_ = distribution_f.prob(action_) f_polyak_i = f_polyak.prob(self.action_ph) phi_i = strip(train_model.proba_distribution.mean, self.n_envs, self.n_steps) q_value = strip(train_model.value_fn, self.n_envs, self.n_steps) q_i = q_value[:, 0] rho_i = tf.reshape(f_i, [-1, 1]) / (self.mu_ph + eps) rho_i_ = tf.reshape(f_i_, [-1, 1]) / (self.mu_ph + eps) qret = q_retrace(self.reward_ph, self.done_ph, q_i, value, tf.pow(rho_i, 1 / self.n_act), self.n_envs, self.n_steps, self.gamma) else: # strip off last step # f is a distribution, chosen to be Gaussian distributions # with fixed diagonal covariance and mean \phi(x) # in the paper distribution_f, f_polyak, q_value = \ map(lambda variables: strip(variables, self.n_envs, self.n_steps), [train_model.policy_proba, polyak_model.policy_proba, train_model.q_value])
tensorflow.pow
664
import tensorflow as tf parser.add_argument('--max_train_step', type=int, default=50000, help='the maximum training step') parser.add_argument('--model_path', type=str, default='', help='the path of checkpoint file') args = parser.parse_args() def model(): x = tf.placeholder(tf.float32, [None, 784], name='x') gt = tf.placeholder(tf.float32, [None, 10], name='groundtruth') with tf.variable_scope('layer1'): w1 = tf.get_variable('weight1', [784, 1024], initializer=tf.random_normal_initializer()) b1 = tf.get_variable('bias1', [1024], initializer=tf.constant_initializer(0.0)) h1 = tf.nn.relu(tf.matmul(x, w1) + b1) with tf.variable_scope('layer2'): w2 = tf.get_variable('weight2', [1024, 1024], initializer=tf.random_normal_initializer()) b2 = tf.get_variable('bias2', [1024], initializer=tf.constant_initializer(0.0)) h2 = tf.nn.relu(tf.matmul(h1, w2) + b2) with tf.variable_scope('layer3'): w3 = tf.get_variable('weight3', [1024, 10], initializer=tf.random_normal_initializer()) b3 = tf.get_variable('bias3', [10], initializer=tf.constant_initializer(0.0)) y = tf.matmul(h2, w3) + b3 # losses
tensorflow.matmul
665
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib self._hidden_units = hidden_units self._feature_columns = tuple(feature_columns or []) self._enable_centered_bias = enable_centered_bias self._estimator = estimator.Estimator( model_fn=_dnn_model_fn, model_dir=model_dir, config=config, params={ "head": head_lib._multi_class_head( # pylint: disable=protected-access n_classes, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias), "hidden_units": hidden_units, "feature_columns": self._feature_columns, "optimizer":
tensorflow.contrib.learn.python.learn.estimators.head._multi_class_head
666
import tensorflow as tf if max_iterations: pbar.close() # List of dicts to dict of lists metrics = dict(zip(metrics[0], zip(*[m.values() for m in metrics]))) metrics = {m: np.nanmean(metrics[m], axis=0) for m in metrics} return metrics def _checkpoint_var_search(self, checkpoint_path): reader = tf.train.NewCheckpointReader(checkpoint_path) saved_shapes = reader.get_variable_to_shape_map() model_names = tf.model_variables() # Used by tf.slim layers if not len(tf.model_variables()): model_names = tf.global_variables() # Fallback when slim is not used model_names = set([v.name.split(':')[0] for v in model_names]) checkpoint_names = set(saved_shapes.keys()) found_names = model_names & checkpoint_names missing_names = model_names - checkpoint_names
tensorflow.train.NewCheckpointReader
667
from tensorflow.contrib.slim.python.slim.data import test_utils def _create_tfrecord_dataset(tmpdir): if not gfile.Exists(tmpdir): gfile.MakeDirs(tmpdir) data_sources = test_utils.create_tfrecord_files(tmpdir, num_files=1) keys_to_features = { 'image/encoded':
tensorflow.contrib.slim.python.slim.data.test_utils.create_tfrecord_files
668
import tensorflow as tf identity = (registry.Modalities.GENERIC, None) if self.has_inputs: p.input_modality["inputs_segmentation"] = identity p.input_modality["inputs_position"] = identity p.input_modality["targets_segmentation"] = identity p.input_modality["targets_position"] = identity def example_reading_spec(self): data_fields = {"targets": tf.VarLenFeature(tf.int64)} if self.has_inputs: data_fields["inputs"] = tf.VarLenFeature(tf.int64) if self.packed_length: if self.has_inputs: data_fields["inputs_segmentation"] = tf.VarLenFeature(tf.int64) data_fields["inputs_position"] = tf.VarLenFeature(tf.int64)
tensorflow.VarLenFeature
669
import tensorflow as tf Returns: a tensor with shape [N, M] representing pairwise iou scores. """ intersections = pairwise_intersection(boxlist1, boxlist2) areas1 = area(boxlist1) areas2 = area(boxlist2) unions = ( tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections) return tf.where( tf.equal(intersections, 0.0), tf.zeros_like(intersections), tf.truediv(intersections, unions)) @under_name_scope() def pairwise_iou_batch(proposal_boxes, gt_boxes, orig_gt_counts, batch_size): """Computes pairwise intersection-over-union between box collections. Args: proposal_boxes: K x 5 (batch_index, x1, y1, x2, y2) gt_boxes: BS x MaxNumGTs x 4 orig_gt_counts: BS
tensorflow.truediv
670
from tensorflow.python.ops import control_flow_ops if update_ops is None: update_ops = global_update_ops else: update_ops = set(update_ops) # Make sure update_ops are computed before total_loss. if update_ops: with tf.control_dependencies(update_ops): barrier = tf.no_op(name='update_barrier') self.d_losses[-1] = control_flow_ops.with_dependencies([barrier], self.d_losses[-1]) self.g_losses[-1] = control_flow_ops.with_dependencies([barrier], self.g_losses[-1]) self.d_loss_real = control_flow_ops.with_dependencies([barrier], self.d_loss_real) self.d_loss_fake = control_flow_ops.with_dependencies([barrier], self.d_loss_fake) self.d_loss_class = control_flow_ops.with_dependencies([barrier], self.d_loss_class) t_vars = self._get_vars_semi_supervised() if self.clip_by_global_norm: self.capped_d_grads = self._clip_grad_global_norms( t_vars['d_vars'], self.d_losses[-1], d_optimizer, gradient_noise_scale=0.0) self.capped_g_grads = self._clip_grad_global_norms(
tensorflow.python.ops.control_flow_ops.with_dependencies
671
import tensorflow as tf lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0) outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = tf.float32) # Slice to keep only the last cell of the RNN outputs = outputs[-1] #print('last outputs={}'.format(outputs)) # Output is result of linear activation of last layer of RNN weight = tf.Variable(tf.random_normal([LSTM_SIZE, N_OUTPUTS])) bias = tf.Variable(tf.random_normal([N_OUTPUTS])) predictions = tf.matmul(outputs, weight) + bias # 2. Loss function, training/eval ops if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL: loss = tf.losses.mean_squared_error(labels, predictions) train_op = tf.contrib.layers.optimize_loss( loss = loss, global_step = tf.train.get_global_step(), learning_rate = 0.01, optimizer = "SGD") eval_metric_ops = { "rmse": tf.metrics.root_mean_squared_error(labels, predictions) } else: loss = None train_op = None eval_metric_ops = None
tensorflow.losses.mean_squared_error
672
import tensorflow as tf input_tensor: The input tensor of tensorflow graph. output_tensor: The output tensor of tensorflow graph. use_mlir_converter: Whether or not to use MLIRConverter to convert the model. Returns: The tflite inference result. """ converter = tf.lite.TFLiteConverter.from_session(sess, [input_tensor], [output_tensor]) tflite = converter.convert() converter.experimental_enable_mlir_converter = use_mlir_converter interpreter = tf.lite.Interpreter(model_content=tflite) try: interpreter.allocate_tensors() except ValueError: assert False input_index = (interpreter.get_input_details()[0]["index"]) interpreter.set_tensor(input_index, test_inputs) interpreter.invoke() output_index = (interpreter.get_output_details()[0]["index"]) result = interpreter.get_tensor(output_index) # Reset all variables so it will not pollute other inferences.
tensorflow.lite.Interpreter
673
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
674
import tensorflow as tf if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL: loss = tf.losses.mean_squared_error(labels, predictions) train_op = tf.contrib.layers.optimize_loss( loss = loss, global_step = tf.train.get_global_step(), learning_rate = 0.01, optimizer = "SGD") eval_metric_ops = { "rmse": tf.metrics.root_mean_squared_error(labels, predictions) } else: loss = None train_op = None eval_metric_ops = None # 3. Create predictions
tensorflow.metrics.root_mean_squared_error
675
import tensorflow as tf inputs.append(inputs_) encoder_inputs_ = tf.concat(inputs, axis=2) # if encoder.convolution_activation.lower() == 'relu': encoder_inputs_ = tf.nn.relu(encoder_inputs_) if encoder.maxout_stride: if encoder.binary: raise NotImplementedError stride = encoder.maxout_stride k = tf.to_int32(tf.ceil(time_steps / stride) * stride) - time_steps # TODO: simpler pad = tf.zeros([batch_size, k, tf.shape(encoder_inputs_)[2]]) encoder_inputs_ = tf.concat([encoder_inputs_, pad], axis=1) encoder_inputs_ = tf.nn.pool(encoder_inputs_, window_shape=[stride], pooling_type='MAX', padding='VALID', strides=[stride]) encoder_input_length_ = tf.to_int32(tf.ceil(encoder_input_length_ / stride)) if encoder.highway_layers: x = encoder_inputs_ for j in range(encoder.highway_layers): size = x.shape[2].value with tf.variable_scope('highway_{}'.format(j + 1)): g = tf.layers.dense(x, size, activation=tf.nn.sigmoid, use_bias=True, name='g') y = tf.layers.dense(x, size, activation=tf.nn.relu, use_bias=True, name='y') x = g * y + (1 - g) * x
tensorflow.nn.pool
676
from tensorflow.contrib.eager.python.examples.l2hmc import l2hmc x = tf.random_normal([hparams.n_samples, hparams.x_dim], dtype=tf.float32) dynamics = l2hmc.Dynamics( x_dim=hparams.x_dim,
tensorflow.contrib.eager.python.examples.l2hmc.l2hmc.Dynamics
677
import tensorflow as tf sess = tf.Session() # 上面的wtih或者是name都是可选的,可以选择添加,也可以选择不添加,but下面的这一行是一定要写的。 # 这个表明了 在当前的目录下面创建以恶搞logs的文件家,然后把图的信息保存进去 # 这样运行完这段代码之后,就会有一个logs的文件夹被创建 if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1: # tensorflow version < 0.12 writer = tf.train.SummaryWriter('logs/', sess.graph) else: # tensorflow version >= 0.12 writer = tf.summary.FileWriter("logs/", sess.graph)
tensorflow.__version__.split
678
from tensorflow.python.ops import nn """ in_top_k = math_ops.to_float(nn.in_top_k(predictions, labels, k))
tensorflow.python.ops.nn.in_top_k
679
import tensorflow.contrib.graph_editor as ge # partial derivatives to the checkpointed tensors and xs ops_to_copy = fast_backward_ops(seed_ops=[y.op for y in ys], stop_at_ts=checkpoints, within_ops=fwd_ops) debug_print("Found %s ops to copy within fwd_ops %s, seed %s, stop_at %s", len(ops_to_copy), fwd_ops, [r.op for r in ys], checkpoints) debug_print("ops_to_copy = %s", ops_to_copy) debug_print("Processing list %s", ys) copied_sgv, info = ge.copy_with_input_replacements(ge.sgv(ops_to_copy), {}) for origin_op, op in info._transformed_ops.items(): op._set_device(origin_op.node_def.device) copied_ops = info._transformed_ops.values() debug_print("Copied %s to %s", ops_to_copy, copied_ops) ge.reroute_ts(checkpoints_disconnected.values(), checkpoints_disconnected.keys(), can_modify=copied_ops) debug_print("Rewired %s in place of %s restricted to %s", checkpoints_disconnected.values(), checkpoints_disconnected.keys(), copied_ops)
tensorflow.contrib.graph_editor.sgv
680
from tensorflow.python.framework import tensor_shape returned_shape = [] for i, dim in enumerate(input_shape.dims): if i != dimension: returned_shape.append(dim) return [tensor_shape.TensorShape(returned_shape)] else: raise ValueError( "dimension (%d) must be in the range [0, %d), where %d is the number "
tensorflow.python.framework.tensor_shape.TensorShape
681
from tensorflow.python.platform import gfile class BoostedTreeEstimatorTest(test_util.TensorFlowTestCase): def setUp(self): self._export_dir_base = tempfile.mkdtemp() + "export/" gfile.MkDir(self._export_dir_base) def testFitAndEvaluateDontThrowException(self): learner_config = learner_pb2.LearnerConfig()
tensorflow.python.platform.gfile.MkDir
682
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],
tensorflow.sparse_tensor_dense_matmul
683
from tensorflow.contrib.learn.python.learn.datasets import base 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( input_fn=input_fn, steps=100) self._assertSingleClassMetrics(metrics) def benchmarkMultiClass(self): iris = base.load_iris() 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)) classifier = dnn_linear_combined.DNNLinearCombinedClassifier( n_classes=3, linear_feature_columns=(bucketized_feature,), dnn_feature_columns=(cont_feature,),
tensorflow.contrib.learn.python.learn.datasets.base.load_iris
684
import tensorflow as tf # Running this command requires an internet connection and a few minutes to download all the images. (X_train, y_train), (X_test, y_test) = tf.contrib.keras.datasets.cifar10.load_data()
tensorflow.contrib.keras.datasets.cifar10.load_data
685
import tensorflow as tf val = val[permutation] shape = np.array([3, 4]).astype(np.int64) return tf.SparseTensorValue(ind, val, shape) def _SparseTensorValue_1x1x1(self):
tensorflow.SparseTensorValue
686
import tensorflow as tf A = tf.subtract(tf.expand_dims(X, 0), tf.expand_dims(X, 1)) return (1.0/(N*N)) * tf.reduce_sum(N0(A, 2*y)) + N0(0.0, 2.0 + 2*y) - (2/N) * tf.reduce_sum(N0(X, 1.0 + 2*y)) def cw_2d(X, y=None): def __phi(x): def __phi_f(s): t = s/7.5 return tf.exp(-s/2) * (1 + 3.5156229*t**2 + 3.0899424*t**4 + 1.2067492*t**6 + 0.2659732*t**8 + 0.0360768*t**10 + 0.0045813*t**12) def __phi_g(s): t = s/7.5 return tf.sqrt(2/s) * (0.39894228 + 0.01328592*t**(-1) + 0.00225319*t**(-2) - 0.00157565*t**(-3) + 0.0091628*t**(-4) - 0.02057706*t**(-5) + 0.02635537*t**(-6) - 0.01647633*t**(-7) + 0.00392377*t**(-8))
tensorflow.exp
687
import tensorflow as tf images = data['data'] num_images = images.shape[0] images = images.reshape((num_images, 3, 32, 32)) labels = data['labels'] with tf.Graph().as_default(): image_placeholder = tf.placeholder(dtype=tf.uint8) encoded_image = tf.image.encode_png(image_placeholder) with tf.Session('') as sess: for j in range(num_images): sys.stdout.write('\r>> Reading file [%s] image %d' % ( filename, offset + 1)) sys.stdout.flush()
tensorflow.image.encode_png
688
import tensorflow as tf 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") X = tf.nn.leaky_relu(X, 0.2) X = self.conv('d_out', X, 1, size=1, stride=1, padding="SAME") print('D out:', X.get_shape().as_list())
tensorflow.nn.leaky_relu
689
from tensorflow.contrib.learn.python.learn.estimators import tensor_signature def _check_inputs(self, features, targets): if self._features_info is not None: if not tensor_signature.tensors_compatible(features, self._features_info): raise ValueError('Features are incompatible with given information. ' 'Given features: %s, required signatures: %s.' % (str(features), str(self._features_info))) else: self._features_info = tensor_signature.create_signatures(features) if self._targets_info is not None: if not tensor_signature.tensors_compatible(targets, self._targets_info): raise ValueError('Targets are incompatible with given information. ' 'Given targets: %s, required signatures: %s.' % (str(targets), str(self._targets_info))) else:
tensorflow.contrib.learn.python.learn.estimators.tensor_signature.create_signatures
690
import tensorflow as tf tf.app.flags.DEFINE_integer('loss_scale', 1024, '') tf.app.flags.DEFINE_float('moving_average_decay', 0.997, '') tf.app.flags.DEFINE_string('gpu_list', '1', '') tf.app.flags.DEFINE_string('checkpoint_path', '/tmp/east_resnet_v1_50_rbox/', '') tf.app.flags.DEFINE_boolean('restore', False, 'whether to resotre from checkpoint') tf.app.flags.DEFINE_integer('save_checkpoint_steps', 1000, '') tf.app.flags.DEFINE_integer('save_summary_steps', 100, '') tf.app.flags.DEFINE_string('pretrained_model_path', None, '')
tensorflow.app.flags.DEFINE_boolean
691
from tensorflow.contrib.learn.python.learn import ops ids = np.random.randint(0, n_embed, ids_shape) with self.cached_session(): embed_np = embeds[ids] embed_tf = ops.embedding_lookup(embeds, ids).eval() self.assertEqual(embed_np.shape, embed_tf.shape) self.assertAllClose(embed_np, embed_tf)
tensorflow.contrib.learn.python.learn.ops.embedding_lookup
692
import tensorflow as tf :return: [Tensor] Convolution output. """ with tf.variable_scope(name): in_filters = ksize[2] out_filters = ksize[3] n = ksize[0] * ksize[1] * out_filters init = tf.truncated_normal_initializer( mean=0.0, stddev=np.sqrt(2.0 / n), seed=0, dtype=dtype) def _reg(x): if weight_decay is not None: return tf.multiply(tf.nn.l2_loss(x), weight_decay) else: return None if weight_decay is not None: reg = _reg else: reg = None kernel = tf.get_variable( 'w', ksize, initializer=init, regularizer=reg, dtype=dtype, trainable=True)
tensorflow.nn.l2_loss
693
from tensorflow.python.framework import tensor_shape filter_shape = tensor_util.constant_value(op.inputs[1]) if filter_shape is not None: return [tensor_shape.TensorShape(filter_shape.tolist())] else: # NOTE(mrry): We could in principle work out the shape from the # gradients and the attrs, but if we do not know filter_shape # statically, then we are unlikely to know the shape of the # gradients either. return [tensor_shape.unknown_shape(ndims=4)] @ops.RegisterShape("Conv2DBackpropInput") def _Conv2DBackpropInputShape(op): """Shape function for the Conv2DBackpropInput op.""" input_shape = tensor_util.constant_value(op.inputs[0]) if input_shape is not None:
tensorflow.python.framework.tensor_shape.unknown_shape
694
import tensorflow as tf var = tf.Variable(other_value, name=var_name) save = tf.train.Saver({var_name: var}) save.restore(sess, save_path) self.assertAllClose(var_value, var.eval()) def testCacheRereadsFile(self): save_path = os.path.join(self.get_temp_dir(), "cache_rereads") # Save and reload one Variable named "var0". self._SaveAndLoad("var0", 0.0, 1.0, save_path) # Save and reload one Variable named "var1" in the same file. # The cached readers should know to re-read the file. self._SaveAndLoad("var1", 1.1, 2.2, save_path) def testGPU(self): if not tf.test.is_built_with_cuda(): return 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) with tf.Session("", graph=tf.Graph()) as sess: with sess.graph.device("/gpu:0"): v0_2 = tf.Variable(543.21) save = tf.train.Saver({"v0": v0_2})
tensorflow.test.is_built_with_cuda
695
import tensorflow as tf self.dropout_input = args.dropout_input self.clip_norm = args.clip_norm self.embedding_init = embedding_init self.x = tf.placeholder(tf.int32, [None, None], 'input') self.y = tf.placeholder(tf.int32, [None, self.num_classes], 'labels') self.seq_len = tf.placeholder(tf.int64, [None], 'input_length') def inference(self, forward_only=None): embed_inputs = tf.nn.embedding_lookup(self.embedding_init, self.x) ## (batch_size, seq_len, 100)
tensorflow.placeholder
696
import tensorflow as tf A namedtuple of input and target data. """ input_text = tf.map_fn(lambda x: x[:-1], chunk) target_text = tf.map_fn(lambda x: x[1:], chunk) return (input_text, target_text) def build_to_ids_fn(vocab, max_seq_len): """Constructs function mapping examples to sequences of token indices.""" _, _, bos, eos = get_special_tokens(len(vocab)) table_values = np.arange(len(vocab), dtype=np.int64) table = tf.lookup.StaticVocabularyTable( tf.lookup.KeyValueTensorInitializer(vocab, table_values), num_oov_buckets=1) def to_ids(example): sentence = tf.reshape(example['tokens'], shape=[1]) words = tf.strings.split(sentence, sep=' ').values truncated_words = words[:max_seq_len] tokens = table.lookup(truncated_words) + 1 tokens = tf.cond( tf.less(tf.size(tokens), max_seq_len), lambda: tf.concat([tokens, [eos]], 0), lambda: tokens) return tf.concat([[bos], tokens], 0)
tensorflow.lookup.KeyValueTensorInitializer
697
from tensorflow.python.ops import state_ops 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):
tensorflow.python.ops.state_ops.scatter_add
698
import tensorflow as tf [rank_assertions[0]], tf.shape(image_list[0])) image_height = image_shape[0] image_width = image_shape[1] crop_size_assert = tf.Assert( tf.logical_and( tf.greater_equal(image_height, crop_height), tf.greater_equal(image_width, crop_width)), ['Crop size greater than the image size.']) asserts = [rank_assertions[0], crop_size_assert] for i in range(1, len(image_list)): image = image_list[i]
tensorflow.greater_equal
699