doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
tf.compat.v1.scatter_nd_update Applies sparse updates to individual values or slices in a Variable. tf.compat.v1.scatter_nd_update( ref, indices, updates, use_locking=True, name=None ) ref is a Tensor with rank P and indices is a Tensor of rank Q. indices must be integer tensor, containing indices into ref. It must be shape [d_0, ..., d_{Q-2}, K] where 0 < K <= P. The innermost dimension of indices (with length K) corresponds to indices into elements (if K = P) or slices (if K < P) along the Kth dimension of ref. updates is Tensor of rank Q-1+P-K with shape: [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]. For example, say we want to update 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this: ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8]) indices = tf.constant([[4], [3], [1] ,[7]]) updates = tf.constant([9, 10, 11, 12]) update = tf.compat.v1.scatter_nd_update(ref, indices, updates) with tf.compat.v1.Session() as sess: print sess.run(update) The resulting update to ref would look like this: [1, 11, 3, 10, 9, 6, 7, 12] See tf.scatter_nd for more details about how to make updates to slices. Args ref A Variable. indices A Tensor. Must be one of the following types: int32, int64. A tensor of indices into ref. updates A Tensor. Must have the same type as ref. A Tensor. Must have the same type as ref. A tensor of updated values to add to ref. use_locking An optional bool. Defaults to True. An optional bool. Defaults to True. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name A name for the operation (optional). Returns The value of the variable after the update.
tensorflow.compat.v1.scatter_nd_update
tf.compat.v1.scatter_sub Subtracts sparse updates to a variable reference. tf.compat.v1.scatter_sub( ref, indices, updates, use_locking=False, name=None ) # Scalar indices ref[indices, ...] -= updates[...] # Vector indices (for each i) ref[indices[i], ...] -= updates[i, ...] # High rank indices (for each i, ..., j) ref[indices[i, ..., j], ...] -= updates[i, ..., j, ...] This operation outputs ref after the update is done. This makes it easier to chain operations that need to use the reset value. Duplicate entries are handled correctly: if multiple indices reference the same location, their (negated) contributions add. Requires updates.shape = indices.shape + ref.shape[1:] or updates.shape = []. Args ref A mutable Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, complex64, int64, qint8, quint8, qint32, bfloat16, uint16, complex128, half, uint32, uint64. Should be from a Variable node. indices A Tensor. Must be one of the following types: int32, int64. A tensor of indices into the first dimension of ref. updates A Tensor. Must have the same type as ref. A tensor of updated values to subtract from ref. use_locking An optional bool. Defaults to False. If True, the subtraction will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name A name for the operation (optional). Returns A mutable Tensor. Has the same type as ref.
tensorflow.compat.v1.scatter_sub
tf.compat.v1.scatter_update Applies sparse updates to a variable reference. tf.compat.v1.scatter_update( ref, indices, updates, use_locking=True, name=None ) This operation computes # Scalar indices ref[indices, ...] = updates[...] # Vector indices (for each i) ref[indices[i], ...] = updates[i, ...] # High rank indices (for each i, ..., j) ref[indices[i, ..., j], ...] = updates[i, ..., j, ...] This operation outputs ref after the update is done. This makes it easier to chain operations that need to use the reset value. If values in ref is to be updated more than once, because there are duplicate entries in indices, the order at which the updates happen for each value is undefined. Requires updates.shape = indices.shape + ref.shape[1:]. Args ref A Variable. indices A Tensor. Must be one of the following types: int32, int64. A tensor of indices into the first dimension of ref. updates A Tensor. Must have the same type as ref. A tensor of updated values to store in ref. use_locking An optional bool. Defaults to True. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. name A name for the operation (optional). Returns Same as ref. Returned as a convenience for operations that want to use the updated values after the update is done.
tensorflow.compat.v1.scatter_update
tf.compat.v1.serialize_many_sparse Serialize N-minibatch SparseTensor into an [N, 3] Tensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.io.serialize_many_sparse tf.compat.v1.serialize_many_sparse( sp_input, name=None, out_type=tf.dtypes.string ) The SparseTensor must have rank R greater than 1, and the first dimension is treated as the minibatch dimension. Elements of the SparseTensor must be sorted in increasing order of this first dimension. The serialized SparseTensor objects going into each row of the output Tensor will have rank R-1. The minibatch size N is extracted from sparse_shape[0]. Args sp_input The input rank R SparseTensor. name A name prefix for the returned tensors (optional). out_type The dtype to use for serialization. Returns A matrix (2-D Tensor) with N rows and 3 columns. Each column represents serialized SparseTensor's indices, values, and shape (respectively). Raises TypeError If sp_input is not a SparseTensor.
tensorflow.compat.v1.serialize_many_sparse
tf.compat.v1.serialize_sparse Serialize a SparseTensor into a 3-vector (1-D Tensor) object. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.io.serialize_sparse tf.compat.v1.serialize_sparse( sp_input, name=None, out_type=tf.dtypes.string ) Args sp_input The input SparseTensor. name A name prefix for the returned tensors (optional). out_type The dtype to use for serialization. Returns A 3-vector (1-D Tensor), with each column representing the serialized SparseTensor's indices, values, and shape (respectively). Raises TypeError If sp_input is not a SparseTensor.
tensorflow.compat.v1.serialize_sparse
tf.compat.v1.Session A class for running TensorFlow operations. tf.compat.v1.Session( target='', graph=None, config=None ) A Session object encapsulates the environment in which Operation objects are executed, and Tensor objects are evaluated. For example: tf.compat.v1.disable_eager_execution() # need to disable eager in TF2.x # Build a graph. a = tf.constant(5.0) b = tf.constant(6.0) c = a * b # Launch the graph in a session. sess = tf.compat.v1.Session() # Evaluate the tensor `c`. print(sess.run(c)) # prints 30.0 A session may own resources, such as tf.Variable, tf.queue.QueueBase, and tf.compat.v1.ReaderBase. It is important to release these resources when they are no longer required. To do this, either invoke the tf.Session.close method on the session, or use the session as a context manager. The following two examples are equivalent: # Using the `close()` method. sess = tf.compat.v1.Session() sess.run(...) sess.close() # Using the context manager. with tf.compat.v1.Session() as sess: sess.run(...) The ConfigProto protocol buffer exposes various configuration options for a session. For example, to create a session that uses soft constraints for device placement, and log the resulting placement decisions, create a session as follows: # Launch the graph in a session that allows soft device placement and # logs the placement decisions. sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto( allow_soft_placement=True, log_device_placement=True)) Args target (Optional.) The execution engine to connect to. Defaults to using an in-process engine. See Distributed TensorFlow for more examples. graph (Optional.) The Graph to be launched (described above). config (Optional.) A ConfigProto protocol buffer with configuration options for the session. Attributes graph The graph that was launched in this session. graph_def A serializable version of the underlying TensorFlow graph. sess_str The TensorFlow process to which this session will connect. Methods as_default View source as_default() Returns a context manager that makes this object the default session. Use with the with keyword to specify that calls to tf.Operation.run or tf.Tensor.eval should be executed in this session. c = tf.constant(..) sess = tf.compat.v1.Session() with sess.as_default(): assert tf.compat.v1.get_default_session() is sess print(c.eval()) To get the current default session, use tf.compat.v1.get_default_session. Note: The as_default context manager does not close the session when you exit the context, and you must close the session explicitly. c = tf.constant(...) sess = tf.compat.v1.Session() with sess.as_default(): print(c.eval()) # ... with sess.as_default(): print(c.eval()) sess.close() Alternatively, you can use with tf.compat.v1.Session(): to create a session that is automatically closed on exiting the context, including when an uncaught exception is raised. Note: The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a with sess.as_default(): in that thread's function. Note: Entering a with sess.as_default(): block does not affect the current default graph. If you are using multiple graphs, and sess.graph is different from the value of tf.compat.v1.get_default_graph, you must explicitly enter a with sess.graph.as_default(): block to make sess.graph the default graph. Returns A context manager using this session as the default session. close View source close() Closes this session. Calling this method frees all resources associated with the session. Raises tf.errors.OpError Or one of its subclasses if an error occurs while closing the TensorFlow session. list_devices View source list_devices() Lists available devices in this session. devices = sess.list_devices() for d in devices: print(d.name) Where: Each element in the list has the following properties name: A string with the full name of the device. ex: /job:worker/replica:0/task:3/device:CPU:0 device_type: The type of the device (e.g. CPU, GPU, TPU.) memory_limit: The maximum amount of memory available on the device. Note: depending on the device, it is possible the usable memory could be substantially less. Raises tf.errors.OpError If it encounters an error (e.g. session is in an invalid state, or network errors occur). Returns A list of devices in the session. make_callable View source make_callable( fetches, feed_list=None, accept_options=False ) Returns a Python callable that runs a particular step. The returned callable will take len(feed_list) arguments whose types must be compatible feed values for the respective elements of feed_list. For example, if element i of feed_list is a tf.Tensor, the ith argument to the returned callable must be a numpy ndarray (or something convertible to an ndarray) with matching element type and shape. See tf.Session.run for details of the allowable feed key and value types. The returned callable will have the same return type as tf.Session.run(fetches, ...). For example, if fetches is a tf.Tensor, the callable will return a numpy ndarray; if fetches is a tf.Operation, it will return None. Args fetches A value or list of values to fetch. See tf.Session.run for details of the allowable fetch types. feed_list (Optional.) A list of feed_dict keys. See tf.Session.run for details of the allowable feed key types. accept_options (Optional.) If True, the returned Callable will be able to accept tf.compat.v1.RunOptions and tf.compat.v1.RunMetadata as optional keyword arguments options and run_metadata, respectively, with the same syntax and semantics as tf.Session.run, which is useful for certain use cases (profiling and debugging) but will result in measurable slowdown of the Callable's performance. Default: False. Returns A function that when called will execute the step defined by feed_list and fetches in this session. Raises TypeError If fetches or feed_list cannot be interpreted as arguments to tf.Session.run. partial_run View source partial_run( handle, fetches, feed_dict=None ) Continues the execution with more feeds and fetches. This is EXPERIMENTAL and subject to change. To use partial execution, a user first calls partial_run_setup() and then a sequence of partial_run(). partial_run_setup specifies the list of feeds and fetches that will be used in the subsequent partial_run calls. The optional feed_dict argument allows the caller to override the value of tensors in the graph. See run() for more information. Below is a simple example: a = array_ops.placeholder(dtypes.float32, shape=[]) b = array_ops.placeholder(dtypes.float32, shape=[]) c = array_ops.placeholder(dtypes.float32, shape=[]) r1 = math_ops.add(a, b) r2 = math_ops.multiply(r1, c) h = sess.partial_run_setup([r1, r2], [a, b, c]) res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2}) res = sess.partial_run(h, r2, feed_dict={c: res}) Args handle A handle for a sequence of partial runs. fetches A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (see documentation for run). feed_dict A dictionary that maps graph elements to values (described above). Returns Either a single value if fetches is a single graph element, or a list of values if fetches is a list, or a dictionary with the same keys as fetches if that is a dictionary (see documentation for run). Raises tf.errors.OpError Or one of its subclasses on error. partial_run_setup View source partial_run_setup( fetches, feeds=None ) Sets up a graph with feeds and fetches for partial run. This is EXPERIMENTAL and subject to change. Note that contrary to run, feeds only specifies the graph elements. The tensors will be supplied by the subsequent partial_run calls. Args fetches A single graph element, or a list of graph elements. feeds A single graph element, or a list of graph elements. Returns A handle for partial run. Raises RuntimeError If this Session is in an invalid state (e.g. has been closed). TypeError If fetches or feed_dict keys are of an inappropriate type. tf.errors.OpError Or one of its subclasses if a TensorFlow error happens. reset View source @staticmethod reset( target, containers=None, config=None ) Resets resource containers on target, and close all connected sessions. A resource container is distributed across all workers in the same cluster as target. When a resource container on target is reset, resources associated with that container will be cleared. In particular, all Variables in the container will become undefined: they lose their values and shapes. NOTE: (i) reset() is currently only implemented for distributed sessions. (ii) Any sessions on the master named by target will be closed. If no resource containers are provided, all containers are reset. Args target The execution engine to connect to. containers A list of resource container name strings, or None if all of all the containers are to be reset. config (Optional.) Protocol buffer with configuration options. Raises tf.errors.OpError Or one of its subclasses if an error occurs while resetting containers. run View source run( fetches, feed_dict=None, options=None, run_metadata=None ) Runs operations and evaluates tensors in fetches. This method runs one "step" of TensorFlow computation, by running the necessary graph fragment to execute every Operation and evaluate every Tensor in fetches, substituting the values in feed_dict for the corresponding input values. The fetches argument may be a single graph element, or an arbitrarily nested list, tuple, namedtuple, dict, or OrderedDict containing graph elements at its leaves. A graph element can be one of the following types: A tf.Operation. The corresponding fetched value will be None. A tf.Tensor. The corresponding fetched value will be a numpy ndarray containing the value of that tensor. A tf.sparse.SparseTensor. The corresponding fetched value will be a tf.compat.v1.SparseTensorValue containing the value of that sparse tensor. A get_tensor_handle op. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor. A string which is the name of a tensor or operation in the graph. The value returned by run() has the same shape as the fetches argument, where the leaves are replaced by the corresponding values returned by TensorFlow. Example: a = tf.constant([10, 20]) b = tf.constant([1.0, 2.0]) # 'fetches' can be a singleton v = session.run(a) # v is the numpy array [10, 20] # 'fetches' can be a list. v = session.run([a, b]) # v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the # 1-D array [1.0, 2.0] # 'fetches' can be arbitrary lists, tuples, namedtuple, dicts: MyData = collections.namedtuple('MyData', ['a', 'b']) v = session.run({'k1': MyData(a, b), 'k2': [b, a]}) # v is a dict with # v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and # 'b' (the numpy array [1.0, 2.0]) # v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array # [10, 20]. The optional feed_dict argument allows the caller to override the value of tensors in the graph. Each key in feed_dict can be one of the following types: If the key is a tf.Tensor, the value may be a Python scalar, string, list, or numpy ndarray that can be converted to the same dtype as that tensor. Additionally, if the key is a tf.compat.v1.placeholder, the shape of the value will be checked for compatibility with the placeholder. If the key is a tf.sparse.SparseTensor, the value should be a tf.compat.v1.SparseTensorValue. If the key is a nested tuple of Tensors or SparseTensors, the value should be a nested tuple with the same structure that maps to their corresponding values as above. Each value in feed_dict must be convertible to a numpy array of the dtype of the corresponding key. The optional options argument expects a [RunOptions] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on). The optional run_metadata argument expects a [RunMetadata] proto. When appropriate, the non-Tensor output of this step will be collected there. For example, when users turn on tracing in options, the profiled info will be collected into this argument and passed back. Args fetches A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (described above). feed_dict A dictionary that maps graph elements to values (described above). options A [RunOptions] protocol buffer run_metadata A [RunMetadata] protocol buffer Returns Either a single value if fetches is a single graph element, or a list of values if fetches is a list, or a dictionary with the same keys as fetches if that is a dictionary (described above). Order in which fetches operations are evaluated inside the call is undefined. Raises RuntimeError If this Session is in an invalid state (e.g. has been closed). TypeError If fetches or feed_dict keys are of an inappropriate type. ValueError If fetches or feed_dict keys are invalid or refer to a Tensor that doesn't exist. __enter__ View source __enter__() __exit__ View source __exit__( exec_type, exec_value, exec_tb )
tensorflow.compat.v1.session
tf.compat.v1.SessionLog A ProtocolMessage View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.summary.SessionLog Attributes checkpoint_path string checkpoint_path msg string msg status SessionStatus status Class Variables CHECKPOINT 3 START 1 STATUS_UNSPECIFIED 0 STOP 2 SessionStatus
tensorflow.compat.v1.sessionlog
tf.compat.v1.setdiff1d Computes the difference between two lists of numbers or strings. tf.compat.v1.setdiff1d( x, y, index_dtype=tf.dtypes.int32, name=None ) Given a list x and a list y, this operation returns a list out that represents all values that are in x but not in y. The returned list out is sorted in the same order that the numbers appear in x (duplicates are preserved). This operation also returns a list idx that represents the position of each out element in x. In other words: out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1] For example, given this input: x = [1, 2, 3, 4, 5, 6] y = [1, 3, 5] This operation would return: out ==> [2, 4, 6] idx ==> [1, 3, 5] Args x A Tensor. 1-D. Values to keep. y A Tensor. Must have the same type as x. 1-D. Values to remove. out_idx An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32. name A name for the operation (optional). Returns A tuple of Tensor objects (out, idx). out A Tensor. Has the same type as x. idx A Tensor of type out_idx.
tensorflow.compat.v1.setdiff1d
Module: tf.compat.v1.sets Tensorflow set operations. Functions difference(...): Compute set difference of elements in last dimension of a and b. intersection(...): Compute set intersection of elements in last dimension of a and b. set_difference(...): Compute set difference of elements in last dimension of a and b. set_intersection(...): Compute set intersection of elements in last dimension of a and b. set_size(...): Compute number of unique elements along last dimension of a. set_union(...): Compute set union of elements in last dimension of a and b. size(...): Compute number of unique elements along last dimension of a. union(...): Compute set union of elements in last dimension of a and b.
tensorflow.compat.v1.sets
tf.compat.v1.set_random_seed Sets the graph-level random seed for the default graph. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.random.set_random_seed tf.compat.v1.set_random_seed( seed ) Operations that rely on a random seed actually derive it from two seeds: the graph-level and operation-level seeds. This sets the graph-level seed. Its interactions with operation-level seeds is as follows: If neither the graph-level nor the operation seed is set: A random seed is used for this op. If the graph-level seed is set, but the operation seed is not: The system deterministically picks an operation seed in conjunction with the graph-level seed so that it gets a unique random sequence. Within the same version of tensorflow and user code, this sequence is deterministic. However across different versions, this sequence might change. If the code depends on particular seeds to work, specify both graph-level and operation-level seeds explicitly. If the graph-level seed is not set, but the operation seed is set: A default graph-level seed and the specified operation seed are used to determine the random sequence. If both the graph-level and the operation seed are set: Both seeds are used in conjunction to determine the random sequence. To illustrate the user-visible effects, consider these examples: To generate different sequences across sessions, set neither graph-level nor op-level seeds: a = tf.random.uniform([1]) b = tf.random.normal([1]) print("Session 1") with tf.compat.v1.Session() as sess1: print(sess1.run(a)) # generates 'A1' print(sess1.run(a)) # generates 'A2' print(sess1.run(b)) # generates 'B1' print(sess1.run(b)) # generates 'B2' print("Session 2") with tf.compat.v1.Session() as sess2: print(sess2.run(a)) # generates 'A3' print(sess2.run(a)) # generates 'A4' print(sess2.run(b)) # generates 'B3' print(sess2.run(b)) # generates 'B4' To generate the same repeatable sequence for an op across sessions, set the seed for the op: a = tf.random.uniform([1], seed=1) b = tf.random.normal([1]) # Repeatedly running this block with the same graph will generate the same # sequence of values for 'a', but different sequences of values for 'b'. print("Session 1") with tf.compat.v1.Session() as sess1: print(sess1.run(a)) # generates 'A1' print(sess1.run(a)) # generates 'A2' print(sess1.run(b)) # generates 'B1' print(sess1.run(b)) # generates 'B2' print("Session 2") with tf.compat.v1.Session() as sess2: print(sess2.run(a)) # generates 'A1' print(sess2.run(a)) # generates 'A2' print(sess2.run(b)) # generates 'B3' print(sess2.run(b)) # generates 'B4' To make the random sequences generated by all ops be repeatable across sessions, set a graph-level seed: tf.compat.v1.random.set_random_seed(1234) a = tf.random.uniform([1]) b = tf.random.normal([1]) # Repeatedly running this block with the same graph will generate the same # sequences of 'a' and 'b'. print("Session 1") with tf.compat.v1.Session() as sess1: print(sess1.run(a)) # generates 'A1' print(sess1.run(a)) # generates 'A2' print(sess1.run(b)) # generates 'B1' print(sess1.run(b)) # generates 'B2' print("Session 2") with tf.compat.v1.Session() as sess2: print(sess2.run(a)) # generates 'A1' print(sess2.run(a)) # generates 'A2' print(sess2.run(b)) # generates 'B1' print(sess2.run(b)) # generates 'B2' Args seed integer.
tensorflow.compat.v1.set_random_seed
tf.compat.v1.shape Returns the shape of a tensor. tf.compat.v1.shape( input, name=None, out_type=tf.dtypes.int32 ) This operation returns a 1-D integer tensor representing the shape of input. For example: t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) tf.shape(t) # [2, 2, 3] Args input A Tensor or SparseTensor. name A name for the operation (optional). out_type (Optional) The specified output type of the operation (int32 or int64). Defaults to tf.int32. Returns A Tensor of type out_type.
tensorflow.compat.v1.shape
Module: tf.compat.v1.signal Signal processing operations. See the tf.signal guide. Functions dct(...): Computes the 1D [Discrete Cosine Transform (DCT)][dct] of input. fft(...): Fast Fourier transform. fft2d(...): 2D fast Fourier transform. fft3d(...): 3D fast Fourier transform. fftshift(...): Shift the zero-frequency component to the center of the spectrum. frame(...): Expands signal's axis dimension into frames of frame_length. hamming_window(...): Generate a Hamming window. hann_window(...): Generate a Hann window. idct(...): Computes the 1D [Inverse Discrete Cosine Transform (DCT)][idct] of input. ifft(...): Inverse fast Fourier transform. ifft2d(...): Inverse 2D fast Fourier transform. ifft3d(...): Inverse 3D fast Fourier transform. ifftshift(...): The inverse of fftshift. inverse_mdct(...): Computes the inverse modified DCT of mdcts. inverse_stft(...): Computes the inverse Short-time Fourier Transform of stfts. inverse_stft_window_fn(...): Generates a window function that can be used in inverse_stft. irfft(...): Inverse real-valued fast Fourier transform. irfft2d(...): Inverse 2D real-valued fast Fourier transform. irfft3d(...): Inverse 3D real-valued fast Fourier transform. kaiser_bessel_derived_window(...): Generate a [Kaiser Bessel derived window][kbd]. kaiser_window(...): Generate a [Kaiser window][kaiser]. linear_to_mel_weight_matrix(...): Returns a matrix to warp linear scale spectrograms to the mel scale. mdct(...): Computes the [Modified Discrete Cosine Transform][mdct] of signals. mfccs_from_log_mel_spectrograms(...): Computes MFCCs of log_mel_spectrograms. overlap_and_add(...): Reconstructs a signal from a framed representation. rfft(...): Real-valued fast Fourier transform. rfft2d(...): 2D real-valued fast Fourier transform. rfft3d(...): 3D real-valued fast Fourier transform. stft(...): Computes the Short-time Fourier Transform of signals. vorbis_window(...): Generate a [Vorbis power complementary window][vorbis].
tensorflow.compat.v1.signal
tf.compat.v1.size Returns the size of a tensor. tf.compat.v1.size( input, name=None, out_type=tf.dtypes.int32 ) Returns a 0-D Tensor representing the number of elements in input of type out_type. Defaults to tf.int32. For example: t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]) tf.size(t) # 12 Args input A Tensor or SparseTensor. name A name for the operation (optional). out_type (Optional) The specified non-quantized numeric output type of the operation. Defaults to tf.int32. Returns A Tensor of type out_type. Defaults to tf.int32. Numpy Compatibility Equivalent to np.size()
tensorflow.compat.v1.size
tf.compat.v1.space_to_batch SpaceToBatch for 4-D tensors of type T. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.space_to_batch tf.compat.v1.space_to_batch( input, paddings, block_size=None, name=None, block_shape=None ) This is a legacy version of the more general SpaceToBatchND. Zero-pads and then rearranges (permutes) blocks of spatial data into batch. More specifically, this op outputs a copy of the input tensor where values from the height and width dimensions are moved to the batch dimension. After the zero-padding, both height and width of the input must be divisible by the block size. Args input A Tensor. 4-D with shape [batch, height, width, depth]. paddings A Tensor. Must be one of the following types: int32, int64. 2-D tensor of non-negative integers with shape [2, 2]. It specifies the padding of the input with zeros across the spatial dimensions as follows: paddings = [[pad_top, pad_bottom], [pad_left, pad_right]] The effective spatial dimensions of the zero-padded input tensor will be: height_pad = pad_top + height + pad_bottom width_pad = pad_left + width + pad_right The attr block_size must be greater than one. It indicates the block size. Non-overlapping blocks of size block_size x block size in the height and width dimensions are rearranged into the batch dimension at each location. The batch of the output tensor is batch * block_size * block_size. Both height_pad and width_pad must be divisible by block_size. The shape of the output will be: [batchblock_sizeblock_size, height_pad/block_size, width_pad/block_size, depth] Some examples: (1) For the following input of shape [1, 2, 2, 1] and block_size of 2: x = [[[[1], [2]], [[3], [4]]]] The output tensor has shape [4, 1, 1, 1] and value: [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] (2) For the following input of shape [1, 2, 2, 3] and block_size of 2: x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] The output tensor has shape [4, 1, 1, 3] and value: [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] (3) For the following input of shape [1, 4, 4, 1] and block_size of 2: x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]], [[9], [10], [11], [12]], [[13], [14], [15], [16]]]] The output tensor has shape [4, 2, 2, 1] and value: x = [[[[1], [3]], [[9], [11]]], [[[2], [4]], [[10], [12]]], [[[5], [7]], [[13], [15]]], [[[6], [8]], [[14], [16]]]] (4) For the following input of shape [2, 2, 4, 1] and block_size of 2: x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]]], [[[9], [10], [11], [12]], [[13], [14], [15], [16]]]] The output tensor has shape [8, 1, 2, 1] and value: x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] Among others, this operation is useful for reducing atrous convolution into regular convolution. block_size An int that is >= 2. name A name for the operation (optional). Returns A Tensor. Has the same type as input.
tensorflow.compat.v1.space_to_batch
tf.compat.v1.space_to_depth SpaceToDepth for tensors of type T. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.nn.space_to_depth tf.compat.v1.space_to_depth( input, block_size, name=None, data_format='NHWC' ) Rearranges blocks of spatial data, into depth. More specifically, this op outputs a copy of the input tensor where values from the height and width dimensions are moved to the depth dimension. The attr block_size indicates the input block size. Non-overlapping blocks of size block_size x block size are rearranged into depth at each location. The depth of the output tensor is block_size * block_size * input_depth. The Y, X coordinates within each block of the input become the high order component of the output channel index. The input tensor's height and width must be divisible by block_size. The data_format attr specifies the layout of the input and output tensors with the following options: "NHWC": [ batch, height, width, channels ] "NCHW": [ batch, channels, height, width ] "NCHW_VECT_C": qint8 [ batch, channels / 4, height, width, 4 ] It is useful to consider the operation as transforming a 6-D Tensor. e.g. for data_format = NHWC, Each element in the input tensor can be specified via 6 coordinates, ordered by decreasing memory layout significance as: n,oY,bY,oX,bX,iC (where n=batch index, oX, oY means X or Y coordinates within the output image, bX, bY means coordinates within the input block, iC means input channels). The output would be a transpose to the following layout: n,oY,oX,bY,bX,iC This operation is useful for resizing the activations between convolutions (but keeping all data), e.g. instead of pooling. It is also useful for training purely convolutional models. For example, given an input of shape [1, 2, 2, 1], data_format = "NHWC" and block_size = 2: x = [[[[1], [2]], [[3], [4]]]] This operation will output a tensor of shape [1, 1, 1, 4]: [[[[1, 2, 3, 4]]]] Here, the input has a batch of 1 and each batch element has shape [2, 2, 1], the corresponding output will have a single element (i.e. width and height are both 1) and will have a depth of 4 channels (1 * block_size * block_size). The output element shape is [1, 1, 4]. For an input tensor with larger depth, here of shape [1, 2, 2, 3], e.g. x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] This operation, for block_size of 2, will return the following tensor of shape [1, 1, 1, 12] [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] Similarly, for the following input of shape [1 4 4 1], and a block size of 2: x = [[[[1], [2], [5], [6]], [[3], [4], [7], [8]], [[9], [10], [13], [14]], [[11], [12], [15], [16]]]] the operator will return the following tensor of shape [1 2 2 4]: x = [[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]] Args input A Tensor. block_size An int that is >= 2. The size of the spatial block. data_format An optional string from: "NHWC", "NCHW", "NCHW_VECT_C". Defaults to "NHWC". name A name for the operation (optional). Returns A Tensor. Has the same type as input.
tensorflow.compat.v1.space_to_depth
Module: tf.compat.v1.sparse Sparse Tensor Representation. See also tf.sparse.SparseTensor. Classes class SparseConditionalAccumulator: A conditional accumulator for aggregating sparse gradients. class SparseTensor: Represents a sparse tensor. Functions add(...): Adds two tensors, at least one of each is a SparseTensor. (deprecated arguments) bincount(...): Count the number of times an integer value appears in a tensor. concat(...): Concatenates a list of SparseTensor along the specified dimension. (deprecated arguments) cross(...): Generates sparse cross from a list of sparse and dense tensors. cross_hashed(...): Generates hashed sparse cross from a list of sparse and dense tensors. expand_dims(...): Returns a tensor with an length 1 axis inserted at index axis. eye(...): Creates a two-dimensional sparse tensor with ones along the diagonal. fill_empty_rows(...): Fills empty rows in the input 2-D SparseTensor with a default value. from_dense(...): Converts a dense tensor into a sparse tensor. mask(...): Masks elements of IndexedSlices. matmul(...): Multiply SparseTensor (or dense Matrix) (of rank 2) "A" by dense matrix maximum(...): Returns the element-wise max of two SparseTensors. merge(...): Combines a batch of feature ids and values into a single SparseTensor. (deprecated) minimum(...): Returns the element-wise min of two SparseTensors. placeholder(...): Inserts a placeholder for a sparse tensor that will be always fed. reduce_max(...): Computes the max of elements across dimensions of a SparseTensor. (deprecated arguments) (deprecated arguments) reduce_max_sparse(...): Computes the max of elements across dimensions of a SparseTensor. (deprecated arguments) reduce_sum(...): Computes the sum of elements across dimensions of a SparseTensor. (deprecated arguments) (deprecated arguments) reduce_sum_sparse(...): Computes the sum of elements across dimensions of a SparseTensor. (deprecated arguments) reorder(...): Reorders a SparseTensor into the canonical, row-major ordering. reset_shape(...): Resets the shape of a SparseTensor with indices and values unchanged. reshape(...): Reshapes a SparseTensor to represent values in a new dense shape. retain(...): Retains specified non-empty values within a SparseTensor. segment_mean(...): Computes the mean along sparse segments of a tensor. segment_sqrt_n(...): Computes the sum along sparse segments of a tensor divided by the sqrt(N). segment_sum(...): Computes the sum along sparse segments of a tensor. slice(...): Slice a SparseTensor based on the start and `size. softmax(...): Applies softmax to a batched N-D SparseTensor. sparse_dense_matmul(...): Multiply SparseTensor (or dense Matrix) (of rank 2) "A" by dense matrix split(...): Split a SparseTensor into num_split tensors along axis. (deprecated arguments) to_dense(...): Converts a SparseTensor into a dense tensor. to_indicator(...): Converts a SparseTensor of ids into a dense bool indicator tensor. transpose(...): Transposes a SparseTensor
tensorflow.compat.v1.sparse
tf.compat.v1.SparseConditionalAccumulator A conditional accumulator for aggregating sparse gradients. Inherits From: ConditionalAccumulatorBase View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.SparseConditionalAccumulator tf.compat.v1.SparseConditionalAccumulator( dtype, shape=None, shared_name=None, name='sparse_conditional_accumulator', reduction_type='MEAN' ) Sparse gradients are represented by IndexedSlices. Up-to-date gradients (i.e., time step at which gradient was computed is equal to the accumulator's time step) are added to the accumulator. Extraction of the average gradient is blocked until the required number of gradients has been accumulated. Args dtype Datatype of the accumulated gradients. shape Shape of the accumulated gradients. shared_name Optional. If non-empty, this accumulator will be shared under the given name across multiple sessions. name Optional name for the accumulator. reduction_type Reduction type to use when taking the gradient. Attributes accumulator_ref The underlying accumulator reference. dtype The datatype of the gradients accumulated by this accumulator. name The name of the underlying accumulator. Methods apply_grad View source apply_grad( grad_indices, grad_values, grad_shape=None, local_step=0, name=None ) Attempts to apply a sparse gradient to the accumulator. The attempt is silently dropped if the gradient is stale, i.e., local_step is less than the accumulator's global time step. A sparse gradient is represented by its indices, values and possibly empty or None shape. Indices must be a vector representing the locations of non-zero entries in the tensor. Values are the non-zero slices of the gradient, and must have the same first dimension as indices, i.e., the nnz represented by indices and values must be consistent. Shape, if not empty or None, must be consistent with the accumulator's shape (if also provided). Example: A tensor [[0, 0], [0, 1], [2, 3]] can be represented indices: [1,2] values: [[0,1],[2,3]] shape: [3, 2] Args grad_indices Indices of the sparse gradient to be applied. grad_values Values of the sparse gradient to be applied. grad_shape Shape of the sparse gradient to be applied. local_step Time step at which the gradient was computed. name Optional name for the operation. Returns The operation that (conditionally) applies a gradient to the accumulator. Raises InvalidArgumentError If grad is of the wrong shape apply_indexed_slices_grad View source apply_indexed_slices_grad( grad, local_step=0, name=None ) Attempts to apply a gradient to the accumulator. The attempt is silently dropped if the gradient is stale, i.e., local_step is less than the accumulator's global time step. Args grad The gradient IndexedSlices to be applied. local_step Time step at which the gradient was computed. name Optional name for the operation. Returns The operation that (conditionally) applies a gradient to the accumulator. Raises InvalidArgumentError If grad is of the wrong shape num_accumulated View source num_accumulated( name=None ) Number of gradients that have currently been aggregated in accumulator. Args name Optional name for the operation. Returns Number of accumulated gradients currently in accumulator. set_global_step View source set_global_step( new_global_step, name=None ) Sets the global time step of the accumulator. The operation logs a warning if we attempt to set to a time step that is lower than the accumulator's own time step. Args new_global_step Value of new time step. Can be a variable or a constant name Optional name for the operation. Returns Operation that sets the accumulator's time step. take_grad View source take_grad( num_required, name=None ) Attempts to extract the average gradient from the accumulator. The operation blocks until sufficient number of gradients have been successfully applied to the accumulator. Once successful, the following actions are also triggered: Counter of accumulated gradients is reset to 0. Aggregated gradient is reset to 0 tensor. Accumulator's internal time step is incremented by 1. Args num_required Number of gradients that needs to have been aggregated name Optional name for the operation Returns A tuple of indices, values, and shape representing the average gradient. Raises InvalidArgumentError If num_required < 1 take_indexed_slices_grad View source take_indexed_slices_grad( num_required, name=None ) Attempts to extract the average gradient from the accumulator. The operation blocks until sufficient number of gradients have been successfully applied to the accumulator. Once successful, the following actions are also triggered: Counter of accumulated gradients is reset to 0. Aggregated gradient is reset to 0 tensor. Accumulator's internal time step is incremented by 1. Args num_required Number of gradients that needs to have been aggregated name Optional name for the operation Returns An IndexedSlices holding the value of the average gradient. Raises InvalidArgumentError If num_required < 1
tensorflow.compat.v1.sparseconditionalaccumulator
tf.compat.v1.SparseTensorValue SparseTensorValue(indices, values, dense_shape) tf.compat.v1.SparseTensorValue( indices, values, dense_shape ) Attributes indices values dense_shape
tensorflow.compat.v1.sparsetensorvalue
tf.compat.v1.sparse_add Adds two tensors, at least one of each is a SparseTensor. (deprecated arguments) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.add tf.compat.v1.sparse_add( a, b, threshold=None, thresh=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (thresh). They will be removed in a future version. Instructions for updating: thresh is deprecated, use threshold instead If one SparseTensor and one Tensor are passed in, returns a Tensor. If both arguments are SparseTensors, this returns a SparseTensor. The order of arguments does not matter. Use vanilla tf.add() for adding two dense Tensors. The shapes of the two operands must match: broadcasting is not supported. The indices of any input SparseTensor are assumed ordered in standard lexicographic order. If this is not the case, before this step run SparseReorder to restore index ordering. If both arguments are sparse, we perform "clipping" as follows. By default, if two values sum to zero at some index, the output SparseTensor would still include that particular location in its index, storing a zero in the corresponding value slot. To override this, callers can specify thresh, indicating that if the sum has a magnitude strictly smaller than thresh, its corresponding value and index would then not be included. In particular, thresh == 0.0 (default) means everything is kept and actual thresholding happens only for a positive value. For example, suppose the logical sum of two sparse operands is (densified): [ 2] [.1 0] [ 6 -.2] Then, thresh == 0 (the default): all 5 index/value pairs will be returned. thresh == 0.11: only .1 and 0 will vanish, and the remaining three index/value pairs will be returned. thresh == 0.21: .1, 0, and -.2 will vanish. Args a The first operand; SparseTensor or Tensor. b The second operand; SparseTensor or Tensor. At least one operand must be sparse. threshold An optional 0-D Tensor (defaults to 0). The magnitude threshold that determines if an output value/index pair takes space. Its dtype should match that of the values if they are real; if the latter are complex64/complex128, then the dtype should be float32/float64, correspondingly. thresh Deprecated alias for threshold. Returns A SparseTensor or a Tensor, representing the sum. Raises TypeError If both a and b are Tensors. Use tf.add() instead.
tensorflow.compat.v1.sparse_add
tf.compat.v1.sparse_concat Concatenates a list of SparseTensor along the specified dimension. (deprecated arguments) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.concat tf.compat.v1.sparse_concat( axis, sp_inputs, name=None, expand_nonconcat_dim=False, concat_dim=None, expand_nonconcat_dims=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (concat_dim). They will be removed in a future version. Instructions for updating: concat_dim is deprecated, use axis instead Concatenation is with respect to the dense versions of each sparse input. It is assumed that each inputs is a SparseTensor whose elements are ordered along increasing dimension number. If expand_nonconcat_dim is False, all inputs' shapes must match, except for the concat dimension. If expand_nonconcat_dim is True, then inputs' shapes are allowed to vary among all inputs. The indices, values, and shapes lists must have the same length. If expand_nonconcat_dim is False, then the output shape is identical to the inputs', except along the concat dimension, where it is the sum of the inputs' sizes along that dimension. If expand_nonconcat_dim is True, then the output shape along the non-concat dimensions will be expand to be the largest among all inputs, and it is the sum of the inputs sizes along the concat dimension. The output elements will be resorted to preserve the sort order along increasing dimension number. This op runs in O(M log M) time, where M is the total number of non-empty values across all inputs. This is due to the need for an internal sort in order to concatenate efficiently across an arbitrary dimension. For example, if axis = 1 and the inputs are sp_inputs[0]: shape = [2, 3] [0, 2]: "a" [1, 0]: "b" [1, 1]: "c" sp_inputs[1]: shape = [2, 4] [0, 1]: "d" [0, 2]: "e" then the output will be shape = [2, 7] [0, 2]: "a" [0, 4]: "d" [0, 5]: "e" [1, 0]: "b" [1, 1]: "c" Graphically this is equivalent to doing [ a] concat [ d e ] = [ a d e ] [b c ] [ ] [b c ] Another example, if 'axis = 1' and the inputs are sp_inputs[0]: shape = [3, 3] [0, 2]: "a" [1, 0]: "b" [2, 1]: "c" sp_inputs[1]: shape = [2, 4] [0, 1]: "d" [0, 2]: "e" if expand_nonconcat_dim = False, this will result in an error. But if expand_nonconcat_dim = True, this will result in: shape = [3, 7] [0, 2]: "a" [0, 4]: "d" [0, 5]: "e" [1, 0]: "b" [2, 1]: "c" Graphically this is equivalent to doing [ a] concat [ d e ] = [ a d e ] [b ] [ ] [b ] [ c ] [ c ] Args axis Dimension to concatenate along. Must be in range [-rank, rank), where rank is the number of dimensions in each input SparseTensor. sp_inputs List of SparseTensor to concatenate. name A name prefix for the returned tensors (optional). expand_nonconcat_dim Whether to allow the expansion in the non-concat dimensions. Defaulted to False. concat_dim The old (deprecated) name for axis. expand_nonconcat_dims alias for expand_nonconcat_dim Returns A SparseTensor with the concatenated output. Raises TypeError If sp_inputs is not a list of SparseTensor.
tensorflow.compat.v1.sparse_concat
tf.compat.v1.sparse_matmul Multiply matrix "a" by matrix "b". tf.compat.v1.sparse_matmul( a, b, transpose_a=False, transpose_b=False, a_is_sparse=False, b_is_sparse=False, name=None ) The inputs must be two-dimensional matrices and the inner dimension of "a" must match the outer dimension of "b". Both "a" and "b" must be Tensors not SparseTensors. This op is optimized for the case where at least one of "a" or "b" is sparse, in the sense that they have a large proportion of zero values. The breakeven for using this versus a dense matrix multiply on one platform was 30% zero values in the sparse matrix. The gradient computation of this operation will only take advantage of sparsity in the input gradient when that gradient comes from a Relu. Args a A Tensor. Must be one of the following types: float32, bfloat16. b A Tensor. Must be one of the following types: float32, bfloat16. transpose_a An optional bool. Defaults to False. transpose_b An optional bool. Defaults to False. a_is_sparse An optional bool. Defaults to False. b_is_sparse An optional bool. Defaults to False. name A name for the operation (optional). Returns A Tensor of type float32.
tensorflow.compat.v1.sparse_matmul
tf.compat.v1.sparse_merge Combines a batch of feature ids and values into a single SparseTensor. (deprecated) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.merge tf.compat.v1.sparse_merge( sp_ids, sp_values, vocab_size, name=None, already_sorted=False ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: No similar op available at this time. The most common use case for this function occurs when feature ids and their corresponding values are stored in Example protos on disk. parse_example will return a batch of ids and a batch of values, and this function joins them into a single logical SparseTensor for use in functions such as sparse_tensor_dense_matmul, sparse_to_dense, etc. The SparseTensor returned by this function has the following properties: indices is equivalent to sp_ids.indices with the last dimension discarded and replaced with sp_ids.values. values is simply sp_values.values. If sp_ids.dense_shape = [D0, D1, ..., Dn, K], then output.shape = [D0, D1, ..., Dn, vocab_size]. For example, consider the following feature vectors: vector1 = [-3, 0, 0, 0, 0, 0] vector2 = [ 0, 1, 0, 4, 1, 0] vector3 = [ 5, 0, 0, 9, 0, 0] These might be stored sparsely in the following Example protos by storing only the feature ids (column number if the vectors are treated as a matrix) of the non-zero elements and the corresponding values: examples = [Example(features={ "ids": Feature(int64_list=Int64List(value=[0])), "values": Feature(float_list=FloatList(value=[-3]))}), Example(features={ "ids": Feature(int64_list=Int64List(value=[1, 4, 3])), "values": Feature(float_list=FloatList(value=[1, 1, 4]))}), Example(features={ "ids": Feature(int64_list=Int64List(value=[0, 3])), "values": Feature(float_list=FloatList(value=[5, 9]))})] The result of calling parse_example on these examples will produce a dictionary with entries for "ids" and "values". Passing those two objects to this function along with vocab_size=6, will produce a SparseTensor that sparsely represents all three instances. Namely, the indices property will contain the coordinates of the non-zero entries in the feature matrix (the first dimension is the row number in the matrix, i.e., the index within the batch, and the second dimension is the column number, i.e., the feature id); values will contain the actual values. shape will be the shape of the original matrix, i.e., (3, 6). For our example above, the output will be equal to: SparseTensor(indices=[[0, 0], [1, 1], [1, 3], [1, 4], [2, 0], [2, 3]], values=[-3, 1, 4, 1, 5, 9], dense_shape=[3, 6]) This method generalizes to higher-dimensions by simply providing a list for both the sp_ids as well as the vocab_size. In this case the resulting SparseTensor has the following properties: indices is equivalent to sp_ids[0].indices with the last dimension discarded and concatenated with sp_ids[0].values, sp_ids[1].values, .... values is simply sp_values.values. If sp_ids.dense_shape = [D0, D1, ..., Dn, K], then output.shape = [D0, D1, ..., Dn] + vocab_size. Args sp_ids A single SparseTensor with values property of type int32 or int64 or a Python list of such SparseTensors or a list thereof. sp_values A SparseTensor of any type. vocab_size A scalar int64 Tensor (or Python int) containing the new size of the last dimension, all(0 <= sp_ids.values < vocab_size). Or a list thereof with all(0 <= sp_ids[i].values < vocab_size[i]) for all i. name A name prefix for the returned tensors (optional) already_sorted A boolean to specify whether the per-batch values in sp_values are already sorted. If so skip sorting, False by default (optional). Returns A SparseTensor compactly representing a batch of feature ids and values, useful for passing to functions that expect such a SparseTensor. Raises TypeError If sp_values is not a SparseTensor. Or if sp_ids is neither a SparseTensor nor a list thereof. Or if vocab_size is not a Tensor or a Python int and sp_ids is a SparseTensor. Or if vocab_size is not a or list thereof and sp_ids is a list. ValueError If sp_ids and vocab_size are lists of different lengths.
tensorflow.compat.v1.sparse_merge
tf.compat.v1.sparse_placeholder Inserts a placeholder for a sparse tensor that will be always fed. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.placeholder tf.compat.v1.sparse_placeholder( dtype, shape=None, name=None ) Key Point: This sparse tensor will produce an error if evaluated. Its value must be fed using the feed_dict optional argument to Session.run(), Tensor.eval(), or Operation.run(). For example: x = tf.compat.v1.sparse.placeholder(tf.float32) y = tf.sparse.reduce_sum(x) with tf.compat.v1.Session() as sess: print(sess.run(y)) # ERROR: will fail because x was not fed. indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64) values = np.array([1.0, 2.0], dtype=np.float32) shape = np.array([7, 9, 2], dtype=np.int64) print(sess.run(y, feed_dict={ x: tf.compat.v1.SparseTensorValue(indices, values, shape)})) # Will succeed. print(sess.run(y, feed_dict={ x: (indices, values, shape)})) # Will succeed. sp = tf.sparse.SparseTensor(indices=indices, values=values, dense_shape=shape) sp_value = sp.eval(session=sess) print(sess.run(y, feed_dict={x: sp_value})) # Will succeed. @compatibility{eager} Placeholders are not compatible with eager execution. Args dtype The type of values elements in the tensor to be fed. shape The shape of the tensor to be fed (optional). If the shape is not specified, you can feed a sparse tensor of any shape. name A name for prefixing the operations (optional). Returns A SparseTensor that may be used as a handle for feeding a value, but not evaluated directly. Raises RuntimeError if eager execution is enabled
tensorflow.compat.v1.sparse_placeholder
tf.compat.v1.sparse_reduce_max Computes the max of elements across dimensions of a SparseTensor. (deprecated arguments) (deprecated arguments) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.reduce_max tf.compat.v1.sparse_reduce_max( sp_input, axis=None, keepdims=None, reduction_axes=None, keep_dims=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims insteadWarning: SOME ARGUMENTS ARE DEPRECATED: (reduction_axes). They will be removed in a future version. Instructions for updating: reduction_axes is deprecated, use axis instead This Op takes a SparseTensor and is the sparse counterpart to tf.reduce_max(). In particular, this Op also returns a dense Tensor instead of a sparse one. Note: A gradient is not defined for this function, so it can't be used in training models that need gradient descent. Reduces sp_input along the dimensions given in reduction_axes. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in reduction_axes. If keepdims is true, the reduced dimensions are retained with length 1. If reduction_axes has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, similar to the indexing rules in Python. The values not defined in sp_input don't participate in the reduce max, as opposed to be implicitly assumed 0 -- hence it can return negative values for sparse reduction_axes. But, in case there are no values in reduction_axes, it will reduce to 0. See second example below. For example: # 'x' represents [[1, ?, 2] # [?, 3, ?]] # where ? is implicitly-zero. tf.sparse.reduce_max(x) ==> 3 tf.sparse.reduce_max(x, 0) ==> [1, 3, 2] tf.sparse.reduce_max(x, 1) ==> [2, 3] # Can also use -1 as the axis. tf.sparse.reduce_max(x, 1, keepdims=True) ==> [[2], [3]] tf.sparse.reduce_max(x, [0, 1]) ==> 3 # 'y' represents [[-7, ?] # [ 4, 3] # [ ?, ?] tf.sparse.reduce_max(x, 1) ==> [-7, 4, 0] Args sp_input The SparseTensor to reduce. Should have numeric type. axis The dimensions to reduce; list or scalar. If None (the default), reduces all dimensions. keepdims If true, retain reduced dimensions with length 1. reduction_axes Deprecated name of axis. keep_dims Deprecated alias for keepdims. Returns The reduced Tensor.
tensorflow.compat.v1.sparse_reduce_max
tf.compat.v1.sparse_reduce_max_sparse Computes the max of elements across dimensions of a SparseTensor. (deprecated arguments) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.reduce_max_sparse tf.compat.v1.sparse_reduce_max_sparse( sp_input, axis=None, keepdims=None, reduction_axes=None, keep_dims=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims instead This Op takes a SparseTensor and is the sparse counterpart to tf.reduce_max(). In contrast to SparseReduceSum, this Op returns a SparseTensor. Note: A gradient is not defined for this function, so it can't be used in training models that need gradient descent. Reduces sp_input along the dimensions given in reduction_axes. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in reduction_axes. If keepdims is true, the reduced dimensions are retained with length 1. If reduction_axes has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, which are interpreted according to the indexing rules in Python. Args sp_input The SparseTensor to reduce. Should have numeric type. axis The dimensions to reduce; list or scalar. If None (the default), reduces all dimensions. keepdims If true, retain reduced dimensions with length 1. reduction_axes Deprecated name of axis. keep_dims Deprecated alias for keepdims. Returns The reduced SparseTensor.
tensorflow.compat.v1.sparse_reduce_max_sparse
tf.compat.v1.sparse_reduce_sum Computes the sum of elements across dimensions of a SparseTensor. (deprecated arguments) (deprecated arguments) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.reduce_sum tf.compat.v1.sparse_reduce_sum( sp_input, axis=None, keepdims=None, reduction_axes=None, keep_dims=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims insteadWarning: SOME ARGUMENTS ARE DEPRECATED: (reduction_axes). They will be removed in a future version. Instructions for updating: reduction_axes is deprecated, use axis instead This Op takes a SparseTensor and is the sparse counterpart to tf.reduce_sum(). In particular, this Op also returns a dense Tensor instead of a sparse one. Reduces sp_input along the dimensions given in reduction_axes. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in reduction_axes. If keepdims is true, the reduced dimensions are retained with length 1. If reduction_axes has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, similar to the indexing rules in Python. For example: # 'x' represents [[1, ?, 1] # [?, 1, ?]] # where ? is implicitly-zero. tf.sparse.reduce_sum(x) ==> 3 tf.sparse.reduce_sum(x, 0) ==> [1, 1, 1] tf.sparse.reduce_sum(x, 1) ==> [2, 1] # Can also use -1 as the axis. tf.sparse.reduce_sum(x, 1, keepdims=True) ==> [[2], [1]] tf.sparse.reduce_sum(x, [0, 1]) ==> 3 Args sp_input The SparseTensor to reduce. Should have numeric type. axis The dimensions to reduce; list or scalar. If None (the default), reduces all dimensions. keepdims If true, retain reduced dimensions with length 1. reduction_axes Deprecated name of axis. keep_dims Deprecated alias for keepdims. Returns The reduced Tensor.
tensorflow.compat.v1.sparse_reduce_sum
tf.compat.v1.sparse_reduce_sum_sparse Computes the sum of elements across dimensions of a SparseTensor. (deprecated arguments) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.reduce_sum_sparse tf.compat.v1.sparse_reduce_sum_sparse( sp_input, axis=None, keepdims=None, reduction_axes=None, keep_dims=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (keep_dims). They will be removed in a future version. Instructions for updating: keep_dims is deprecated, use keepdims instead This Op takes a SparseTensor and is the sparse counterpart to tf.reduce_sum(). In contrast to SparseReduceSum, this Op returns a SparseTensor. Note: A gradient is not defined for this function, so it can't be used in training models that need gradient descent. Reduces sp_input along the dimensions given in reduction_axes. Unless keepdims is true, the rank of the tensor is reduced by 1 for each entry in reduction_axes. If keepdims is true, the reduced dimensions are retained with length 1. If reduction_axes has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, which are interpreted according to the indexing rules in Python. Args sp_input The SparseTensor to reduce. Should have numeric type. axis The dimensions to reduce; list or scalar. If None (the default), reduces all dimensions. keepdims If true, retain reduced dimensions with length 1. reduction_axes Deprecated name of axis. keep_dims Deprecated alias for keepdims. Returns The reduced SparseTensor.
tensorflow.compat.v1.sparse_reduce_sum_sparse
tf.compat.v1.sparse_segment_mean Computes the mean along sparse segments of a tensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.segment_mean tf.compat.v1.sparse_segment_mean( data, indices, segment_ids, name=None, num_segments=None ) Read the section on segmentation for an explanation of segments. Like tf.math.segment_mean, but segment_ids can have rank less than data's first dimension, selecting a subset of dimension 0, specified by indices. segment_ids is allowed to have missing ids, in which case the output will be zeros at those indices. In those cases num_segments is used to determine the size of the output. Args data A Tensor with data that will be assembled in the output. indices A 1-D Tensor with indices into data. Has same rank as segment_ids. segment_ids A 1-D Tensor with indices into the output Tensor. Values should be sorted and can be repeated. name A name for the operation (optional). num_segments An optional int32 scalar. Indicates the size of the output Tensor. Returns A tensor of the shape as data, except for dimension 0 which has size k, the number of segments specified via num_segments or inferred for the last element in segments_ids.
tensorflow.compat.v1.sparse_segment_mean
tf.compat.v1.sparse_segment_sqrt_n Computes the sum along sparse segments of a tensor divided by the sqrt(N). View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.segment_sqrt_n tf.compat.v1.sparse_segment_sqrt_n( data, indices, segment_ids, name=None, num_segments=None ) N is the size of the segment being reduced. Args data A Tensor with data that will be assembled in the output. indices A 1-D Tensor with indices into data. Has same rank as segment_ids. segment_ids A 1-D Tensor with indices into the output Tensor. Values should be sorted and can be repeated. name A name for the operation (optional). num_segments An optional int32 scalar. Indicates the size of the output Tensor. Returns A tensor of the shape as data, except for dimension 0 which has size k, the number of segments specified via num_segments or inferred for the last element in segments_ids.
tensorflow.compat.v1.sparse_segment_sqrt_n
tf.compat.v1.sparse_segment_sum Computes the sum along sparse segments of a tensor. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.segment_sum tf.compat.v1.sparse_segment_sum( data, indices, segment_ids, name=None, num_segments=None ) Read the section on segmentation for an explanation of segments. Like tf.math.segment_sum, but segment_ids can have rank less than data's first dimension, selecting a subset of dimension 0, specified by indices. segment_ids is allowed to have missing ids, in which case the output will be zeros at those indices. In those cases num_segments is used to determine the size of the output. For example: c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) # Select two rows, one segment. tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 0])) # => [[0 0 0 0]] # Select two rows, two segment. tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 1])) # => [[ 1 2 3 4] # [-1 -2 -3 -4]] # With missing segment ids. tf.sparse.segment_sum(c, tf.constant([0, 1]), tf.constant([0, 2]), num_segments=4) # => [[ 1 2 3 4] # [ 0 0 0 0] # [-1 -2 -3 -4] # [ 0 0 0 0]] # Select all rows, two segments. tf.sparse.segment_sum(c, tf.constant([0, 1, 2]), tf.constant([0, 0, 1])) # => [[0 0 0 0] # [5 6 7 8]] # Which is equivalent to: tf.math.segment_sum(c, tf.constant([0, 0, 1])) Args data A Tensor with data that will be assembled in the output. indices A 1-D Tensor with indices into data. Has same rank as segment_ids. segment_ids A 1-D Tensor with indices into the output Tensor. Values should be sorted and can be repeated. name A name for the operation (optional). num_segments An optional int32 scalar. Indicates the size of the output Tensor. Returns A tensor of the shape as data, except for dimension 0 which has size k, the number of segments specified via num_segments or inferred for the last element in segments_ids.
tensorflow.compat.v1.sparse_segment_sum
tf.compat.v1.sparse_split Split a SparseTensor into num_split tensors along axis. (deprecated arguments) View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.sparse.split tf.compat.v1.sparse_split( keyword_required=KeywordRequired(), sp_input=None, num_split=None, axis=None, name=None, split_dim=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (split_dim). They will be removed in a future version. Instructions for updating: split_dim is deprecated, use axis instead If the sp_input.dense_shape[axis] is not an integer multiple of num_split each slice starting from 0:shape[axis] % num_split gets extra one dimension. For example, if axis = 1 and num_split = 2 and the input is: input_tensor = shape = [2, 7] [ a d e ] [b c ] Graphically the output tensors are: output_tensor[0] = [ a ] [b c ] output_tensor[1] = [ d e ] [ ] Args keyword_required Python 2 standin for * (temporary for argument reorder) sp_input The SparseTensor to split. num_split A Python integer. The number of ways to split. axis A 0-D int32 Tensor. The dimension along which to split. Must be in range [-rank, rank), where rank is the number of dimensions in the input SparseTensor. name A name for the operation (optional). split_dim Deprecated old name for axis. Returns num_split SparseTensor objects resulting from splitting value. Raises TypeError If sp_input is not a SparseTensor. ValueError If the deprecated split_dim and axis are both non None.
tensorflow.compat.v1.sparse_split
tf.compat.v1.sparse_to_dense Converts a sparse representation into a dense tensor. (deprecated) tf.compat.v1.sparse_to_dense( sparse_indices, output_shape, sparse_values, default_value=0, validate_indices=True, name=None ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Create a tf.sparse.SparseTensor and use tf.sparse.to_dense instead. Builds an array dense with shape output_shape such that # If sparse_indices is scalar dense[i] = (i == sparse_indices ? sparse_values : default_value) # If sparse_indices is a vector, then for each i dense[sparse_indices[i]] = sparse_values[i] # If sparse_indices is an n by d matrix, then for each i in [0, n) dense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i] All other values in dense are set to default_value. If sparse_values is a scalar, all sparse indices are set to this single value. Indices should be sorted in lexicographic order, and indices must not contain any repeats. If validate_indices is True, these properties are checked during execution. Args sparse_indices A 0-D, 1-D, or 2-D Tensor of type int32 or int64. sparse_indices[i] contains the complete index where sparse_values[i] will be placed. output_shape A 1-D Tensor of the same type as sparse_indices. Shape of the dense output tensor. sparse_values A 0-D or 1-D Tensor. Values corresponding to each row of sparse_indices, or a scalar value to be used for all sparse indices. default_value A 0-D Tensor of the same type as sparse_values. Value to set for indices not specified in sparse_indices. Defaults to zero. validate_indices A boolean value. If True, indices are checked to make sure they are sorted in lexicographic order and that there are no repeats. name A name for the operation (optional). Returns Dense Tensor of shape output_shape. Has the same type as sparse_values.
tensorflow.compat.v1.sparse_to_dense
Module: tf.compat.v1.spectral Public API for tf.spectral namespace. Functions dct(...): Computes the 1D [Discrete Cosine Transform (DCT)][dct] of input. fft(...): Fast Fourier transform. fft2d(...): 2D fast Fourier transform. fft3d(...): 3D fast Fourier transform. idct(...): Computes the 1D [Inverse Discrete Cosine Transform (DCT)][idct] of input. ifft(...): Inverse fast Fourier transform. ifft2d(...): Inverse 2D fast Fourier transform. ifft3d(...): Inverse 3D fast Fourier transform. irfft(...): Inverse real-valued fast Fourier transform. irfft2d(...): Inverse 2D real-valued fast Fourier transform. irfft3d(...): Inverse 3D real-valued fast Fourier transform. rfft(...): Real-valued fast Fourier transform. rfft2d(...): 2D real-valued fast Fourier transform. rfft3d(...): 3D real-valued fast Fourier transform.
tensorflow.compat.v1.spectral
tf.compat.v1.squeeze Removes dimensions of size 1 from the shape of a tensor. (deprecated arguments) tf.compat.v1.squeeze( input, axis=None, name=None, squeeze_dims=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (squeeze_dims). They will be removed in a future version. Instructions for updating: Use the axis argument instead Given a tensor input, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don't want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying axis. For example: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] t = tf.ones([1, 2, 1, 3, 1, 1]) print(tf.shape(tf.squeeze(t)).numpy()) [2 3] Or, to remove specific size 1 dimensions: # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] t = tf.ones([1, 2, 1, 3, 1, 1]) print(tf.shape(tf.squeeze(t, [2, 4])).numpy()) [1 2 3 1] Note: if input is a tf.RaggedTensor, then this operation takes O(N) time, where N is the number of elements in the squeezed dimensions. Args input A Tensor. The input to squeeze. axis An optional list of ints. Defaults to []. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1. Must be in the range [-rank(input), rank(input)). Must be specified if input is a RaggedTensor. name A name for the operation (optional). squeeze_dims Deprecated keyword argument that is now axis. Returns A Tensor. Has the same type as input. Contains the same data as input, but has one or more dimensions of size 1 removed. Raises ValueError When both squeeze_dims and axis are specified.
tensorflow.compat.v1.squeeze
Module: tf.compat.v1.strings Operations for working with string Tensors. Functions as_string(...): Converts each entry in the given tensor to strings. bytes_split(...): Split string elements of input into bytes. format(...): Formats a string template using a list of tensors. join(...): Perform element-wise concatenation of a list of string tensors. length(...): Computes the length of each string given in the input tensor. lower(...): Converts all uppercase characters into their respective lowercase replacements. ngrams(...): Create a tensor of n-grams based on data. reduce_join(...): Joins all strings into a single string, or joins along an axis. regex_full_match(...): Check if the input matches the regex pattern. regex_replace(...): Replace elements of input matching regex pattern with rewrite. split(...): Split elements of input based on sep. strip(...): Strip leading and trailing whitespaces from the Tensor. substr(...): Return substrings from Tensor of strings. to_hash_bucket(...): Converts each string in the input Tensor to its hash mod by a number of buckets. to_hash_bucket_fast(...): Converts each string in the input Tensor to its hash mod by a number of buckets. to_hash_bucket_strong(...): Converts each string in the input Tensor to its hash mod by a number of buckets. to_number(...): Converts each string in the input Tensor to the specified numeric type. unicode_decode(...): Decodes each string in input into a sequence of Unicode code points. unicode_decode_with_offsets(...): Decodes each string into a sequence of code points with start offsets. unicode_encode(...): Encodes each sequence of Unicode code points in input into a string. unicode_script(...): Determine the script codes of a given tensor of Unicode integer code points. unicode_split(...): Splits each string in input into a sequence of Unicode code points. unicode_split_with_offsets(...): Splits each string into a sequence of code points with start offsets. unicode_transcode(...): Transcode the input text from a source encoding to a destination encoding. unsorted_segment_join(...): Joins the elements of inputs based on segment_ids. upper(...): Converts all lowercase characters into their respective uppercase replacements.
tensorflow.compat.v1.strings
tf.compat.v1.strings.length Computes the length of each string given in the input tensor. tf.compat.v1.strings.length( input, name=None, unit='BYTE' ) strings = tf.constant(['Hello','TensorFlow', '🙂']) tf.strings.length(strings).numpy() # default counts bytes array([ 5, 10, 4], dtype=int32) tf.strings.length(strings, unit="UTF8_CHAR").numpy() array([ 5, 10, 1], dtype=int32) Args input A Tensor of type string. The strings for which to compute the length for each element. name A name for the operation (optional). unit An optional string from: "BYTE", "UTF8_CHAR". Defaults to "BYTE". The unit that is counted to compute string length. One of: "BYTE" (for the number of bytes in each string) or "UTF8_CHAR" (for the number of UTF-8 encoded Unicode code points in each string). Results are undefined if unit=UTF8_CHAR and the input strings do not contain structurally valid UTF-8. Returns A Tensor of type int32, containing the length of the input string in the same element of the input tensor.
tensorflow.compat.v1.strings.length
tf.compat.v1.strings.split Split elements of input based on sep. tf.compat.v1.strings.split( input=None, sep=None, maxsplit=-1, result_type='SparseTensor', source=None, name=None ) Let N be the size of input (typically N will be the batch size). Split each element of input based on sep and return a SparseTensor or RaggedTensor containing the split tokens. Empty tokens are ignored. Examples: print(tf.compat.v1.strings.split(['hello world', 'a b c'])) SparseTensor(indices=tf.Tensor( [[0 0] [0 1] [1 0] [1 1] [1 2]], ...), values=tf.Tensor([b'hello' b'world' b'a' b'b' b'c'], ...), dense_shape=tf.Tensor([2 3], shape=(2,), dtype=int64)) print(tf.compat.v1.strings.split(['hello world', 'a b c'], result_type="RaggedTensor")) <tf.RaggedTensor [[b'hello', b'world'], [b'a', b'b', b'c']]> If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings. For example, input of "1<>2<><>3" and sep of "<>" returns ["1", "2", "", "3"]. If sep is None or an empty string, consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Note that the above mentioned behavior matches python's str.split. Args input A string Tensor of rank N, the strings to split. If rank(input) is not known statically, then it is assumed to be 1. sep 0-D string Tensor, the delimiter character. maxsplit An int. If maxsplit > 0, limit of the split of the result. result_type The tensor type for the result: one of "RaggedTensor" or "SparseTensor". source alias for "input" argument. name A name for the operation (optional). Raises ValueError If sep is not a string. Returns A SparseTensor or RaggedTensor of rank N+1, the strings split according to the delimiter.
tensorflow.compat.v1.strings.split
tf.compat.v1.strings.substr Return substrings from Tensor of strings. tf.compat.v1.strings.substr( input, pos, len, name=None, unit='BYTE' ) For each string in the input Tensor, creates a substring starting at index pos with a total length of len. If len defines a substring that would extend beyond the length of the input string, or if len is negative, then as many characters as possible are used. A negative pos indicates distance within the string backwards from the end. If pos specifies an index which is out of range for any of the input strings, then an InvalidArgumentError is thrown. pos and len must have the same shape, otherwise a ValueError is thrown on Op creation. Note: Substr supports broadcasting up to two dimensions. More about broadcasting here Examples Using scalar pos and len: input = [b'Hello', b'World'] position = 1 length = 3 output = [b'ell', b'orl'] Using pos and len with same shape as input: input = [[b'ten', b'eleven', b'twelve'], [b'thirteen', b'fourteen', b'fifteen'], [b'sixteen', b'seventeen', b'eighteen']] position = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] length = [[2, 3, 4], [4, 3, 2], [5, 5, 5]] output = [[b'en', b'eve', b'lve'], [b'hirt', b'urt', b'te'], [b'ixtee', b'vente', b'hteen']] Broadcasting pos and len onto input: input = [[b'ten', b'eleven', b'twelve'], [b'thirteen', b'fourteen', b'fifteen'], [b'sixteen', b'seventeen', b'eighteen'], [b'nineteen', b'twenty', b'twentyone']] position = [1, 2, 3] length = [1, 2, 3] output = [[b'e', b'ev', b'lve'], [b'h', b'ur', b'tee'], [b'i', b've', b'hte'], [b'i', b'en', b'nty']] Broadcasting input onto pos and len: input = b'thirteen' position = [1, 5, 7] length = [3, 2, 1] output = [b'hir', b'ee', b'n'] Raises ValueError: If the first argument cannot be converted to a Tensor of dtype string. InvalidArgumentError: If indices are out of range. ValueError: If pos and len are not the same shape. Args input A Tensor of type string. Tensor of strings pos A Tensor. Must be one of the following types: int32, int64. Scalar defining the position of first character in each substring len A Tensor. Must have the same type as pos. Scalar defining the number of characters to include in each substring unit An optional string from: "BYTE", "UTF8_CHAR". Defaults to "BYTE". The unit that is used to create the substring. One of: "BYTE" (for defining position and length by bytes) or "UTF8_CHAR" (for the UTF-8 encoded Unicode code points). The default is "BYTE". Results are undefined if unit=UTF8_CHAR and the input strings do not contain structurally valid UTF-8. name A name for the operation (optional). Returns A Tensor of type string.
tensorflow.compat.v1.strings.substr
tf.compat.v1.string_split Split elements of source based on delimiter. (deprecated arguments) tf.compat.v1.string_split( source, sep=None, skip_empty=True, delimiter=None, result_type='SparseTensor', name=None ) Warning: SOME ARGUMENTS ARE DEPRECATED: (delimiter). They will be removed in a future version. Instructions for updating: delimiter is deprecated, please use sep instead. Let N be the size of source (typically N will be the batch size). Split each element of source based on delimiter and return a SparseTensor or RaggedTensor containing the split tokens. Empty tokens are ignored. If sep is an empty string, each element of the source is split into individual strings, each containing one byte. (This includes splitting multibyte sequences of UTF-8.) If delimiter contains multiple bytes, it is treated as a set of delimiters with each considered a potential split point. Examples: print(tf.compat.v1.string_split(['hello world', 'a b c'])) SparseTensor(indices=tf.Tensor( [[0 0] [0 1] [1 0] [1 1] [1 2]], ...), values=tf.Tensor([b'hello' b'world' b'a' b'b' b'c'], ...), dense_shape=tf.Tensor([2 3], shape=(2,), dtype=int64)) print(tf.compat.v1.string_split(['hello world', 'a b c'], result_type="RaggedTensor")) <tf.RaggedTensor [[b'hello', b'world'], [b'a', b'b', b'c']]> Args source 1-D string Tensor, the strings to split. sep 0-D string Tensor, the delimiter character, the string should be length 0 or 1. Default is ' '. skip_empty A bool. If True, skip the empty strings from the result. delimiter deprecated alias for sep. result_type The tensor type for the result: one of "RaggedTensor" or "SparseTensor". name A name for the operation (optional). Raises ValueError If delimiter is not a string. Returns A SparseTensor or RaggedTensor of rank 2, the strings split according to the delimiter. The first column of the indices corresponds to the row in source and the second column corresponds to the index of the split component in this row.
tensorflow.compat.v1.string_split
tf.compat.v1.string_to_hash_bucket Converts each string in the input Tensor to its hash mod by a number of buckets. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.strings.to_hash_bucket tf.compat.v1.string_to_hash_bucket( string_tensor=None, num_buckets=None, name=None, input=None ) The hash function is deterministic on the content of the string within the process. Note that the hash function may change from time to time. This functionality will be deprecated and it's recommended to use tf.string_to_hash_bucket_fast() or tf.string_to_hash_bucket_strong(). Args string_tensor A Tensor of type string. num_buckets An int that is >= 1. The number of buckets. name A name for the operation (optional). Returns A Tensor of type int64.
tensorflow.compat.v1.string_to_hash_bucket
tf.compat.v1.string_to_number Converts each string in the input Tensor to the specified numeric type. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.strings.to_number tf.compat.v1.string_to_number( string_tensor=None, out_type=tf.dtypes.float32, name=None, input=None ) (Note that int32 overflow results in an error while float overflow results in a rounded value.) Example: strings = ["5.0", "3.0", "7.0"] tf.strings.to_number(strings) <tf.Tensor: shape=(3,), dtype=float32, numpy=array([5., 3., 7.], dtype=float32)> Args string_tensor A Tensor of type string. out_type An optional tf.DType from: tf.float32, tf.float64, tf.int32, tf.int64. Defaults to tf.float32. The numeric type to interpret each string in string_tensor as. name A name for the operation (optional). Returns A Tensor of type out_type.
tensorflow.compat.v1.string_to_number
tf.compat.v1.substr Return substrings from Tensor of strings. tf.compat.v1.substr( input, pos, len, name=None, unit='BYTE' ) For each string in the input Tensor, creates a substring starting at index pos with a total length of len. If len defines a substring that would extend beyond the length of the input string, or if len is negative, then as many characters as possible are used. A negative pos indicates distance within the string backwards from the end. If pos specifies an index which is out of range for any of the input strings, then an InvalidArgumentError is thrown. pos and len must have the same shape, otherwise a ValueError is thrown on Op creation. Note: Substr supports broadcasting up to two dimensions. More about broadcasting here Examples Using scalar pos and len: input = [b'Hello', b'World'] position = 1 length = 3 output = [b'ell', b'orl'] Using pos and len with same shape as input: input = [[b'ten', b'eleven', b'twelve'], [b'thirteen', b'fourteen', b'fifteen'], [b'sixteen', b'seventeen', b'eighteen']] position = [[1, 2, 3], [1, 2, 3], [1, 2, 3]] length = [[2, 3, 4], [4, 3, 2], [5, 5, 5]] output = [[b'en', b'eve', b'lve'], [b'hirt', b'urt', b'te'], [b'ixtee', b'vente', b'hteen']] Broadcasting pos and len onto input: input = [[b'ten', b'eleven', b'twelve'], [b'thirteen', b'fourteen', b'fifteen'], [b'sixteen', b'seventeen', b'eighteen'], [b'nineteen', b'twenty', b'twentyone']] position = [1, 2, 3] length = [1, 2, 3] output = [[b'e', b'ev', b'lve'], [b'h', b'ur', b'tee'], [b'i', b've', b'hte'], [b'i', b'en', b'nty']] Broadcasting input onto pos and len: input = b'thirteen' position = [1, 5, 7] length = [3, 2, 1] output = [b'hir', b'ee', b'n'] Raises ValueError: If the first argument cannot be converted to a Tensor of dtype string. InvalidArgumentError: If indices are out of range. ValueError: If pos and len are not the same shape. Args input A Tensor of type string. Tensor of strings pos A Tensor. Must be one of the following types: int32, int64. Scalar defining the position of first character in each substring len A Tensor. Must have the same type as pos. Scalar defining the number of characters to include in each substring unit An optional string from: "BYTE", "UTF8_CHAR". Defaults to "BYTE". The unit that is used to create the substring. One of: "BYTE" (for defining position and length by bytes) or "UTF8_CHAR" (for the UTF-8 encoded Unicode code points). The default is "BYTE". Results are undefined if unit=UTF8_CHAR and the input strings do not contain structurally valid UTF-8. name A name for the operation (optional). Returns A Tensor of type string.
tensorflow.compat.v1.substr
Module: tf.compat.v1.summary Operations for writing summary data, for use in analysis and visualization. See the Summaries and TensorBoard guide. Classes class Event: A ProtocolMessage class FileWriter: Writes Summary protocol buffers to event files. class FileWriterCache: Cache for file writers. class SessionLog: A ProtocolMessage class Summary: A ProtocolMessage class SummaryDescription: A ProtocolMessage class TaggedRunMetadata: A ProtocolMessage Functions all_v2_summary_ops(...): Returns all V2-style summary ops defined in the current default graph. audio(...): Outputs a Summary protocol buffer with audio. get_summary_description(...): Given a TensorSummary node_def, retrieve its SummaryDescription. histogram(...): Outputs a Summary protocol buffer with a histogram. image(...): Outputs a Summary protocol buffer with images. initialize(...): Initializes summary writing for graph execution mode. merge(...): Merges summaries. merge_all(...): Merges all summaries collected in the default graph. scalar(...): Outputs a Summary protocol buffer containing a single scalar value. tensor_summary(...): Outputs a Summary protocol buffer with a serialized tensor.proto. text(...): Summarizes textual data.
tensorflow.compat.v1.summary
tf.compat.v1.summary.all_v2_summary_ops Returns all V2-style summary ops defined in the current default graph. tf.compat.v1.summary.all_v2_summary_ops() This includes ops from TF 2.0 tf.summary and TF 1.x tf.contrib.summary (except for tf.contrib.summary.graph and tf.contrib.summary.import_event), but does not include TF 1.x tf.summary ops. Returns List of summary ops, or None if called under eager execution.
tensorflow.compat.v1.summary.all_v2_summary_ops
tf.compat.v1.summary.audio Outputs a Summary protocol buffer with audio. tf.compat.v1.summary.audio( name, tensor, sample_rate, max_outputs=3, collections=None, family=None ) The summary has up to max_outputs summary values containing audio. The audio is built from tensor which must be 3-D with shape [batch_size, frames, channels] or 2-D with shape [batch_size, frames]. The values are assumed to be in the range of [-1.0, 1.0] with a sample rate of sample_rate. The tag in the outputted Summary.Value protobufs is generated based on the name, with a suffix depending on the max_outputs setting: If max_outputs is 1, the summary value tag is 'name/audio'. If max_outputs is greater than 1, the summary value tags are generated sequentially as 'name/audio/0', 'name/audio/1', etc Args name A name for the generated node. Will also serve as a series name in TensorBoard. tensor A 3-D float32 Tensor of shape [batch_size, frames, channels] or a 2-D float32 Tensor of shape [batch_size, frames]. sample_rate A Scalar float32 Tensor indicating the sample rate of the signal in hertz. max_outputs Max number of batch elements to generate audio for. collections Optional list of ops.GraphKeys. The collections to add the summary to. Defaults to [_ops.GraphKeys.SUMMARIES] family Optional; if provided, used as the prefix of the summary tag name, which controls the tab name used for display on Tensorboard. Returns A scalar Tensor of type string. The serialized Summary protocol buffer.
tensorflow.compat.v1.summary.audio
tf.compat.v1.summary.FileWriter Writes Summary protocol buffers to event files. tf.compat.v1.summary.FileWriter( logdir, graph=None, max_queue=10, flush_secs=120, graph_def=None, filename_suffix=None, session=None ) The FileWriter class provides a mechanism to create an event file in a given directory and add summaries and events to it. The class updates the file contents asynchronously. This allows a training program to call methods to add data to the file directly from the training loop, without slowing down training. When constructed with a tf.compat.v1.Session parameter, a FileWriter instead forms a compatibility layer over new graph-based summaries to facilitate the use of new summary writing with pre-existing code that expects a FileWriter instance. This class is not thread-safe. Args logdir A string. Directory where event file will be written. graph A Graph object, such as sess.graph. max_queue Integer. Size of the queue for pending events and summaries. flush_secs Number. How often, in seconds, to flush the pending events and summaries to disk. graph_def DEPRECATED: Use the graph argument instead. filename_suffix A string. Every event file's name is suffixed with suffix. session A tf.compat.v1.Session object. See details above. Raises RuntimeError If called with eager execution enabled. Methods add_event View source add_event( event ) Adds an event to the event file. Args event An Event protocol buffer. add_graph View source add_graph( graph, global_step=None, graph_def=None ) Adds a Graph to the event file. The graph described by the protocol buffer will be displayed by TensorBoard. Most users pass a graph in the constructor instead. Args graph A Graph object, such as sess.graph. global_step Number. Optional global step counter to record with the graph. graph_def DEPRECATED. Use the graph parameter instead. Raises ValueError If both graph and graph_def are passed to the method. add_meta_graph View source add_meta_graph( meta_graph_def, global_step=None ) Adds a MetaGraphDef to the event file. The MetaGraphDef allows running the given graph via saver.import_meta_graph(). Args meta_graph_def A MetaGraphDef object, often as returned by saver.export_meta_graph(). global_step Number. Optional global step counter to record with the graph. Raises TypeError If both meta_graph_def is not an instance of MetaGraphDef. add_run_metadata View source add_run_metadata( run_metadata, tag, global_step=None ) Adds a metadata information for a single session.run() call. Args run_metadata A RunMetadata protobuf object. tag The tag name for this metadata. global_step Number. Optional global step counter to record with the StepStats. Raises ValueError If the provided tag was already used for this type of event. add_session_log View source add_session_log( session_log, global_step=None ) Adds a SessionLog protocol buffer to the event file. This method wraps the provided session in an Event protocol buffer and adds it to the event file. Args session_log A SessionLog protocol buffer. global_step Number. Optional global step value to record with the summary. add_summary View source add_summary( summary, global_step=None ) Adds a Summary protocol buffer to the event file. This method wraps the provided summary in an Event protocol buffer and adds it to the event file. You can pass the result of evaluating any summary op, using tf.Session.run or tf.Tensor.eval, to this function. Alternatively, you can pass a tf.compat.v1.Summary protocol buffer that you populate with your own data. The latter is commonly done to report evaluation results in event files. Args summary A Summary protocol buffer, optionally serialized as a string. global_step Number. Optional global step value to record with the summary. close View source close() Flushes the event file to disk and close the file. Call this method when you do not need the summary writer anymore. flush View source flush() Flushes the event file to disk. Call this method to make sure that all pending events have been written to disk. get_logdir View source get_logdir() Returns the directory where event file will be written. reopen View source reopen() Reopens the EventFileWriter. Can be called after close() to add more events in the same directory. The events will go into a new events file. Does nothing if the EventFileWriter was not closed. __enter__ View source __enter__() Make usable with "with" statement. __exit__ View source __exit__( unused_type, unused_value, unused_traceback ) Make usable with "with" statement.
tensorflow.compat.v1.summary.filewriter
tf.compat.v1.summary.FileWriterCache Cache for file writers. This class caches file writers, one per directory. Methods clear View source @staticmethod clear() Clear cached summary writers. Currently only used for unit tests. get View source @staticmethod get( logdir ) Returns the FileWriter for the specified directory. Args logdir str, name of the directory. Returns A FileWriter.
tensorflow.compat.v1.summary.filewritercache
tf.compat.v1.summary.get_summary_description Given a TensorSummary node_def, retrieve its SummaryDescription. tf.compat.v1.summary.get_summary_description( node_def ) When a Summary op is instantiated, a SummaryDescription of associated metadata is stored in its NodeDef. This method retrieves the description. Args node_def the node_def_pb2.NodeDef of a TensorSummary op Returns a summary_pb2.SummaryDescription Raises ValueError if the node is not a summary op. Eager Compatibility Not compatible with eager execution. To write TensorBoard summaries under eager execution, use tf.contrib.summary instead.
tensorflow.compat.v1.summary.get_summary_description
tf.compat.v1.summary.histogram Outputs a Summary protocol buffer with a histogram. tf.compat.v1.summary.histogram( name, values, collections=None, family=None ) Adding a histogram summary makes it possible to visualize your data's distribution in TensorBoard. You can see a detailed explanation of the TensorBoard histogram dashboard here. The generated Summary has one summary value containing a histogram for values. This op reports an InvalidArgument error if any value is not finite. Args name A name for the generated node. Will also serve as a series name in TensorBoard. values A real numeric Tensor. Any shape. Values to use to build the histogram. collections Optional list of graph collections keys. The new summary op is added to these collections. Defaults to [GraphKeys.SUMMARIES]. family Optional; if provided, used as the prefix of the summary tag name, which controls the tab name used for display on Tensorboard. Returns A scalar Tensor of type string. The serialized Summary protocol buffer.
tensorflow.compat.v1.summary.histogram
tf.compat.v1.summary.image Outputs a Summary protocol buffer with images. tf.compat.v1.summary.image( name, tensor, max_outputs=3, collections=None, family=None ) The summary has up to max_outputs summary values containing images. The images are built from tensor which must be 4-D with shape [batch_size, height, width, channels] and where channels can be: 1: tensor is interpreted as Grayscale. 3: tensor is interpreted as RGB. 4: tensor is interpreted as RGBA. The images have the same number of channels as the input tensor. For float input, the values are normalized one image at a time to fit in the range [0, 255]. uint8 values are unchanged. The op uses two different normalization algorithms: If the input values are all positive, they are rescaled so the largest one is 255. If any input value is negative, the values are shifted so input value 0.0 is at 127. They are then rescaled so that either the smallest value is 0, or the largest one is 255. The tag in the outputted Summary.Value protobufs is generated based on the name, with a suffix depending on the max_outputs setting: If max_outputs is 1, the summary value tag is 'name/image'. If max_outputs is greater than 1, the summary value tags are generated sequentially as 'name/image/0', 'name/image/1', etc. Args name A name for the generated node. Will also serve as a series name in TensorBoard. tensor A 4-D uint8 or float32 Tensor of shape [batch_size, height, width, channels] where channels is 1, 3, or 4. max_outputs Max number of batch elements to generate images for. collections Optional list of ops.GraphKeys. The collections to add the summary to. Defaults to [_ops.GraphKeys.SUMMARIES] family Optional; if provided, used as the prefix of the summary tag name, which controls the tab name used for display on Tensorboard. Returns A scalar Tensor of type string. The serialized Summary protocol buffer.
tensorflow.compat.v1.summary.image
tf.compat.v1.summary.initialize Initializes summary writing for graph execution mode. tf.compat.v1.summary.initialize( graph=None, session=None ) This operation is a no-op when executing eagerly. This helper method provides a higher-level alternative to using tf.contrib.summary.summary_writer_initializer_op and tf.contrib.summary.graph. Most users will also want to call tf.compat.v1.train.create_global_step which can happen before or after this function is called. Args graph A tf.Graph or tf.compat.v1.GraphDef to output to the writer. This function will not write the default graph by default. When writing to an event log file, the associated step will be zero. session So this method can call tf.Session.run. This defaults to tf.compat.v1.get_default_session. Raises RuntimeError If the current thread has no default tf.contrib.summary.SummaryWriter. ValueError If session wasn't passed and no default session.
tensorflow.compat.v1.summary.initialize
tf.compat.v1.summary.merge Merges summaries. tf.compat.v1.summary.merge( inputs, collections=None, name=None ) This op creates a Summary protocol buffer that contains the union of all the values in the input summaries. When the Op is run, it reports an InvalidArgument error if multiple values in the summaries to merge use the same tag. Args inputs A list of string Tensor objects containing serialized Summary protocol buffers. collections Optional list of graph collections keys. The new summary op is added to these collections. Defaults to []. name A name for the operation (optional). Returns A scalar Tensor of type string. The serialized Summary protocol buffer resulting from the merging. Raises RuntimeError If called with eager mode enabled. Eager Compatibility Not compatible with eager execution. To write TensorBoard summaries under eager execution, use tf.contrib.summary instead.
tensorflow.compat.v1.summary.merge
tf.compat.v1.summary.merge_all Merges all summaries collected in the default graph. tf.compat.v1.summary.merge_all( key=tf.GraphKeys.SUMMARIES, scope=None, name=None ) Args key GraphKey used to collect the summaries. Defaults to GraphKeys.SUMMARIES. scope Optional scope used to filter the summary ops, using re.match Returns If no summaries were collected, returns None. Otherwise returns a scalar Tensor of type string containing the serialized Summary protocol buffer resulting from the merging. Raises RuntimeError If called with eager execution enabled. Eager Compatibility Not compatible with eager execution. To write TensorBoard summaries under eager execution, use tf.contrib.summary instead.
tensorflow.compat.v1.summary.merge_all
tf.compat.v1.summary.scalar Outputs a Summary protocol buffer containing a single scalar value. tf.compat.v1.summary.scalar( name, tensor, collections=None, family=None ) The generated Summary has a Tensor.proto containing the input Tensor. Args name A name for the generated node. Will also serve as the series name in TensorBoard. tensor A real numeric Tensor containing a single value. collections Optional list of graph collections keys. The new summary op is added to these collections. Defaults to [GraphKeys.SUMMARIES]. family Optional; if provided, used as the prefix of the summary tag name, which controls the tab name used for display on Tensorboard. Returns A scalar Tensor of type string. Which contains a Summary protobuf. Raises ValueError If tensor has the wrong shape or type.
tensorflow.compat.v1.summary.scalar
tf.compat.v1.summary.SummaryDescription A ProtocolMessage Attributes type_hint string type_hint
tensorflow.compat.v1.summary.summarydescription
tf.compat.v1.summary.TaggedRunMetadata A ProtocolMessage Attributes run_metadata bytes run_metadata tag string tag
tensorflow.compat.v1.summary.taggedrunmetadata
tf.compat.v1.summary.tensor_summary Outputs a Summary protocol buffer with a serialized tensor.proto. tf.compat.v1.summary.tensor_summary( name, tensor, summary_description=None, collections=None, summary_metadata=None, family=None, display_name=None ) Args name A name for the generated node. If display_name is not set, it will also serve as the tag name in TensorBoard. (In that case, the tag name will inherit tf name scopes.) tensor A tensor of any type and shape to serialize. summary_description A long description of the summary sequence. Markdown is supported. collections Optional list of graph collections keys. The new summary op is added to these collections. Defaults to [GraphKeys.SUMMARIES]. summary_metadata Optional SummaryMetadata proto (which describes which plugins may use the summary value). family Optional; if provided, used as the prefix of the summary tag, which controls the name used for display on TensorBoard when display_name is not set. display_name A string used to name this data in TensorBoard. If this is not set, then the node name will be used instead. Returns A scalar Tensor of type string. The serialized Summary protocol buffer.
tensorflow.compat.v1.summary.tensor_summary
tf.compat.v1.summary.text Summarizes textual data. tf.compat.v1.summary.text( name, tensor, collections=None ) Text data summarized via this plugin will be visible in the Text Dashboard in TensorBoard. The standard TensorBoard Text Dashboard will render markdown in the strings, and will automatically organize 1d and 2d tensors into tables. If a tensor with more than 2 dimensions is provided, a 2d subarray will be displayed along with a warning message. (Note that this behavior is not intrinsic to the text summary api, but rather to the default TensorBoard text plugin.) Args name A name for the generated node. Will also serve as a series name in TensorBoard. tensor a string-type Tensor to summarize. collections Optional list of ops.GraphKeys. The collections to add the summary to. Defaults to [_ops.GraphKeys.SUMMARIES] Returns A TensorSummary op that is configured so that TensorBoard will recognize that it contains textual data. The TensorSummary is a scalar Tensor of type string which contains Summary protobufs. Raises ValueError If tensor has the wrong type.
tensorflow.compat.v1.summary.text
tf.compat.v1.SummaryMetadata A ProtocolMessage Attributes data_class DataClass data_class display_name string display_name plugin_data PluginData plugin_data summary_description string summary_description Child Classes class PluginData
tensorflow.compat.v1.summarymetadata
tf.compat.v1.SummaryMetadata.PluginData A ProtocolMessage Attributes content bytes content plugin_name string plugin_name
tensorflow.compat.v1.summarymetadata.plugindata
Module: tf.compat.v1.sysconfig System configuration library. Functions get_build_info(...): Get a dictionary describing TensorFlow's build environment. get_compile_flags(...): Get the compilation flags for custom operators. get_include(...): Get the directory containing the TensorFlow C++ header files. get_lib(...): Get the directory containing the TensorFlow framework library. get_link_flags(...): Get the link flags for custom operators. Other Members CXX11_ABI_FLAG 0 MONOLITHIC_BUILD 0
tensorflow.compat.v1.sysconfig
tf.compat.v1.tables_initializer Returns an Op that initializes all tables of the default graph. View aliases Compat aliases for migration See Migration guide for more details. tf.compat.v1.initializers.tables_initializer tf.compat.v1.tables_initializer( name='init_all_tables' ) See the Low Level Intro guide, for an example of usage. Args name Optional name for the initialization op. Returns An Op that initializes all tables. Note that if there are not tables the returned Op is a NoOp.
tensorflow.compat.v1.tables_initializer
tf.compat.v1.TensorInfo A ProtocolMessage Attributes composite_tensor CompositeTensor composite_tensor coo_sparse CooSparse coo_sparse dtype DataType dtype name string name tensor_shape TensorShapeProto tensor_shape Child Classes class CompositeTensor class CooSparse
tensorflow.compat.v1.tensorinfo
tf.compat.v1.TensorInfo.CompositeTensor A ProtocolMessage Attributes components repeated TensorInfo components type_spec TypeSpecProto type_spec
tensorflow.compat.v1.tensorinfo.compositetensor
tf.compat.v1.TensorInfo.CooSparse A ProtocolMessage Attributes dense_shape_tensor_name string dense_shape_tensor_name indices_tensor_name string indices_tensor_name values_tensor_name string values_tensor_name
tensorflow.compat.v1.tensorinfo.coosparse
Module: tf.compat.v1.test Testing. Classes class Benchmark: Abstract class that provides helpers for TensorFlow benchmarks. class StubOutForTesting: Support class for stubbing methods out for unit testing. class TestCase: Base class for tests that need to test TensorFlow. Functions assert_equal_graph_def(...): Asserts that two GraphDefs are (mostly) the same. benchmark_config(...): Returns a tf.compat.v1.ConfigProto for disabling the dependency optimizer. compute_gradient(...): Computes and returns the theoretical and numerical Jacobian. (deprecated) compute_gradient_error(...): Computes the gradient error. (deprecated) create_local_cluster(...): Create and start local servers and return the associated Server objects. get_temp_dir(...): Returns a temporary directory for use during tests. gpu_device_name(...): Returns the name of a GPU device if available or the empty string. is_built_with_cuda(...): Returns whether TensorFlow was built with CUDA (GPU) support. is_built_with_gpu_support(...): Returns whether TensorFlow was built with GPU (i.e. CUDA or ROCm) support. is_built_with_rocm(...): Returns whether TensorFlow was built with ROCm (GPU) support. is_built_with_xla(...): Returns whether TensorFlow was built with XLA support. is_gpu_available(...): Returns whether TensorFlow can access a GPU. (deprecated) main(...): Runs all unit tests. test_src_dir_path(...): Creates an absolute test srcdir path given a relative path.
tensorflow.compat.v1.test
tf.compat.v1.test.assert_equal_graph_def Asserts that two GraphDefs are (mostly) the same. tf.compat.v1.test.assert_equal_graph_def( actual, expected, checkpoint_v2=False, hash_table_shared_name=False ) Compares two GraphDef protos for equality, ignoring versions and ordering of nodes, attrs, and control inputs. Node names are used to match up nodes between the graphs, so the naming of nodes must be consistent. Args actual The GraphDef we have. expected The GraphDef we expected. checkpoint_v2 boolean determining whether to ignore randomized attribute values that appear in V2 checkpoints. hash_table_shared_name boolean determining whether to ignore randomized shared_names that appear in HashTableV2 op defs. Raises AssertionError If the GraphDefs do not match. TypeError If either argument is not a GraphDef.
tensorflow.compat.v1.test.assert_equal_graph_def
tf.compat.v1.test.compute_gradient Computes and returns the theoretical and numerical Jacobian. (deprecated) tf.compat.v1.test.compute_gradient( x, x_shape, y, y_shape, x_init_value=None, delta=0.001, init_targets=None, extra_feed_dict=None ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.test.compute_gradient in 2.0, which has better support for functions. Note that the two versions have different usage, so code change is needed. If x or y is complex, the Jacobian will still be real but the corresponding Jacobian dimension(s) will be twice as large. This is required even if both input and output is complex since TensorFlow graphs are not necessarily holomorphic, and may have gradients not expressible as complex numbers. For example, if x is complex with shape [m] and y is complex with shape [n], each Jacobian J will have shape [m * 2, n * 2] with J[:m, :n] = d(Re y)/d(Re x) J[:m, n:] = d(Im y)/d(Re x) J[m:, :n] = d(Re y)/d(Im x) J[m:, n:] = d(Im y)/d(Im x) Args x a tensor or list of tensors x_shape the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes. y a tensor y_shape the dimensions of y as a tuple or an array of ints. x_init_value (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value. delta (optional) the amount of perturbation. init_targets list of targets to run to initialize model params. extra_feed_dict dict that allows fixing specified tensor values during the Jacobian calculation. Returns Two 2-d numpy arrays representing the theoretical and numerical Jacobian for dy/dx. Each has "x_size" rows and "y_size" columns where "x_size" is the number of elements in x and "y_size" is the number of elements in y. If x is a list, returns a list of two numpy arrays.
tensorflow.compat.v1.test.compute_gradient
tf.compat.v1.test.compute_gradient_error Computes the gradient error. (deprecated) tf.compat.v1.test.compute_gradient_error( x, x_shape, y, y_shape, x_init_value=None, delta=0.001, init_targets=None, extra_feed_dict=None ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.test.compute_gradient in 2.0, which has better support for functions. Note that the two versions have different usage, so code change is needed. Computes the maximum error for dy/dx between the computed Jacobian and the numerically estimated Jacobian. This function will modify the tensors passed in as it adds more operations and hence changing the consumers of the operations of the input tensors. This function adds operations to the current session. To compute the error using a particular device, such as a GPU, use the standard methods for setting a device (e.g. using with sess.graph.device() or setting a device function in the session constructor). Args x a tensor or list of tensors x_shape the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes. y a tensor y_shape the dimensions of y as a tuple or an array of ints. x_init_value (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value. delta (optional) the amount of perturbation. init_targets list of targets to run to initialize model params. extra_feed_dict dict that allows fixing specified tensor values during the Jacobian calculation. Returns The maximum error in between the two Jacobians.
tensorflow.compat.v1.test.compute_gradient_error
tf.compat.v1.test.get_temp_dir Returns a temporary directory for use during tests. tf.compat.v1.test.get_temp_dir() There is no need to delete the directory after the test. Returns The temporary directory.
tensorflow.compat.v1.test.get_temp_dir
tf.compat.v1.test.StubOutForTesting Support class for stubbing methods out for unit testing. tf.compat.v1.test.StubOutForTesting() Sample Usage: You want os.path.exists() to always return true during testing. stubs = StubOutForTesting() stubs.Set(os.path, 'exists', lambda x: 1) ... stubs.CleanUp() The above changes os.path.exists into a lambda that returns 1. Once the ... part of the code finishes, the CleanUp() looks up the old value of os.path.exists and restores it. Methods CleanUp View source CleanUp() Undoes all SmartSet() & Set() calls, restoring original definitions. Set View source Set( parent, child_name, new_child ) In parent, replace child_name's old definition with new_child. The parent could be a module when the child is a function at module scope. Or the parent could be a class when a class' method is being replaced. The named child is set to new_child, while the prior definition is saved away for later, when UnsetAll() is called. This method supports the case where child_name is a staticmethod or a classmethod of parent. Args parent The context in which the attribute child_name is to be changed. child_name The name of the attribute to change. new_child The new value of the attribute. SmartSet View source SmartSet( obj, attr_name, new_attr ) Replace obj.attr_name with new_attr. This method is smart and works at the module, class, and instance level while preserving proper inheritance. It will not stub out C types however unless that has been explicitly allowed by the type. This method supports the case where attr_name is a staticmethod or a classmethod of obj. Notes: If obj is an instance, then it is its class that will actually be stubbed. Note that the method Set() does not do that: if obj is an instance, it (and not its class) will be stubbed. The stubbing is using the builtin getattr and setattr. So, the get and set will be called when stubbing ( probably be to manipulate obj.dict instead of getattr() and setattr()). Args obj The object whose attributes we want to modify. attr_name The name of the attribute to modify. new_attr The new value for the attribute. Raises AttributeError If the attribute cannot be found. SmartUnsetAll View source SmartUnsetAll() Reverses SmartSet() calls, restoring things to original definitions. This method is automatically called when the StubOutForTesting() object is deleted; there is no need to call it explicitly. It is okay to call SmartUnsetAll() repeatedly, as later calls have no effect if no SmartSet() calls have been made. UnsetAll View source UnsetAll() Reverses Set() calls, restoring things to their original definitions. This method is automatically called when the StubOutForTesting() object is deleted; there is no need to call it explicitly. It is okay to call UnsetAll() repeatedly, as later calls have no effect if no Set() calls have been made. __enter__ View source __enter__() __exit__ View source __exit__( unused_exc_type, unused_exc_value, unused_tb )
tensorflow.compat.v1.test.stuboutfortesting
tf.compat.v1.test.test_src_dir_path Creates an absolute test srcdir path given a relative path. tf.compat.v1.test.test_src_dir_path( relative_path ) Args relative_path a path relative to tensorflow root. e.g. "core/platform". Returns An absolute path to the linked in runfiles.
tensorflow.compat.v1.test.test_src_dir_path
tf.compat.v1.TextLineReader A Reader that outputs the lines of a file delimited by newlines. Inherits From: ReaderBase tf.compat.v1.TextLineReader( skip_header_lines=None, name=None ) Newlines are stripped from the output. See ReaderBase for supported methods. Args skip_header_lines An optional int. Defaults to 0. Number of lines to skip from the beginning of every file. name A name for the operation (optional). Eager Compatibility Readers are not compatible with eager execution. Instead, please use tf.data to get data into your model. Attributes reader_ref Op that implements the reader. supports_serialize Whether the Reader implementation can serialize its state. Methods num_records_produced View source num_records_produced( name=None ) Returns the number of records this reader has produced. This is the same as the number of Read executions that have succeeded. Args name A name for the operation (optional). Returns An int64 Tensor. num_work_units_completed View source num_work_units_completed( name=None ) Returns the number of work units this reader has finished processing. Args name A name for the operation (optional). Returns An int64 Tensor. read View source read( queue, name=None ) Returns the next record (key, value) pair produced by a reader. Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file). Args queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. name A name for the operation (optional). Returns A tuple of Tensors (key, value). key A string scalar Tensor. value A string scalar Tensor. read_up_to View source read_up_to( queue, num_records, name=None ) Returns up to num_records (key, value) pairs produced by a reader. Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num_records even before the last batch. Args queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. num_records Number of records to read. name A name for the operation (optional). Returns A tuple of Tensors (keys, values). keys A 1-D string Tensor. values A 1-D string Tensor. reset View source reset( name=None ) Restore a reader to its initial clean state. Args name A name for the operation (optional). Returns The created Operation. restore_state View source restore_state( state, name=None ) Restore a reader to a previously saved state. Not all Readers support being restored, so this can produce an Unimplemented error. Args state A string Tensor. Result of a SerializeState of a Reader with matching type. name A name for the operation (optional). Returns The created Operation. serialize_state View source serialize_state( name=None ) Produce a string tensor that encodes the state of a reader. Not all Readers support being serialized, so this can produce an Unimplemented error. Args name A name for the operation (optional). Returns A string Tensor.
tensorflow.compat.v1.textlinereader
tf.compat.v1.TFRecordReader A Reader that outputs the records from a TFRecords file. Inherits From: ReaderBase tf.compat.v1.TFRecordReader( name=None, options=None ) See ReaderBase for supported methods. Args name A name for the operation (optional). options A TFRecordOptions object (optional). Eager Compatibility Readers are not compatible with eager execution. Instead, please use tf.data to get data into your model. Attributes reader_ref Op that implements the reader. supports_serialize Whether the Reader implementation can serialize its state. Methods num_records_produced View source num_records_produced( name=None ) Returns the number of records this reader has produced. This is the same as the number of Read executions that have succeeded. Args name A name for the operation (optional). Returns An int64 Tensor. num_work_units_completed View source num_work_units_completed( name=None ) Returns the number of work units this reader has finished processing. Args name A name for the operation (optional). Returns An int64 Tensor. read View source read( queue, name=None ) Returns the next record (key, value) pair produced by a reader. Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file). Args queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. name A name for the operation (optional). Returns A tuple of Tensors (key, value). key A string scalar Tensor. value A string scalar Tensor. read_up_to View source read_up_to( queue, num_records, name=None ) Returns up to num_records (key, value) pairs produced by a reader. Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num_records even before the last batch. Args queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. num_records Number of records to read. name A name for the operation (optional). Returns A tuple of Tensors (keys, values). keys A 1-D string Tensor. values A 1-D string Tensor. reset View source reset( name=None ) Restore a reader to its initial clean state. Args name A name for the operation (optional). Returns The created Operation. restore_state View source restore_state( state, name=None ) Restore a reader to a previously saved state. Not all Readers support being restored, so this can produce an Unimplemented error. Args state A string Tensor. Result of a SerializeState of a Reader with matching type. name A name for the operation (optional). Returns The created Operation. serialize_state View source serialize_state( name=None ) Produce a string tensor that encodes the state of a reader. Not all Readers support being serialized, so this can produce an Unimplemented error. Args name A name for the operation (optional). Returns A string Tensor.
tensorflow.compat.v1.tfrecordreader
tf.compat.v1.to_bfloat16 Casts a tensor to type bfloat16. (deprecated) tf.compat.v1.to_bfloat16( x, name='ToBFloat16' ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead. Args x A Tensor or SparseTensor or IndexedSlices. name A name for the operation (optional). Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type bfloat16. Raises TypeError If x cannot be cast to the bfloat16.
tensorflow.compat.v1.to_bfloat16
tf.compat.v1.to_complex128 Casts a tensor to type complex128. (deprecated) tf.compat.v1.to_complex128( x, name='ToComplex128' ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead. Args x A Tensor or SparseTensor or IndexedSlices. name A name for the operation (optional). Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type complex128. Raises TypeError If x cannot be cast to the complex128.
tensorflow.compat.v1.to_complex128
tf.compat.v1.to_complex64 Casts a tensor to type complex64. (deprecated) tf.compat.v1.to_complex64( x, name='ToComplex64' ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead. Args x A Tensor or SparseTensor or IndexedSlices. name A name for the operation (optional). Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type complex64. Raises TypeError If x cannot be cast to the complex64.
tensorflow.compat.v1.to_complex64
tf.compat.v1.to_double Casts a tensor to type float64. (deprecated) tf.compat.v1.to_double( x, name='ToDouble' ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead. Args x A Tensor or SparseTensor or IndexedSlices. name A name for the operation (optional). Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type float64. Raises TypeError If x cannot be cast to the float64.
tensorflow.compat.v1.to_double
tf.compat.v1.to_float Casts a tensor to type float32. (deprecated) tf.compat.v1.to_float( x, name='ToFloat' ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead. Args x A Tensor or SparseTensor or IndexedSlices. name A name for the operation (optional). Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type float32. Raises TypeError If x cannot be cast to the float32.
tensorflow.compat.v1.to_float
tf.compat.v1.to_int32 Casts a tensor to type int32. (deprecated) tf.compat.v1.to_int32( x, name='ToInt32' ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead. Args x A Tensor or SparseTensor or IndexedSlices. name A name for the operation (optional). Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type int32. Raises TypeError If x cannot be cast to the int32.
tensorflow.compat.v1.to_int32
tf.compat.v1.to_int64 Casts a tensor to type int64. (deprecated) tf.compat.v1.to_int64( x, name='ToInt64' ) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.cast instead. Args x A Tensor or SparseTensor or IndexedSlices. name A name for the operation (optional). Returns A Tensor or SparseTensor or IndexedSlices with same shape as x with type int64. Raises TypeError If x cannot be cast to the int64.
tensorflow.compat.v1.to_int64
Module: tf.compat.v1.tpu Ops related to Tensor Processing Units. Modules experimental module: Public API for tf.tpu.experimental namespace. Classes class CrossShardOptimizer: An optimizer that averages gradients across TPU shards. class PaddingSpec: Represents the type of padding policies for tpu.replicate. class XLAOptions: XLA compilation options. Functions batch_parallel(...): Shards computation along the batch dimension for parallel execution. bfloat16_scope(...): Scope class for bfloat16 variables so that the model uses custom getter. core(...): Returns the device name for a core in a replicated TPU computation. cross_replica_sum(...): Sum the input tensor across replicas according to group_assignment. initialize_system(...): Initializes a distributed TPU system for use with TensorFlow. outside_compilation(...): Builds part of a computation outside any current TPU replicate scope. replicate(...): Builds a graph operator that runs a replicated TPU computation. rewrite(...): Rewrites computation for execution on a TPU system. shard(...): Shards computation for parallel execution. shutdown_system(...): Shuts down a running a distributed TPU system.
tensorflow.compat.v1.tpu
tf.compat.v1.tpu.batch_parallel Shards computation along the batch dimension for parallel execution. tf.compat.v1.tpu.batch_parallel( computation, inputs=None, num_shards=1, infeed_queue=None, device_assignment=None, name=None, xla_options=None ) Convenience wrapper around shard(). inputs must be a list of Tensors or None (equivalent to an empty list). Each input is split into num_shards pieces along the 0-th dimension, and computation is applied to each shard in parallel. Tensors are broadcast to all shards if they are lexically captured by computation. e.g., x = tf.constant(7) def computation(): return x + 3 ... = shard(computation, ...) The outputs from all shards are concatenated back together along their 0-th dimension. Inputs and outputs of the computation must be at least rank-1 Tensors. Args computation A Python function that builds a computation to apply to each shard of the input. inputs A list of input tensors or None (equivalent to an empty list). The 0-th dimension of each Tensor must have size divisible by num_shards. num_shards The number of shards. infeed_queue If not None, the InfeedQueue from which to append a tuple of arguments as inputs to computation. device_assignment If not None, a DeviceAssignment describing the mapping between logical cores in the computation with physical cores in the TPU topology. Uses a default device assignment if None. The DeviceAssignment may be omitted if each shard of the computation uses only one core, and there is either only one shard, or the number of shards is equal to the number of cores in the TPU system. name (Deprecated) Does nothing. xla_options An instance of tpu.XLAOptions which indicates the options passed to XLA compiler. Use None for default options. Returns A list of output tensors. Raises ValueError If num_shards <= 0
tensorflow.compat.v1.tpu.batch_parallel
tf.compat.v1.tpu.bfloat16_scope Scope class for bfloat16 variables so that the model uses custom getter. @tf_contextlib.contextmanager tf.compat.v1.tpu.bfloat16_scope( name=None ) This enables variables to be read as bfloat16 type when using get_variable.
tensorflow.compat.v1.tpu.bfloat16_scope
tf.compat.v1.tpu.core Returns the device name for a core in a replicated TPU computation. tf.compat.v1.tpu.core( num ) Args num the virtual core number within each replica to which operators should be assigned. Returns A device name, suitable for passing to tf.device().
tensorflow.compat.v1.tpu.core
tf.compat.v1.tpu.CrossShardOptimizer An optimizer that averages gradients across TPU shards. Inherits From: Optimizer tf.compat.v1.tpu.CrossShardOptimizer( opt, reduction=losses.Reduction.MEAN, name='CrossShardOptimizer', group_assignment=None ) Args opt An existing Optimizer to encapsulate. reduction The reduction to apply to the shard losses. name Optional name prefix for the operations created when applying gradients. Defaults to "CrossShardOptimizer". group_assignment Optional 2d int32 lists with shape [num_groups, num_replicas_per_group] which describles how to apply optimizer to subgroups. Raises ValueError If reduction is not a valid cross-shard reduction. Methods apply_gradients View source apply_gradients( grads_and_vars, global_step=None, name=None ) Apply gradients to variables. Calls tpu_ops.cross_replica_sum() to sum gradient contributions across replicas, and then applies the real optimizer. Args grads_and_vars List of (gradient, variable) pairs as returned by compute_gradients(). global_step Optional Variable to increment by one after the variables have been updated. name Optional name for the returned operation. Default to the name passed to the Optimizer constructor. Returns An Operation that applies the gradients. If global_step was not None, that operation also increments global_step. Raises ValueError If the grads_and_vars is malformed. compute_gradients View source compute_gradients( loss, var_list=None, **kwargs ) Compute gradients of "loss" for the variables in "var_list". This simply wraps compute_gradients() from the real optimizer. The gradients will be aggregated in apply_gradients() so that user can modify the gradients like clipping with per replica global norm if needed. The global norm with aggregated gradients can be bad as one replica's huge gradients can hurt the gradients from other replicas. When the CrossShardOptimizer is constructed with reduction == losses.Reduction.MEAN (default), this function scales the loss by 1.0 / num_shards before computing the gradients. Assuming the optimizer uses the default implementation of compute_gradients(), the gradients of the scaled loss are scaled by 1.0 / num_shards compared to the gradients of the original loss. This scaling factor is important because apply_gradients() sums gradients across shards, rather than averaging them. However, the scaling factor must be taken into account when clipping the norm of the gradients or performing other postprocessing. Args loss A Tensor containing the value to minimize. var_list Optional list or tuple of tf.Variable to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKey.TRAINABLE_VARIABLES. **kwargs Keyword arguments for compute_gradients(). Returns A list of (gradient, variable) pairs. Raises ValueError If not within a tpu_shard_context or group_assignment is invalid. get_name View source get_name() get_slot View source get_slot( *args, **kwargs ) Return a slot named "name" created for "var" by the Optimizer. This simply wraps the get_slot() from the actual optimizer. Args *args Arguments for get_slot(). **kwargs Keyword arguments for get_slot(). Returns The Variable for the slot if it was created, None otherwise. get_slot_names View source get_slot_names( *args, **kwargs ) Return a list of the names of slots created by the Optimizer. This simply wraps the get_slot_names() from the actual optimizer. Args *args Arguments for get_slot(). **kwargs Keyword arguments for get_slot(). Returns A list of strings. minimize View source minimize( loss, global_step=None, var_list=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None ) Add operations to minimize loss by updating var_list. This method simply combines calls compute_gradients() and apply_gradients(). If you want to process the gradient before applying them call compute_gradients() and apply_gradients() explicitly instead of using this function. Args loss A Tensor containing the value to minimize. global_step Optional Variable to increment by one after the variables have been updated. var_list Optional list or tuple of Variable objects to update to minimize loss. Defaults to the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. gate_gradients How to gate the computation of gradients. Can be GATE_NONE, GATE_OP, or GATE_GRAPH. aggregation_method Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod. colocate_gradients_with_ops If True, try colocating gradients with the corresponding op. name Optional name for the returned operation. grad_loss Optional. A Tensor holding the gradient computed for loss. Returns An Operation that updates the variables in var_list. If global_step was not None, that operation also increments global_step. Raises ValueError If some of the variables are not Variable objects. Eager Compatibility When eager execution is enabled, loss should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of var_list if not None, else with respect to any trainable variables created during the execution of the loss function. gate_gradients, aggregation_method, colocate_gradients_with_ops and grad_loss are ignored when eager execution is enabled. variables View source variables() Forwarding the variables from the underlying optimizer. Class Variables GATE_GRAPH 2 GATE_NONE 0 GATE_OP 1
tensorflow.compat.v1.tpu.crossshardoptimizer
tf.compat.v1.tpu.cross_replica_sum Sum the input tensor across replicas according to group_assignment. tf.compat.v1.tpu.cross_replica_sum( x, group_assignment=None, name=None ) Args x The local tensor to the sum. group_assignment Optional 2d int32 lists with shape [num_groups, num_replicas_per_group]. group_assignment[i] represents the replica ids in the ith subgroup. name Optional op name. Returns A Tensor which is summed across replicas.
tensorflow.compat.v1.tpu.cross_replica_sum
Module: tf.compat.v1.tpu.experimental Public API for tf.tpu.experimental namespace. Modules embedding module: Public API for tf.tpu.experimental.embedding namespace. Classes class AdagradParameters: Optimization parameters for Adagrad with TPU embeddings. class AdamParameters: Optimization parameters for Adam with TPU embeddings. class DeviceAssignment: Mapping from logical cores in a computation to the physical TPU topology. class FtrlParameters: Optimization parameters for Ftrl with TPU embeddings. class StochasticGradientDescentParameters: Optimization parameters for stochastic gradient descent for TPU embeddings. class TPUSystemMetadata: Describes some metadata about the TPU system. class Topology: Describes a set of TPU devices. Functions embedding_column(...): TPU version of tf.compat.v1.feature_column.embedding_column. initialize_tpu_system(...): Initialize the TPU devices. shared_embedding_columns(...): TPU version of tf.compat.v1.feature_column.shared_embedding_columns. shutdown_tpu_system(...): Shuts down the TPU devices.
tensorflow.compat.v1.tpu.experimental
tf.compat.v1.tpu.experimental.AdagradParameters Optimization parameters for Adagrad with TPU embeddings. tf.compat.v1.tpu.experimental.AdagradParameters( learning_rate: float, initial_accumulator: float = 0.1, use_gradient_accumulation: bool = True, clip_weight_min: Optional[float] = None, clip_weight_max: Optional[float] = None, weight_decay_factor: Optional[float] = None, multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, clip_gradient_min: Optional[float] = None, clip_gradient_max: Optional[float] = None ) Pass this to tf.estimator.tpu.experimental.EmbeddingConfigSpec via the optimization_parameters argument to set the optimizer and its parameters. See the documentation for tf.estimator.tpu.experimental.EmbeddingConfigSpec for more details. estimator = tf.estimator.tpu.TPUEstimator( ... embedding_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( ... optimization_parameters=tf.tpu.experimental.AdagradParameters(0.1), ...)) Args learning_rate used for updating embedding table. initial_accumulator initial accumulator for Adagrad. use_gradient_accumulation setting this to False makes embedding gradients calculation less accurate but faster. Please see optimization_parameters.proto for details. for details. clip_weight_min the minimum value to clip by; None means -infinity. clip_weight_max the maximum value to clip by; None means +infinity. weight_decay_factor amount of weight decay to apply; None means that the weights are not decayed. multiply_weight_decay_factor_by_learning_rate if true, weight_decay_factor is multiplied by the current learning rate. clip_gradient_min the minimum value to clip by; None means -infinity. clip_gradient_max the maximum value to clip by; None means +infinity.
tensorflow.compat.v1.tpu.experimental.adagradparameters
tf.compat.v1.tpu.experimental.AdamParameters Optimization parameters for Adam with TPU embeddings. tf.compat.v1.tpu.experimental.AdamParameters( learning_rate: float, beta1: float = 0.9, beta2: float = 0.999, epsilon: float = 1e-08, lazy_adam: bool = True, sum_inside_sqrt: bool = True, use_gradient_accumulation: bool = True, clip_weight_min: Optional[float] = None, clip_weight_max: Optional[float] = None, weight_decay_factor: Optional[float] = None, multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, clip_gradient_min: Optional[float] = None, clip_gradient_max: Optional[float] = None ) Pass this to tf.estimator.tpu.experimental.EmbeddingConfigSpec via the optimization_parameters argument to set the optimizer and its parameters. See the documentation for tf.estimator.tpu.experimental.EmbeddingConfigSpec for more details. estimator = tf.estimator.tpu.TPUEstimator( ... embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( ... optimization_parameters=tf.tpu.experimental.AdamParameters(0.1), ...)) Args learning_rate a floating point value. The learning rate. beta1 A float value. The exponential decay rate for the 1st moment estimates. beta2 A float value. The exponential decay rate for the 2nd moment estimates. epsilon A small constant for numerical stability. lazy_adam Use lazy Adam instead of Adam. Lazy Adam trains faster. Please see optimization_parameters.proto for details. sum_inside_sqrt This improves training speed. Please see optimization_parameters.proto for details. use_gradient_accumulation setting this to False makes embedding gradients calculation less accurate but faster. Please see optimization_parameters.proto for details. for details. clip_weight_min the minimum value to clip by; None means -infinity. clip_weight_max the maximum value to clip by; None means +infinity. weight_decay_factor amount of weight decay to apply; None means that the weights are not decayed. multiply_weight_decay_factor_by_learning_rate if true, weight_decay_factor is multiplied by the current learning rate. clip_gradient_min the minimum value to clip by; None means -infinity. clip_gradient_max the maximum value to clip by; None means +infinity.
tensorflow.compat.v1.tpu.experimental.adamparameters
Module: tf.compat.v1.tpu.experimental.embedding Public API for tf.tpu.experimental.embedding namespace. Classes class Adagrad: Optimization parameters for Adagrad with TPU embeddings. class Adam: Optimization parameters for Adam with TPU embeddings. class FeatureConfig: Configuration data for one embedding feature. class SGD: Optimization parameters for stochastic gradient descent for TPU embeddings. class TPUEmbedding: The TPUEmbedding mid level API. class TableConfig: Configuration data for one embedding table. Functions serving_embedding_lookup(...): Apply standard lookup ops with tf.tpu.experimental.embedding configs.
tensorflow.compat.v1.tpu.experimental.embedding
tf.compat.v1.tpu.experimental.embedding_column TPU version of tf.compat.v1.feature_column.embedding_column. tf.compat.v1.tpu.experimental.embedding_column( categorical_column, dimension, combiner='mean', initializer=None, max_sequence_length=0, learning_rate_fn=None, embedding_lookup_device=None, tensor_core_shape=None, use_safe_embedding_lookup=True ) Note that the interface for tf.tpu.experimental.embedding_column is different from that of tf.compat.v1.feature_column.embedding_column: The following arguments are NOT supported: ckpt_to_load_from, tensor_name_in_ckpt, max_norm and trainable. Use this function in place of tf.compat.v1.feature_column.embedding_column when you want to use the TPU to accelerate your embedding lookups via TPU embeddings. column = tf.feature_column.categorical_column_with_identity(...) tpu_column = tf.tpu.experimental.embedding_column(column, 10) ... def model_fn(features): dense_feature = tf.keras.layers.DenseFeature(tpu_column) embedded_feature = dense_feature(features) ... estimator = tf.estimator.tpu.TPUEstimator( model_fn=model_fn, ... embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( column=[tpu_column], ...)) Args categorical_column A categorical column returned from categorical_column_with_identity, weighted_categorical_column, categorical_column_with_vocabulary_file, categorical_column_with_vocabulary_list, sequence_categorical_column_with_identity, sequence_categorical_column_with_vocabulary_file, sequence_categorical_column_with_vocabulary_list dimension An integer specifying dimension of the embedding, must be > 0. combiner A string specifying how to reduce if there are multiple entries in a single row for a non-sequence column. For more information, see tf.feature_column.embedding_column. initializer A variable initializer function to be used in embedding variable initialization. If not specified, defaults to tf.compat.v1.truncated_normal_initializer with mean 0.0 and standard deviation 1/sqrt(dimension). max_sequence_length An non-negative integer specifying the max sequence length. Any sequence shorter then this will be padded with 0 embeddings and any sequence longer will be truncated. This must be positive for sequence features and 0 for non-sequence features. learning_rate_fn A function that takes global step and returns learning rate for the embedding table. If you intend to use the same learning rate for multiple embedding tables, please ensure that you pass the exact same python function to all calls of embedding_column, otherwise performence may suffer. embedding_lookup_device The device on which to run the embedding lookup. Valid options are "cpu", "tpu_tensor_core", and "tpu_embedding_core". If specifying "tpu_tensor_core", a tensor_core_shape must be supplied. If not specified, the default behavior is embedding lookup on "tpu_embedding_core" for training and "cpu" for inference. Valid options for training : ["tpu_embedding_core", "tpu_tensor_core"] Valid options for serving : ["cpu", "tpu_tensor_core"] For training, tpu_embedding_core is good for large embedding vocab (>1M), otherwise, tpu_tensor_core is often sufficient. For serving, doing embedding lookup on tpu_tensor_core during serving is a way to reduce host cpu usage in cases where that is a bottleneck. tensor_core_shape If supplied, a list of integers which specifies the intended dense shape to run embedding lookup for this feature on TensorCore. The batch dimension can be left None or -1 to indicate a dynamic shape. Only rank 2 shapes currently supported. use_safe_embedding_lookup If true, uses safe_embedding_lookup_sparse instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures there are no empty rows and all weights and ids are positive at the expense of extra compute cost. This only applies to rank 2 (NxM) shaped input tensors. Defaults to true, consider turning off if the above checks are not needed. Note that having empty rows will not trigger any error though the output result might be 0 or omitted. Returns A _TPUEmbeddingColumnV2. Raises ValueError if dimension not > 0. ValueError if initializer is specified but not callable.
tensorflow.compat.v1.tpu.experimental.embedding_column
tf.compat.v1.tpu.experimental.FtrlParameters Optimization parameters for Ftrl with TPU embeddings. tf.compat.v1.tpu.experimental.FtrlParameters( learning_rate: float, learning_rate_power: float = -0.5, initial_accumulator_value: float = 0.1, l1_regularization_strength: float = 0.0, l2_regularization_strength: float = 0.0, use_gradient_accumulation: bool = True, clip_weight_min: Optional[float] = None, clip_weight_max: Optional[float] = None, weight_decay_factor: Optional[float] = None, multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, multiply_linear_by_learning_rate: bool = False, beta: float = 0, allow_zero_accumulator: bool = False, clip_gradient_min: Optional[float] = None, clip_gradient_max: Optional[float] = None ) Pass this to tf.estimator.tpu.experimental.EmbeddingConfigSpec via the optimization_parameters argument to set the optimizer and its parameters. See the documentation for tf.estimator.tpu.experimental.EmbeddingConfigSpec for more details. estimator = tf.estimator.tpu.TPUEstimator( ... embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( ... optimization_parameters=tf.tpu.experimental.FtrlParameters(0.1), ...)) Args learning_rate a floating point value. The learning rate. learning_rate_power A float value, must be less or equal to zero. Controls how the learning rate decreases during training. Use zero for a fixed learning rate. See section 3.1 in the paper. initial_accumulator_value The starting value for accumulators. Only zero or positive values are allowed. l1_regularization_strength A float value, must be greater than or equal to zero. l2_regularization_strength A float value, must be greater than or equal to zero. use_gradient_accumulation setting this to False makes embedding gradients calculation less accurate but faster. Please see optimization_parameters.proto for details. for details. clip_weight_min the minimum value to clip by; None means -infinity. clip_weight_max the maximum value to clip by; None means +infinity. weight_decay_factor amount of weight decay to apply; None means that the weights are not decayed. multiply_weight_decay_factor_by_learning_rate if true, weight_decay_factor is multiplied by the current learning rate. multiply_linear_by_learning_rate When true, multiplies the usages of the linear slot in the weight update by the learning rate. This is useful when ramping up learning rate from 0 (which would normally produce NaNs). beta The beta parameter for FTRL. allow_zero_accumulator Changes the implementation of the square root to allow for the case of initial_accumulator_value being zero. This will cause a slight performance drop. clip_gradient_min the minimum value to clip by; None means -infinity. clip_gradient_max the maximum value to clip by; None means +infinity.
tensorflow.compat.v1.tpu.experimental.ftrlparameters
tf.compat.v1.tpu.experimental.shared_embedding_columns TPU version of tf.compat.v1.feature_column.shared_embedding_columns. tf.compat.v1.tpu.experimental.shared_embedding_columns( categorical_columns, dimension, combiner='mean', initializer=None, shared_embedding_collection_name=None, max_sequence_lengths=None, learning_rate_fn=None, embedding_lookup_device=None, tensor_core_shape=None, use_safe_embedding_lookup=True ) Note that the interface for tf.tpu.experimental.shared_embedding_columns is different from that of tf.compat.v1.feature_column.shared_embedding_columns: The following arguments are NOT supported: ckpt_to_load_from, tensor_name_in_ckpt, max_norm and trainable. Use this function in place of tf.compat.v1.feature_column.shared_embedding_columns` when you want to use the TPU to accelerate your embedding lookups via TPU embeddings. column_a = tf.feature_column.categorical_column_with_identity(...) column_b = tf.feature_column.categorical_column_with_identity(...) tpu_columns = tf.tpu.experimental.shared_embedding_columns( [column_a, column_b], 10) ... def model_fn(features): dense_feature = tf.keras.layers.DenseFeature(tpu_columns) embedded_feature = dense_feature(features) ... estimator = tf.estimator.tpu.TPUEstimator( model_fn=model_fn, ... embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( column=tpu_columns, ...)) Args categorical_columns A list of categorical columns returned from categorical_column_with_identity, weighted_categorical_column, categorical_column_with_vocabulary_file, categorical_column_with_vocabulary_list, sequence_categorical_column_with_identity, sequence_categorical_column_with_vocabulary_file, sequence_categorical_column_with_vocabulary_list dimension An integer specifying dimension of the embedding, must be > 0. combiner A string specifying how to reduce if there are multiple entries in a single row for a non-sequence column. For more information, see tf.feature_column.embedding_column. initializer A variable initializer function to be used in embedding variable initialization. If not specified, defaults to tf.truncated_normal_initializer with mean 0.0 and standard deviation 1/sqrt(dimension). shared_embedding_collection_name Optional name of the collection where shared embedding weights are added. If not given, a reasonable name will be chosen based on the names of categorical_columns. This is also used in variable_scope when creating shared embedding weights. max_sequence_lengths An list of non-negative integers, either None or empty or the same length as the argument categorical_columns. Entries corresponding to non-sequence columns must be 0 and entries corresponding to sequence columns specify the max sequence length for the column. Any sequence shorter then this will be padded with 0 embeddings and any sequence longer will be truncated. learning_rate_fn A function that takes global step and returns learning rate for the embedding table. If you intend to use the same learning rate for multiple embedding tables, please ensure that you pass the exact same python function to all calls of shared_embedding_columns, otherwise performence may suffer. embedding_lookup_device The device on which to run the embedding lookup. Valid options are "cpu", "tpu_tensor_core", and "tpu_embedding_core". If specifying "tpu_tensor_core", a tensor_core_shape must be supplied. Defaults to "cpu". If not specified, the default behavior is embedding lookup on "tpu_embedding_core" for training and "cpu" for inference. Valid options for training : ["tpu_embedding_core", "tpu_tensor_core"] Valid options for serving : ["cpu", "tpu_tensor_core"] For training, tpu_embedding_core is good for large embedding vocab (>1M), otherwise, tpu_tensor_core is often sufficient. For serving, doing embedding lookup on tpu_tensor_core during serving is a way to reduce host cpu usage in cases where that is a bottleneck. tensor_core_shape If supplied, a list of integers which specifies the intended dense shape to run embedding lookup for this feature on TensorCore. The batch dimension can be left None or -1 to indicate a dynamic shape. Only rank 2 shapes currently supported. use_safe_embedding_lookup If true, uses safe_embedding_lookup_sparse instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures there are no empty rows and all weights and ids are positive at the expense of extra compute cost. This only applies to rank 2 (NxM) shaped input tensors. Defaults to true, consider turning off if the above checks are not needed. Note that having empty rows will not trigger any error though the output result might be 0 or omitted. Returns A list of _TPUSharedEmbeddingColumnV2. Raises ValueError if dimension not > 0. ValueError if initializer is specified but not callable. ValueError if max_sequence_lengths is specified and not the same length as categorical_columns. ValueError if max_sequence_lengths is positive for a non sequence column or 0 for a sequence column.
tensorflow.compat.v1.tpu.experimental.shared_embedding_columns
tf.compat.v1.tpu.experimental.StochasticGradientDescentParameters Optimization parameters for stochastic gradient descent for TPU embeddings. tf.compat.v1.tpu.experimental.StochasticGradientDescentParameters( learning_rate: float, clip_weight_min: Optional[float] = None, clip_weight_max: Optional[float] = None, weight_decay_factor: Optional[float] = None, multiply_weight_decay_factor_by_learning_rate: Optional[bool] = None, clip_gradient_min: Optional[float] = None, clip_gradient_max: Optional[float] = None ) Pass this to tf.estimator.tpu.experimental.EmbeddingConfigSpec via the optimization_parameters argument to set the optimizer and its parameters. See the documentation for tf.estimator.tpu.experimental.EmbeddingConfigSpec for more details. estimator = tf.estimator.tpu.TPUEstimator( ... embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec( ... optimization_parameters=( tf.tpu.experimental.StochasticGradientDescentParameters(0.1)))) Args learning_rate a floating point value. The learning rate. clip_weight_min the minimum value to clip by; None means -infinity. clip_weight_max the maximum value to clip by; None means +infinity. weight_decay_factor amount of weight decay to apply; None means that the weights are not decayed. multiply_weight_decay_factor_by_learning_rate if true, weight_decay_factor is multiplied by the current learning rate. clip_gradient_min the minimum value to clip by; None means -infinity. clip_gradient_max the maximum value to clip by; None means +infinity.
tensorflow.compat.v1.tpu.experimental.stochasticgradientdescentparameters
tf.compat.v1.tpu.initialize_system Initializes a distributed TPU system for use with TensorFlow. tf.compat.v1.tpu.initialize_system( embedding_config=None, job=None, compilation_failure_closes_chips=True ) Args embedding_config If not None, a TPUEmbeddingConfiguration proto describing the desired configuration of the hardware embedding lookup tables. If embedding_config is None, no hardware embeddings can be used. job The job (the XXX in TensorFlow device specification /job:XXX) that contains the TPU devices that will be initialized. If job=None it is assumed there is only one job in the TensorFlow flock, and an error will be returned if this assumption does not hold. compilation_failure_closes_chips Set the configuration whether we want to close TPU chips when there is a compilation failure. Returns A serialized TopologyProto that describes the TPU system. Note: the topology must be evaluated using Session.run before it can be used.
tensorflow.compat.v1.tpu.initialize_system
tf.compat.v1.tpu.outside_compilation Builds part of a computation outside any current TPU replicate scope. tf.compat.v1.tpu.outside_compilation( computation, *args, **kwargs ) tf.tpu.outside_compilation() is used to run ops in computation on CPU instead of running on TPU. For example, users can run ops that are not supported on TPU's (e.g. tf.summary.write()) by explicitly placing those ops on CPU's. Below usage of outside compilation will place ops in computation_with_string_ops on CPU. Example usage: def computation_with_string_ops(x): # strings types are not supported on TPU's and below ops must # run on CPU instead. output = tf.strings.format('1{}', x) return tf.strings.to_number(output) def tpu_computation(): # Expected output is 11. output = tf.tpu.outside_compilation(computation_with_string_ops, 1) Outside compilation should be called inside TPUReplicateContext. That is, tf.tpu.outside_compilation() should be called inside a function that is passed to tpu.split_compile_and_replicate() -- this is implied when outside compilation is invoked inside a function passed to TPUStrategy run(). If invoked outside of TPUReplicateContext, then this simply returns the result of computation, and therefore, would be a no-op. Note that outside compilation is different from tf.distribute.experimental.TPUStrategy.merge_call() as logic in outside compilation is replicated and executed separately for each replica. On the other hand, merge_call() requires a merge_fn to aggregate the inputs from different replicas and is executed only once. For variables placed in TPU device, which includes variables created inside TPUStrategy scope, outside compilation logic must not include variable read/write. For variables placed on host, which is the case when variables created via TPUEstimator, variable read/write is only allowed if the variable is not accessed by any other ops in the TPU computation. Variable read/write from outside compilation cluster is not visible from TPU computation and vice versa. Therefore, if outside compilation logic contains such host variables read/write ops and if the variables are accessed by TPU computation as well, then this may lead to deadlock. Internally, tf.tpu.outside_compilation() adds outside compilation attributes to all ops in computation. During later graph pass, these ops with outside compilation attribute is extracted out and replicated into a host-side graph. Inputs to this extract host-side graph is sent from TPU computation graph to host graph via a pair of XlaSendToHost and XlaRecvFromHost ops. Note that using tf.tpu.outside_compilation() may result in tensor transfer between TPU and CPU, leading to non-trivial performance impact. Args computation A Python function that builds the computation to place on the host. *args the positional arguments for the computation. **kwargs the keyword arguments for the computation. Returns The Tensors returned by computation.
tensorflow.compat.v1.tpu.outside_compilation
tf.compat.v1.tpu.PaddingSpec Represents the type of padding policies for tpu.replicate. Class Variables AUTO <PaddingSpec.AUTO: 0> POWER_OF_TWO <PaddingSpec.POWER_OF_TWO: 1>
tensorflow.compat.v1.tpu.paddingspec
tf.compat.v1.tpu.replicate Builds a graph operator that runs a replicated TPU computation. tf.compat.v1.tpu.replicate( computation, inputs=None, infeed_queue=None, device_assignment=None, name=None, maximum_shapes=None, padding_spec=None, xla_options=None ) Example for the basic usage that inputs has static shape: def computation(x): x = x + 1 return tf.math.reduce_mean(x) x = tf.convert_to_tensor([1., 2., 3.]) y = tf.convert_to_tensor([4., 5., 6.]) tf.compat.v1.tpu.replicate(computation, inputs=[[x], [y]]) If the inputs has dynamic shapes and you would like to automatically bucketize the inputs to avoid XLA recompilation. See the advanced example below: def computation(x): x = x + 1 return tf.math.reduce_mean(x) # Assume input tensors in two replicas `x` and `y` both have dynamic shape # ([None, 2]). tf.compat.v1.tpu.replicate( computation, inputs=[x, y], maximum_shapes=[tf.TensorShape([None, None])], padding_spec=tf.compat.v1.tpu.PaddingSpec.POWER_OF_TWO) Args computation A Python function that builds the computation to replicate. inputs A list of lists of input tensors or None (equivalent to [[]]), indexed by [replica_num][input_num]. All replicas must have the same number of inputs. Each input can be a nested structure containing values that are convertible to tensors. Note that passing an N-dimension list of compatible values will result in a N-dimension list of scalar tensors rather than a single Rank-N tensors. If you need different behavior, convert part of inputs to tensors with tf.convert_to_tensor. infeed_queue If not None, the InfeedQueue from which to append a tuple of arguments as inputs to computation. device_assignment If not None, a DeviceAssignment describing the mapping between logical cores in the computation with physical cores in the TPU topology. Uses a default device assignment if None. The DeviceAssignment may be omitted if each replica of the computation uses only one core, and there is either only one replica, or the number of replicas is equal to the number of cores in the TPU system. name (Deprecated) Does nothing. maximum_shapes A nested structure of tf.TensorShape representing the shape to which the respective component of each input element in each replica should be padded. Any unknown dimensions (e.g. tf.compat.v1.Dimension(None) in a tf.TensorShape or -1 in a tensor-like object) will be padded to the maximum size of that dimension over all replicas. The structure of maximum_shapes needs to be the same as inputs[0]. padding_spec An enum specified by tpu.PaddingSpec. This describes the padding policy when the inputs to tpu.replicate is dynamic. One usage is to enable automatic bucketizing on the inputs by setting the value to tpu.PaddingSpec.POWER_OF_TWO, which can help to reduce the recompilation in the XLA side. xla_options An instance of tpu.XLAOptions which indicates the options passed to XLA compiler. Use None for default options. Returns A list of outputs, indexed by [replica_num] each output can be a nested structure same as what computation() returns with a few exceptions. Exceptions include: 1) None output: a NoOp would be returned which control-depends on computation. 2) Single value output: A tuple containing the value would be returned. 3) Operation-only outputs: a NoOp would be returned which control-depends on computation. Raises ValueError If all replicas do not have equal numbers of input tensors. ValueError If the number of inputs per replica does not match the number of formal parameters to computation. ValueError If the static inputs dimensions don't match with the values given in maximum_shapes. ValueError If the structure of inputs per replica does not match the structure of maximum_shapes.
tensorflow.compat.v1.tpu.replicate
tf.compat.v1.tpu.rewrite Rewrites computation for execution on a TPU system. tf.compat.v1.tpu.rewrite( computation, inputs=None, infeed_queue=None, device_assignment=None, name=None, xla_options=None ) Args computation A Python function that builds a computation to apply to the input. If the function takes n inputs, 'inputs' should be a list of n tensors. computation may return a list of operations and tensors. Tensors must come before operations in the returned list. The return value of rewrite is a list of tensors corresponding to the tensors from the output of computation. All Operations constructed during computation will be executed when evaluating any of the returned output tensors, not just the ones returned. inputs A list of input tensors or None (equivalent to an empty list). Each input can be a nested structure containing values that are convertible to tensors. Note that passing an N-dimension list of compatible values will result in a N-dimension list of scalar tensors rather than a single Rank-N tensors. If you need different behavior, convert part of inputs to tensors with tf.convert_to_tensor. infeed_queue If not None, the InfeedQueue from which to append a tuple of arguments as inputs to computation. device_assignment if not None, a DeviceAssignment describing the mapping between logical cores in the computation with physical cores in the TPU topology. May be omitted for a single-core computation, in which case the core attached to task 0, TPU device 0 is used. name (Deprecated) Does nothing. xla_options An instance of tpu.XLAOptions which indicates the options passed to XLA compiler. Use None for default options. Returns Same data structure as if computation(*inputs) is called directly with some exceptions for correctness. Exceptions include: 1) None output: a NoOp would be returned which control-depends on computation. 2) Single value output: A tuple containing the value would be returned. 3) Operation-only outputs: a NoOp would be returned which control-depends on computation.
tensorflow.compat.v1.tpu.rewrite