-1
$\begingroup$

I am trying to use EfficientNetB7 from keras implementation Image classification via fine-tuning with EfficientNet

but always the following code gives me error:

def build_model(num_classes):
inputs = layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3))
x = img_augmentation(inputs)
model = EfficientNetB7(include_top=False, input_tensor=x, weights="imagenet")

# Freeze the pretrained weights
model.trainable = False

# Rebuild top
x = layers.GlobalAveragePooling2D(name="avg_pool")(model.output)
x = layers.BatchNormalization()(x)

top_dropout_rate = 0.2
x = layers.Dropout(top_dropout_rate, name="top_dropout")(x)
outputs = layers.Dense(NUM_CLASSES, activation="softmax", name="pred")(x)

# Compile
model = tf.keras.Model(inputs, outputs, name="EfficientNet")
optimizer = tf.keras.optimizers.Adam(learning_rate=1e-2)
model.compile(optimizer=optimizer, loss="categorical_crossentropy", metrics=["accuracy")
return model

and I call the function using:

with strategy.scope():
  model = build_model(num_classes=NUM_CLASSE)
epochs = 10  # @param {type: "slider", min:8, max:80}
hist = model.fit(train_set, epochs=epochs, validation_data=test_set, verbose=2)
plot_hist(hist)

Error:

NameError: name 'layers' is not defined

can somebody help me?

$\endgroup$
3
  • $\begingroup$ In 2nd line you are using layers.input, did you import or define this function anywhere? $\endgroup$ Jan 15 at 4:21
  • $\begingroup$ yes I import layers using this (from tensorflow.keras.layers import *) $\endgroup$
    – Beba.S
    Jan 15 at 6:44
  • $\begingroup$ Try this : solution1 : from tensorflow.keras import layers Solution2 : Insteads of layers.INPUT directly use input But nor advisable as input maybe defined multiple time various packages $\endgroup$ Jan 15 at 7:01
0
$\begingroup$

The reason for this seems to be your are importing

from tensorflow.keras.layers import *

But while your are calling you are using :

layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3))

this calling will give you an error so instead try below import

Please try this import :

from tensorflow.keras import layers
$\endgroup$
5
  • $\begingroup$ Thank you it has been worked but the code give me another error $\endgroup$
    – Beba.S
    Jan 15 at 7:14
  • $\begingroup$ ValueError: Input 0 of layer "avg_pool" is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: (None, 2560) $\endgroup$
    – Beba.S
    Jan 15 at 7:16
  • $\begingroup$ This is due mismatch in dimension.you have to make sure dimension matches what avgpool edpeceyd. Please upvote if answer helped :) $\endgroup$ Jan 15 at 7:18
  • $\begingroup$ sorry, I am not very good at this, how can I be sure of this? $\endgroup$
    – Beba.S
    Jan 15 at 7:26
  • $\begingroup$ Please check dimension at every step..if not aligned maybe reshaping is required .. $\endgroup$ Jan 15 at 12:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.