Fix of another small annoyance in “Tensorflow Introduction” assignment

After the text

The dataset that you’ll be using during this assignment is a subset of the sign language digits. It contains six different classes representing the digits from 0 to 5.

a somewhat opaque piece of code appears to load the “unique labels”.

Suggesting to add least add some comments and thus make the processing more evident, like so:

# "y_train" is a Tensorflow "Dataset"
# https://www.tensorflow.org/api_docs/python/tf/data/Dataset
# It implements the "iterator" protocol, so we can use "for ... in" on it.
# The "element" obtained during iteration is a "Tensor" 
# (more specifically, an "EagerTensor", but that is too much detail).
# https://www.tensorflow.org/api_docs/python/tf/Tensor
# The call ".numpy()" converts the tensor into a Numpy array or scalar (in this case, a scalar)

def collect_unique_labels_from_training_tf_dataset(tf_dataset):
    return {element.numpy() for element in tf_dataset}

unique_labels = collect_unique_labels_from_training_tf_dataset(y_train)
print(unique_labels)

Here is the “somewhat opaque piece of code” that David refers to:

unique_labels = set()
for element in y_train:
    unique_labels.add(element.numpy())
print(unique_labels)

Which gives this result:

{0, 1, 2, 3, 4, 5}

It’s a matter of taste of course, but I would say that is pretty clear. The uniqueness is handled by the “set” construct in python. But your code uses that as well, just in a bit more subtle way: the “set” magic is the curly braces in the return value.

Of course your code is also more “pythonic” in that it uses an iterator.

So your code is more elegant, but I think it’s a stretch to call the original code “opaque”.

2 Likes

@dtonhofer @paulinpaloalto Well it is pretty good.
But one question I have is that when we keep the name so long for example in this case collect_unique_labels_from_training_tf_dataset what can be other factors that can decrease the optimization of the function/code. One I know is the memory. Do we are taking these parameters under considerations :red_question_mark:

Sorry about that. Yes, I was being hyperbolic (also, I couldn’t fully remember what had been there). But in fact, I was mostly fixated on the accompanying comments.