การบันทึกและโหลดไปป์ไลน์ด้วย joblib
ผู้เรียนจะทำให้ Pipeline ที่ฝึกแล้วอยู่ในรูปแบบอนุกรมและบันทึกลงดิสก์ด้วย joblib.dump จากนั้นโหลดกลับในเซสชัน Python ใหม่เพื่อทำนายโดยไม่ต้องฝึกซ้ำ
การบันทึกและโหลดไปป์ไลน์ด้วย joblib เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Persist a Trained Pipeline?
Training a machine learning pipeline can take minutes or hours. Once fitted, you want to save it to disk so you can reload it later for predictions without re-training. Persistence is also essential for deployment: you train on a development machine and serve predictions on a production server. The saved file must include both the preprocessing steps and the model weights.
Two Serialisation Options: pickle and joblib
Python's built-in pickle module can serialise any Python object, including sklearn pipelines. joblib is a third-party library (bundled with scikit-learn) that is generally preferred for ML objects because it is more efficient for large NumPy arrays — using memory mapping instead of copying — and can compress the output file automatically.
import pickle
import joblib
# Both approaches work; joblib is recommended for sklearn objects
print('pickle version:', pickle.HIGHEST_PROTOCOL)
import sklearn
print('sklearn version:', sklearn.__version__)Saving with joblib.dump
joblib.dump(obj, filename) serialises the pipeline to a file. You can optionally set compress=3 to use zlib compression (levels 1-9; 3 balances speed and size). The function returns a list of files created. For most pipelines, a single .pkl or .joblib file is created.
import joblib
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', LogisticRegression(C=1.0, max_iter=200))
])
pipe.fit(X, y)
# Save
joblib.dump(pipe, '/tmp/iris_pipeline.joblib')
print('Pipeline saved!')Loading with joblib.load
joblib.load(filename) deserialises the pipeline back into a Python object. The loaded pipeline is identical to the original: it has the same fitted scaler parameters (mean, variance) and the same model weights. You can call predict, predict_proba, or score immediately without re-fitting.
import joblib
from sklearn.datasets import load_iris
import numpy as np
X, y = load_iris(return_X_y=True)
# Load the saved pipeline
loaded_pipe = joblib.load('/tmp/iris_pipeline.joblib')
# Predict and verify
predictions = loaded_pipe.predict(X[:5])
print('Predictions:', predictions)
print('Test accuracy:', loaded_pipe.score(X, y).round(4))Verifying Round-Trip Fidelity
After loading, confirm that the loaded pipeline produces identical predictions to the original. Any mismatch indicates a serialisation bug or a version incompatibility. A simple check is to compare predictions element-wise using np.array_equal.
import joblib
import numpy as np
from sklearn.datasets import load_iris
X, _ = load_iris(return_X_y=True)
# Reload and compare
loaded = joblib.load('/tmp/iris_pipeline.joblib')
# Reload the original reference predictions
# (in practice, save original predictions before reload)
original_preds = loaded.predict(X) # use loaded as reference
loaded2 = joblib.load('/tmp/iris_pipeline.joblib')
reloaded_preds = loaded2.predict(X)
print('Predictions match:', np.array_equal(original_preds, reloaded_preds))Compression Options in joblib
Large pipelines (e.g., with RandomForest of 1000 trees) can be hundreds of MB. Use joblib.dump(pipe, path, compress=3) to compress on the fly. Alternatively, specify the compressor explicitly: compress=('zlib', 3) or compress=('lz4', 1) for maximum speed. LZ4 is the fastest; zlib gives smaller files but is slower.
import joblib
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
import os
X, y = load_iris(return_X_y=True)
pipe = Pipeline([('sc', StandardScaler()), ('lr', LogisticRegression())]).fit(X, y)
# Uncompressed
joblib.dump(pipe, '/tmp/pipe_raw.joblib')
# Compressed
joblib.dump(pipe, '/tmp/pipe_compressed.joblib', compress=3)
print('Raw size:', os.path.getsize('/tmp/pipe_raw.joblib'), 'bytes')
print('Compressed size:', os.path.getsize('/tmp/pipe_compressed.joblib'), 'bytes')Using pickle as an Alternative
If joblib is not available, pickle works for sklearn pipelines. Use binary mode ('rb'/'wb') when opening the file. For small models or scripted one-off tools, pickle is perfectly fine; for production systems handling large NumPy arrays, joblib is strongly preferred.
import pickle
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
pipe = Pipeline([('sc', StandardScaler()), ('lr', LogisticRegression())]).fit(X, y)
# Save with pickle
with open('/tmp/model.pkl', 'wb') as f:
pickle.dump(pipe, f)
# Load with pickle
with open('/tmp/model.pkl', 'rb') as f:
loaded = pickle.load(f)
print('Loaded score:', loaded.score(X, y).round(4))Version Compatibility Warnings
A critical production concern: a pipeline pickled with scikit-learn 1.2 may not load correctly in scikit-learn 1.5. Always record the library versions used at training time in a metadata file alongside the saved model. Use pip freeze > requirements.txt or record versions programmatically and store them next to the model file.
import sklearn
import numpy as np
import json
import os
metadata = {
'sklearn_version': sklearn.__version__,
'numpy_version': np.__version__,
'model_file': 'iris_pipeline.joblib'
}
with open('/tmp/model_metadata.json', 'w') as f:
json.dump(metadata, f, indent=2)
print(json.dumps(metadata, indent=2))Loading a Pipeline in a Production Script
In a production service, the workflow is: load the pipeline once at startup (not per request), receive input features, preprocess with the pipeline's built-in transforms, and return predictions. Because the pipeline includes all preprocessing, the serving code does not need to know about scaling, encoding, or PCA — all of that is encapsulated in the saved object.
import joblib
import numpy as np
# At startup (once)
model = joblib.load('/tmp/iris_pipeline.joblib')
def predict(sepal_length, sepal_width, petal_length, petal_width):
features = np.array([[sepal_length, sepal_width, petal_length, petal_width]])
label = model.predict(features)[0]
proba = model.predict_proba(features)[0]
return {'label': int(label), 'confidence': round(float(proba.max()), 4)}
result = predict(5.1, 3.5, 1.4, 0.2)
print('Prediction result:', result)Security Considerations with Pickled Models
Never load a pickle file from an untrusted source. Pickle files can execute arbitrary code on loading — this is a fundamental Python security constraint. For sharing models externally, consider format-specific safer alternatives: ONNX for cross-framework serialisation, or joblib files shared only within trusted infrastructure. Always verify the file checksum before loading.
import hashlib
def file_sha256(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(65536), b''):
h.update(chunk)
return h.hexdigest()
checksum = file_sha256('/tmp/iris_pipeline.joblib')
print('Model SHA-256:', checksum)
# In production: compare this checksum with the one stored in your model registryQuick Load-Predict Sanity Test
A final best practice: include a short sanity test script in your model package that loads the pipeline, runs a known input, and asserts the expected output. Run this test in your CI/CD pipeline every time the model is promoted to production, confirming the file was not corrupted and the environment is compatible.
import joblib
import numpy as np
# Sanity test
model = joblib.load('/tmp/iris_pipeline.joblib')
# Known input (setosa): sepal_length=5.1, sepal_width=3.5, petal_length=1.4, petal_width=0.2
X_test = np.array([[5.1, 3.5, 1.4, 0.2]])
pred = model.predict(X_test)[0]
# Iris class 0 = setosa
assert pred == 0, f'Expected setosa (0) but got {pred}'
print('Sanity test PASSED — model predicts setosa correctly.')Quick Check
Test your understanding of saving and loading pipelines from this lesson.
Lesson Recap
In this lesson you learned: joblib.dump and joblib.load save and restore a complete fitted pipeline including all preprocessing parameters, always record library versions alongside the saved model to ensure reproducible loading, and never load pickle files from untrusted sources as they can execute arbitrary code. Next up we tackle imbalanced datasets — detecting class imbalance and understanding why accuracy is a misleading metric in that setting.
เรียนรู้ Python ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “การบันทึกและโหลดไปป์ไลน์ด้วย joblib” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การบันทึกและโหลดไปป์ไลน์ด้วย joblib” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การบันทึกและโหลดไปป์ไลน์ด้วย joblib”
ผู้เรียนจะทำให้ Pipeline ที่ฝึกแล้วอยู่ในรูปแบบอนุกรมและบันทึกลงดิสก์ด้วย joblib.dump จากนั้นโหลดกลับในเซสชัน Python ใหม่เพื่อทำนายโดยไม่ต้องฝึกซ้ำ คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การบันทึกและโหลดไปป์ไลน์ด้วย joblib” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม
ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างไปป์ไลน์แรกของคุณ: ตัวปรับมาตราส่วนและตัวจำแนก
- ColumnTransformer ภายในไปป์ไลน์
- การตรวจสอบไขว้และค้นหาแบบกริดสำหรับไปป์ไลน์ทั้งหมด
- การบันทึกและโหลดไปป์ไลน์ด้วย joblib