【问题标题】:How I can save the model python3如何保存模型 python3
【发布时间】:2021-02-07 17:51:39
【问题描述】:

**我正在尝试保存模型以在 Web 应用程序中使用它,但我收到此错误 **

X = []
sentences = list(review_df['text'])
for sen in sentences:
X.append(clean_text(sen))
y = review_df['Label']

y = np.array(list(map(lambda x: 1 if x=="fake" else 0, y)))

#使用循环神经网络 (LSTM) 进行文本分类

from keras.layers.recurrent import LSTM
model = Sequential()
embedding_layer = Embedding(vocab_size, 100, weights=[embedding_matrix], input_length=maxlen , 
trainable=False)
model.add(embedding_layer)
model.add(LSTM(128))

model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc'])
print(model.summary())

#训练模型

history = model.fit(X_train, y_train, batch_size=128, epochs=6, verbose=1, validation_split=0.2)
score = model.evaluate(X_test, y_test, verbose=1) 

#打印模型结果

print("Test Score:", score[0])
print("Test Accuracy:", score[1])

#对单个实例进行预测

instance = X[57]
print(instance)
instance = tokenizer.texts_to_sequences(instance)

flat_list = []
for sublist in instance:
for item in sublist:
flat_list.append(item)

flat_list = [flat_list]

instance = pad_sequences(flat_list, padding='post', maxlen=maxlen)
model.predict(instance)

#保存模型

import pickle
with open('model.pkl', 'wb') as f:
pickle.dump(model, f)

当我尝试保存模型时出现此错误:TypeError: can't pickle _thread.RLock objects 有什么办法可以解决这个错误

【问题讨论】:

    标签: python python-3.x machine-learning keras deep-learning


    【解决方案1】:

    尝试这样做:

    model_json = model.to_json()
    with open("my_model.json", "w") as json_file:
        json_file.write(model_json)
    

    【讨论】:

      【解决方案2】:

      您可以通过以下方式直接保存 keras 模型: model.save('path/xyz.h5') 建议将模型保存为H5格式并使用model.save() 也可以使用model.load()加载格式

      【讨论】:

        猜你喜欢
        • 2021-11-09
        • 2020-01-04
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-06
        • 2020-01-03
        • 1970-01-01
        相关资源
        最近更新 更多