本机环境:
- cudatoolkit = 10.1.243
- cudnn = 7.6.5
- tensorflow-gpu = 2.1.0
- keras-gpu = 2.3.1
今天在以TensorFlow2.1.0为后端的Keras中使用TensorBoard时报错,发现原因是keras和tf.keras混用导致的。报错与解决方案如下:
- 导致报错语句:
summary = TensorBoard(log_dir="cnn_lstm_logs/",histogram_freq=1)
报错:
---> 54 summary = TensorBoard(log_dir="cnn_lstm_logs/",histogram_freq=1)
55 history=model.fit(trainX, trainy,
56 epochs=epochs, batch_size=batch_size, verbose=verbose, validation_data=(testX, testy),
NameError: name 'TensorBoard' is not defined
- 更改程序:
summary = keras.callbacks.TensorBoard(log_dir="cnn_lstm_logs/",histogram_freq=1)
报错:
AttributeError: 'Sequential' object has no attribute '_get_distribution_strategy
- 进一步修改程序
summary = tf.keras.callbacks.TensorBoard(log_dir="cnn_lstm_logs/",histogram_freq=1)
仍然报错:
AttributeError: 'Sequential' object has no attribute '_get_distribution_strategy
- 根据Stack Overflow 描述,做如下修改:
#model = Sequential() # 顺序模型
model = tf.keras.Sequential()
报错:
C:\anaconda3\envs\keras\lib\site-packages\tensorflow_core\python\keras\engine\sequential.py in add(self, layer)
159 raise TypeError('The added layer must be '
160 'an instance of class Layer. '
--> 161 'Found: ' + str(layer))
162
163 tf_utils.assert_no_legacy_layers([layer])
TypeError: The added layer must be an instance of class Layer. Found: <keras.layers.wrappers.TimeDistributed object at 0x0000016997098348>
- 继续修改
将开头导入的包from keras.xx
,全部改为from tensorflow.keras.xx
,如:
#import keras
import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, TimeDistributed, Conv1D, MaxPooling1D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import LSTM
from tensorflow.keras.utils import to_categorical
仍然报错:
C:\anaconda3\envs\keras\lib\site-packages\tensorflow_core\python\eager\profiler.py in stop()
97 if _profiler is None:
98 raise ProfilerNotRunningError(
---> 99 'Cannot stop profiling. No profiler is running.')
100 if context.default_execution_mode == context.EAGER_MODE:
101 context.context().executor.wait()
ProfilerNotRunningError: Cannot stop profiling. No profiler is running.
- 参考这位博主的解决方案,做如下修改,成功运行:
logdir = os.path.join('cnn_lstm_logs')
summary = tensorflow.keras.callbacks.TensorBoard(log_dir=logdir,histogram_freq=1)
history=model.fit(trainX, trainy,
epochs=epochs, batch_size=batch_size, verbose=verbose, validation_data=(testX, testy),
callbacks=[summary])
- 运行结果:
参考:
https://stackoverflow.com/questions/59765784/attributeerror-sequential-object-has-no-attribute-get-distribution-strategy
https://stackoverflow.com/questions/59894720/keras-and-tensorboard-attributeerror-sequential-object-has-no-attribute-g