Amin Ba
Amin Ba

Reputation: 2436

what is the difference between `from tensorflow.keras.metrics import binary_accuracy` vs `from tensorflow.metrics import binary_accuracy`

I have this code that works:

import tensorflow as tf
from tensorflow.keras.metrics import binary_accuracy

# Compile the model
model_4.compile(optimizer=Adam(), loss=BinaryCrossentropy(),
                metrics=[binary_accuracy])

and this one that works:

import tensorflow as tf

# Compile the model
model_4.compile(optimizer=Adam(), loss=BinaryCrossentropy(),
                metrics=[tf.metrics.binary_accuracy])

but this one does not work and I do not understand why:

import tensorflow as tf
from tensorflow.metrics import binary_accuracy


# Compile the model
model_4.compile(optimizer=Adam(), loss=BinaryCrossentropy(),
                metrics=[binary_accuracy])
ModuleNotFoundError: No module named 'tensorflow.metrics'

This should be something simple but I do not understand why I have this error

Upvotes: 1

Views: 124

Answers (1)

furas
furas

Reputation: 142641

If you use print(tf.__file__) then you see the full path to code - on my Linux Mint it is

/usr/local/lib/python3.8/dist-packages/tensorflow

and when you open this folder then you see there is no subfolder metrics.

And this is why doesn't work from tensorflow.metrics import binary_accuracy which looks for the real subfolder.

But there is a real subfolder keras.metrics and works other imports.


If you open __init__.py in this folder and use the search function in your editor to find metrics then you should see

if hasattr(_current_module, 'keras'):

   metrics = keras.metrics

   setattr(_current_module, "metrics", metrics)

which creates alias metrics = keras.metrics and this is why works tf.metrics.binary_accuracy

Upvotes: 3

Related Questions