numpy() is only available when eager execution is enabled in TensorFlow2 and its solution

When upgrading the HPCC GNN bundle from TensorFlow1.x to TensorFlow2.x, I encountered an error of numpy() is only available when eager execution is enabled. This blog records the cause and solution of the problem.

Problem Description

When writing the test code, I encountered a strange bug.

I defined a TensorFlow model:

1
2
3
4
5
6
7
8
9
10
11
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import models,layers

tf.keras.backend.clear_session()

model = models.Sequential()
model.add(layers.Dense(20,activation = 'relu',input_shape=(15,)))
model.add(layers.Dense(10,activation = 'relu' ))
model.add(layers.Dense(1,activation = 'sigmoid' ))

When defining the optimizer, if the name is used directly, it can be compiled normally. The code is as follows:

1
2
3
model.compile(optimizer=‘Adam’,
loss='binary_crossentropy',
metrics=['AUC'])

But if I use

1
2
3
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss='binary_crossentropy',
metrics=['AUC'])

will report an error:

numpy() is only available when eager execution is enabled.

Cause and solution

After many investigations, it is found that the result of tf.executing_eagerly() is False. This is strange. I am using TensorFlow2.12, and the eager mode is enabled by default. Why does this error still occur?

The reason is that I upgraded from the compatibility mode of TensorFlow2. That is, the original TensorFlow mode is:

1
2
import tensorflow.compat.v1 as tf # V2.x
tf.disable_v2_behavior()

Before the HPCC System Platform is restarted, tf.disable_v2_behavior() will always take effect, so the value of tf.executing_eagerly() is False.

Solution: restart the HPCC System Platform.