[英]After building a model in Python, how do I save the model so I could shut down my computer and work on it the next day?
比如說,我已經用 Python 構建了一個回歸模型,如下:
from sklearn import linear_model
model = linear_model.LogisticRegression().fit(X_train, Y_train)
如何保存我構建的“模型”,以便我可以關閉計算機並在第二天繼續工作,而不必重新運行代碼來再次獲取“模型”?
我之所以這么問是因為我的數據集非常龐大,而且需要很長時間才能重新運行才能再次獲得模型。
這是一個序列化問題,一個非常簡單的方法是使用pickle
模塊。 以下片段顯示了如何保存和加載 Python 對象。
保存:
import pickle
with open("YOUR_FILE_NAME_HERE.pkl", 'wb') as file:
pickle.dump(model, file)
裝載:
# Import all your relevant libraries first
from sklearn import linear_model
...
import pickle
with open("YOUR_FILE_NAME_HERE.pkl", 'rb') as file:
model = pickle.load(file)
這個想法本質上是創建對象( model
)的文件表示,並以可以按需解釋和加載的方式將其保存到文件中。 這可以通過許多不同的方式實現,但 Python 最簡單的方法是使用 pickle,它創建對象以及所有關聯對象和模塊的二進制表示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.