我正在通过一个在线课程学习如何通过Keras升级模型的构建。
这是我的代码。 (声称可以正常工作)
import pandas as pd
import keras
from keras.models import Sequential
from keras.layers import *
training_data_df = pd.read_csv("sales_data_training_scaled.csv")
X = training_data_df.drop('total_earnings', axis=1).values
Y = training_data_df[['total_earnings']].values
# Define the model
model = Sequential()
model.add(Dense(50, input_dim=9, activation='relu', name='layer_1'))
model.add(Dense(100, activation='relu', name='layer_2'))
model.add(Dense(50, activation='relu', name='layer_3'))
model.add(Dense(1, activation='linear', name='output_layer'))
model.compile(loss='mean_squared_error', optimizer='adam')
# Create a TensorBoard logger
logger = keras.callbacks.TensorBoard(
log_dir='logs',
write_graph=True,
histogram_freq=5
)
# Train the model
model.fit(
X,
Y,
epochs=50,
shuffle=True,
verbose=2,
callbacks=[logger]
)
# Load the separate test data set
test_data_df = pd.read_csv("sales_data_test_scaled.csv")
X_test = test_data_df.drop('total_earnings', axis=1).values
Y_test = test_data_df[['total_earnings']].values
test_error_rate = model.evaluate(X_test, Y_test, verbose=0)
print("The mean squared error (MSE) for the test data set is: {}".format(test_error_rate))
当执行以下代码时,出现以下错误。
Using TensorFlow backend.
2020-01-16 13:58:14.024374: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2020-01-16 13:58:14.037202: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fc47b436390 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-01-16 13:58:14.037211: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version
Traceback (most recent call last):
File "/Users/himsaragallage/Documents/Building_Deep_Learning_apps/06/model_logging final.py", line 35, in <module>
callbacks=[logger]
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/training.py", line 1239, in fit
validation_freq=validation_freq)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/engine/training_arrays.py", line 119, in fit_loop
callbacks.set_model(callback_model)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/callbacks/callbacks.py", line 68, in set_model
callback.set_model(model)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/keras/callbacks/tensorboard_v2.py", line 116, in set_model
super(TensorBoard, self).set_model(model)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow_core/python/keras/callbacks.py", line 1532, in set_model
self.log_dir, self.model._get_distribution_strategy()) # pylint: disable=protected-access
AttributeError: 'Sequential' object has no attribute '_get_distribution_strategy'
Process finished with exit code 1
当我尝试调试时
我发现此错误是由于我尝试使用tensorboard logger
而引起的。更精确地。当我添加callbacks=[logger]
时。如果没有那行代码,程序就可以正常运行。但是不会使用Tensorboard。
请向我建议一种可以成功运行上述python脚本消除错误的方法。
答案 0 :(得分:4)
希望您指的是这个LinkedIn Keras Course。
使用 Tensorflow Version 2.1
时,即使遇到相同的错误。但是,在将 Tensorflow Version
降级并在代码中稍作修改后,我可以调用 Tensorboard
。
工作代码如下所示:
import pandas as pd
import keras
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import *
training_data_df = pd.read_csv("sales_data_training_scaled.csv")
X = training_data_df.drop('total_earnings', axis=1).values
Y = training_data_df[['total_earnings']].values
# Define the model
model = Sequential()
model.add(Dense(50, input_dim=9, activation='relu', name='layer_1'))
model.add(Dense(100, activation='relu', name='layer_2'))
model.add(Dense(50, activation='relu', name='layer_3'))
model.add(Dense(1, activation='linear', name='output_layer'))
model.compile(loss='mean_squared_error', optimizer='adam')
# Create a TensorBoard logger
logger = tf.keras.callbacks.TensorBoard(
log_dir='logs',
write_graph=True,
histogram_freq=5
)
# Train the model
model.fit(
X,
Y,
epochs=50,
shuffle=True,
verbose=2,
callbacks=[logger]
)
# Load the separate test data set
test_data_df = pd.read_csv("sales_data_test_scaled.csv")
X_test = test_data_df.drop('total_earnings', axis=1).values
Y_test = test_data_df[['total_earnings']].values
test_error_rate = model.evaluate(X_test, Y_test, verbose=0)
print("The mean squared error (MSE) for the test data set is: {}".format(test_error_rate))
答案 1 :(得分:1)
您可能会发现this帖子很有用。
因此,而不是从keras(即)导入
from keras.models import Sequential
从tensorflow导入:
from tensorflow.keras.models import Sequential
这当然也适用于大多数其他进口。
这只是一个幸运的猜测,因为我无法运行您的代码,但希望对您有所帮助!
答案 2 :(得分:1)
您的python环境似乎混合了keras
和tensorflow.keras
的导入。尝试使用顺序模块,如下所示:
model = tensorflow.keras.Sequential()
答案 3 :(得分:1)
我建议不要混用keras
和tf.keras
。这些是不同的项目,因为keras
是原始的多后端项目,而tf.keras
是集成到tensorflow中的版本。 Keras将停止支持其他后端,但不再使用tensorflow,因此建议改用它。选中https://keras.io/#multi-backend-keras-and-tfkeras
一种简单的方法是从tensorflow导入keras:
import tensorflow as tf
import tensorflow.keras as keras
#import keras
import keras.backend as K
from keras.models import Model, Sequential, load_model
from keras.layers import Dense, Embedding, Dropout, Input, Concatenate
print("Python: "+str(sys.version))
print("Tensorflow version: "+tf.__version__)
print("Keras version: "+keras.__version__)
Python: 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0]
Tensorflow version: 2.1.0
Keras version: 2.2.4-tf