【发布时间】:2021-11-18 14:20:25
【问题描述】:
我见过this question 和this one,但没有真正解释发生了什么,也没有为我面临的问题提供解决方案。
下面的代码是我在更大的上下文中尝试做的一个 sn-p。基本上,我正在创建一个包含 tensorflow.keras 模型的对象,我使用从this answer 改编的技巧将其保存到带有泡菜的文件中。我正在处理的实际课程还有其他几个领域和方法,因此我更愿意让它可以腌制并以灵活的方式这样做。请参阅下面的代码,以最小化重现问题。 ReproduceProblem.py:
import pickle
import numpy as np
import tempfile
import tensorflow as tf
def __getstate__(self):
model_str = ""
with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=False) as fd:
tf.keras.models.save_model(self, fd.name, overwrite=True)
model_str = fd.read()
d = {"model_str": model_str}
return d
def __setstate__(self, state):
with tempfile.NamedTemporaryFile(suffix=".hdf5", delete=False) as fd:
fd.write(state["model_str"])
fd.flush()
model = tf.keras.models.load_model(fd.name)
self.__dict__ = model.__dict__
class ContainsSequential:
def __init__(self):
self.other_field = "potato"
self.model = tf.keras.models.Sequential()
self.model.__getstate__ = lambda mdl=self.model: __getstate__(mdl)
self.model.__setstate__ = __setstate__
self.model.add(tf.keras.layers.Input(shape=(None, 3)))
self.model.add(tf.keras.layers.LSTM(3, activation="relu", return_sequences=True))
self.model.add(tf.keras.layers.Dense(3, activation="linear"))
# Now do the business:
tf.keras.backend.clear_session()
file_name = 'pickle_file.pckl'
instance = ContainsSequential()
instance.model.predict(np.random.rand(3, 1, 3))
print(instance.other_field)
with open(file_name, 'wb') as fid:
pickle.dump(instance, fid)
with open(file_name, 'rb') as fid:
restored_instance = pickle.load(fid)
print(restored_instance.other_field)
restored_instance.model.predict(np.random.rand(3, 1, 3))
print('Done')
虽然在instance.model.predict(np.random.rand(3, 1, 3)) 行上没有失败,但在restored_instance.model.predict(np.random.rand(3, 1, 3)) 行上确实失败了,错误消息是:
File "<path>\ReproduceProblem.py", line 52, in <module>
restored_instance.model.predict(np.random.rand(3, 1, 3))
File "<path>\Python\Python39\lib\site-packages\keras\engine\training.py", line 1693, in predict
if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access
File "<path>\Python\Python39\lib\site-packages\keras\engine\training.py", line 716, in distribute_strategy
return self._distribution_strategy or tf.distribute.get_strategy()
AttributeError: 'Sequential' object has no attribute '_distribution_strategy'
我对@987654329@ 应该是什么一无所知,但在我的工作流程中,一旦我保存了文件,我就不需要再训练它了,只需用它来进行预测或咨询其他类的属性。我尝试将其设置为 None 并添加更多属性,但没有成功。
【问题讨论】:
标签: python python-3.x tensorflow keras pickle