Returns x - y element-wise.
tf.raw_ops.Sub(
x, y, name=None
)
Note: tf.subtract supports broadcasting. More about broadcasting here
Both input and output have a range (-inf, inf).
Example usages below.
Subtract operation between an array and a scalar:
x = [1, 2, 3, 4, 5] y = 1 tf.subtract(x, y) <tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)> tf.subtract(y, x) <tf.Tensor: shape=(5,), dtype=int32, numpy=array([ 0, -1, -2, -3, -4], dtype=int32)>
Note that binary - operator can be used instead:
x = tf.convert_to_tensor([1, 2, 3, 4, 5]) y = tf.convert_to_tensor(1) x - y <tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>
Subtract operation between an array and a tensor of same shape:
x = [1, 2, 3, 4, 5] y = tf.constant([5, 4, 3, 2, 1]) tf.subtract(y, x) <tf.Tensor: shape=(5,), dtype=int32, numpy=array([ 4, 2, 0, -2, -4], dtype=int32)>
For example,
x = tf.constant([1, 2], dtype=tf.int8) y = [2**8 + 1, 2**8 + 2] tf.subtract(x, y) <tf.Tensor: shape=(2,), dtype=int8, numpy=array([0, 0], dtype=int8)>
When subtracting two input values of different shapes, tf.subtract follows the general broadcasting rules . The two input array shapes are compared element-wise. Starting with the trailing dimensions, the two dimensions either have to be equal or one of them needs to be 1.
For example,
x = np.ones(6).reshape(2, 3, 1)
y = np.ones(6).reshape(2, 1, 3)
tf.subtract(x, y)
<tf.Tensor: shape=(2, 3, 3), dtype=float64, numpy=
array([[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]])>
Example with inputs of different dimensions:
x = np.ones(6).reshape(2, 3, 1)
y = np.ones(6).reshape(1, 6)
tf.subtract(x, y)
<tf.Tensor: shape=(2, 3, 6), dtype=float64, numpy=
array([[[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]]])>
| Args | |
|---|---|
x | A Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128, uint32, uint64. |
y | A Tensor. Must have the same type as x. |
name | A name for the operation (optional). |
| Returns | |
|---|---|
A Tensor. Has the same type as x. |
© 2022 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 4.0.
Code samples licensed under the Apache 2.0 License.
https://www.tensorflow.org/versions/r2.9/api_docs/python/tf/raw_ops/Sub