Varis Darasirikul
Varis Darasirikul

Reputation: 4177

'Sequential' object has no attribute '_compile_metrics'

My tensorflow is version 2.4.1

i imported modules like this

### import modules
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense, Conv2D, MaxPool2D, BatchNormalization, Dropout
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import pandas as pd
import scipy

%matplotlib inline

Then i try to create simple compile model like this

def compile_model(model):
    # YOUR CODE HERE
    model.compile(loss='sparse_categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

So my testing function is like this

test_model = Sequential([Dense(100),
                        Dense(2, activation='softmax')])
compile_model(test_model)
assert isinstance(test_model.optimizer, tf.keras.optimizers.Adam)
assert hasattr(test_model, 'loss')
assert test_model.loss == 'sparse_categorical_crossentropy'
assert ['accuracy'] == test_model._compile_metrics
del test_model

After i ran above code blocks i got this error AttributeError: 'Sequential' object has no attribute '_compile_metrics'

enter image description here

But i can't seems find any actual document about _compile_metrics

Am i missing something or is it about tensorflow version? Please help.

Thanks!

Upvotes: 1

Views: 1315

Answers (2)

Innat
Innat

Reputation: 17219

Update

The answer by OP will only work in TF 2.0, 2.1 only. From TF 2.2 - 2.5, it won't work.


To get the metric name, like accuracy you have to run the model at least one epoch or on a single batch.

def compile_model(model):
    # YOUR CODE HERE
    model.compile(loss='sparse_categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
test_model = Sequential([Dense(256, ),
                        Dense(2, activation='softmax')])
compile_model(test_model)
assert isinstance(test_model.optimizer, tf.keras.optimizers.Adam)
assert hasattr(test_model, 'loss')
assert test_model.loss == 'sparse_categorical_crossentropy'

Run-on single epoch with dummy set

test_model.fit(x = np.random.uniform(0,1, (37432,512)),
               y = np.random.randint(0,2, (37432,1)))

test_model.loss # sparse_categorical_crossentropy
test_model.metrics_names # ['loss', 'accuracy']

assert 'loss' == test_model.metrics_names[0]
assert 'accuracy' == test_model.metrics_names[1]

Upvotes: 1

Varis Darasirikul
Varis Darasirikul

Reputation: 4177

Basically, it is about the version, so the sample that i got suppose to run on Tensorflow 2.0.0 but i ran it on 2.4.0 so if i ran the code in 2.0.0 then it works fine.

Upvotes: 1

Related Questions