【问题标题】:How do I pickle my neural net prediction models, so that i don't have to re-train them everytime?如何腌制我的神经网络预测模型,这样我就不必每次都重新训练它们?
【发布时间】:2022-01-03 23:37:50
【问题描述】:

正如标题所说,我想腌制我的神经网络,但我得到了一个 TypeError

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16896/2912615623.py in <module>
      5 
      6 with open('lstm_model.pkl', 'wb') as file:
----> 7     pickle.dump(mod, file)

TypeError: cannot pickle 'weakref' object

我尝试了this SO question 的解决方案,但我得到了同样的错误。
顺便说一句,模型是来自 sklearn 库的 LSTM

编辑:
抱歉,正如@Ben Reiniger 所说,LSTM 来自keras.layer

这是可重现的代码。

model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape = (x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences = False))
model.add(Dense(25))
model.add(Dense(1))

model.compile(optimizer="adam", loss='mean_squared_error')

model.fit(x_train, y_train, batch_size = 1, epochs = 1)


# Saving the model
import pickle

mod = {'Model': model}

with open('lstm_model.pkl', 'wb') as file:
    pickle.dump(mod, file)

我得到的错误


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16896/2912615623.py in <module>
      5 
      6 with open('lstm_model.pkl', 'wb') as file:
----> 7     pickle.dump(mod, file)

TypeError: cannot pickle 'weakref' object

【问题讨论】:

  • 请添加最少的代码来重现此问题。
  • sklearn 没有 LSTM

标签: python scikit-learn deep-learning neural-network


【解决方案1】:

Keras 有一个save 方法,在docs 中描述。他们说

不建议使用 pickle 或 cPickle 来保存 Keras 模型

因此,这样做:

保存:

model.save('your/path')

加载中:

model = keras.models.load_model('your/path')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2020-08-24
    • 2017-08-14
    • 1970-01-01
    • 2017-08-19
    • 2014-04-07
    • 2017-06-19
    相关资源
    最近更新 更多