TensorFlow tf.equal, reduce all, reduce any Examples

This TensorFlow example page uses equal to determine the equality of each element. It uses reduce_all and reduce_any.

Equal, TensorFlow.

Two tensors have many elements—but how many of the elements are equal in each tensor? With equal() we get a vector of boolean values.

For each index,

equal() determines if the element in the first tensor equals the one in the second. We get an array of bools (True and False).

Example program.

Consider this program. It introduces 3 arrays, but only the first 2 are equal. The third one is different. We then use tf.equal to create a tensor that tests for equality.

Results: When 2 vectors have the same elements, equal() returns a vector (of the same shape) that contains True in each index.

And: When an element is different, False is placed in that index instead. So we compare elements at certain indexes.

TensorFlow program that uses equal import tensorflow as tf x = [1., 2., 3.] y = [1., 2., 3.] z = [0., 1., 3.] # Use equal to test each element for equality. result1 = tf.equal(x, y) result2 = tf.equal(y, z) session = tf.Session() print( print( Output [ True True True] [False False True]

Reduce_all, any.

The reduce_all and reduce_any methods act upon vectors of booleans (True and False). We can pass the result of equal() to these methods.

Here: We use reduce_all, which returns True if all elements are True. It returns False otherwise.

And: We use reduce_any, which returns True if at least 1 element is True. If none are True, it returns false.

TensorFlow program that uses reduce_all, reduce_any import tensorflow as tf x = [1., 2., 3.] y = [1., 2., 3.] z = [0., 1., 3.] result1 = tf.equal(x, y) result2 = tf.equal(y, z) # Use reduce_all and reduce_any to test the results of equal. result3 = tf.reduce_all(result1) result4 = tf.reduce_all(result2) result5 = tf.reduce_any(result1) result6 = tf.reduce_any(result2) session = tf.Session() print("EQUAL ", print("EQUAL ", print("REDUCE ALL", print("REDUCE ALL", print("REDUCE ANY", print("REDUCE ANY", Output EQUAL [ True True True] EQUAL [False False True] REDUCE ALL True REDUCE ALL False REDUCE ANY True REDUCE ANY True

Some notes.

With equal() we get a vector of element equality bools. And with reduce_all and reduce_any, we can determine if two vectors have all equal elements, any equal elements, or none.

A review.

It is important to understand how to use "reduce" methods. These transform a vector into a single value. To determine if 2 tensors are equal, we can reduce the result of equal().reduce_meanreduce_sum
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen,