![]() | ![]() | ![]() | ![]() |
ברוכים הבאים למדריך המקיף לאשכולות משקל , חלק מערכת הכלים למיטוב המודל TensorFlow.
דף זה מתעד מקרי שימוש שונים ומראה כיצד להשתמש ב- API לכל אחד. לאחר שתדע אילו ממשקי API אתה זקוק, מצא את הפרמטרים ואת הפרטים ברמה הנמוכה במסמכי ה- API :
- אם ברצונך לראות את היתרונות של קיבוץ משקל ומה נתמך, עיין בסקירה הכללית .
- לקבלת דוגמה אחת מקצה לקצה, עיין בדוגמה של אשכול משקל .
במדריך זה מקרים על מקרי השימוש הבאים:
- הגדר מודל מקובץ.
- בדוק וערוק מחדש של מודל מקובץ.
- שפר את הדיוק של המודל המקובץ.
- לפריסה בלבד, עליך לנקוט בצעדים כדי לראות יתרונות דחיסה.
להכין
! pip install -q tensorflow-model-optimization
import tensorflow as tf
import numpy as np
import tempfile
import os
import tensorflow_model_optimization as tfmot
input_dim = 20
output_dim = 20
x_train = np.random.randn(1, input_dim).astype(np.float32)
y_train = tf.keras.utils.to_categorical(np.random.randn(1), num_classes=output_dim)
def setup_model():
model = tf.keras.Sequential([
tf.keras.layers.Dense(input_dim, input_shape=[input_dim]),
tf.keras.layers.Flatten()
])
return model
def train_model(model):
model.compile(
loss=tf.keras.losses.categorical_crossentropy,
optimizer='adam',
metrics=['accuracy']
)
model.summary()
model.fit(x_train, y_train)
return model
def save_model_weights(model):
_, pretrained_weights = tempfile.mkstemp('.h5')
model.save_weights(pretrained_weights)
return pretrained_weights
def setup_pretrained_weights():
model= setup_model()
model = train_model(model)
pretrained_weights = save_model_weights(model)
return pretrained_weights
def setup_pretrained_model():
model = setup_model()
pretrained_weights = setup_pretrained_weights()
model.load_weights(pretrained_weights)
return model
def save_model_file(model):
_, keras_file = tempfile.mkstemp('.h5')
model.save(keras_file, include_optimizer=False)
return keras_file
def get_gzipped_model_size(model):
# It returns the size of the gzipped model in bytes.
import os
import zipfile
keras_file = save_model_file(model)
_, zipped_file = tempfile.mkstemp('.zip')
with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:
f.write(keras_file)
return os.path.getsize(zipped_file)
setup_model()
pretrained_weights = setup_pretrained_weights()
הגדר מודל מקובץ
מקבצים דגם שלם (רציף ופונקציונלי)
טיפים לדיוק טוב יותר של המודל:
- עליך להעביר מודל שהוכשר מראש עם דיוק מקובל ל- API זה. אימון מודלים מאפס עם תוצאות אשכולות לדיוק תת-חלקי.
- במקרים מסוימים, לאשכול שכבות מסוימות יש השפעה מזיקה על דיוק המודל. סמן את האפשרות "אשכול כמה שכבות" כדי לראות כיצד לדלג על אשכול שכבות המשפיעות ביותר על הדיוק.
כדי לקבץ את כל השכבות, tfmot.clustering.keras.cluster_weights
את המודל tfmot.clustering.keras.cluster_weights
.
import tensorflow_model_optimization as tfmot
cluster_weights = tfmot.clustering.keras.cluster_weights
CentroidInitialization = tfmot.clustering.keras.CentroidInitialization
clustering_params = {
'number_of_clusters': 3,
'cluster_centroids_init': CentroidInitialization.DENSITY_BASED
}
model = setup_model()
model.load_weights(pretrained_weights)
clustered_model = cluster_weights(model, **clustering_params)
clustered_model.summary()
Model: "sequential_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= cluster_dense_2 (ClusterWeig (None, 20) 423 _________________________________________________________________ cluster_flatten_2 (ClusterWe (None, 20) 0 ================================================================= Total params: 423 Trainable params: 23 Non-trainable params: 400 _________________________________________________________________
מקבצים כמה שכבות (מודלים רציפים ופונקציונליים)
טיפים לדיוק טוב יותר של המודל:
- עליך להעביר מודל שהוכשר מראש עם דיוק מקובל ל- API זה. אימון מודלים מאפס עם תוצאות אשכולות לדיוק משנה.
-
tf.keras.layers.Dense
שכבות מאוחרות יותר עם פרמטרים מיותרים יותר (למשלtf.keras.layers.Dense
,tf.keras.layers.Conv2D
), בניגוד לשכבות המוקדמות. - הקפיאו שכבות מוקדמות לפני השכבות המקובצות במהלך כוונון עדין. התייחס למספר השכבות הקפואות כהיפרפרמטר. מבחינה אמפירית, הקפאת רוב השכבות המוקדמות היא אידיאלית עבור ממשק ה- API לאשכולות הנוכחי.
- הימנע מקבץ שכבות קריטיות (למשל מנגנון קשב).
עוד : מסמכי ה- API של tfmot.clustering.keras.cluster_weights
מספקים פרטים על אופן הגדרת תצורת האשכול לכל שכבה.
# Create a base model
base_model = setup_model()
base_model.load_weights(pretrained_weights)
# Helper function uses `cluster_weights` to make only
# the Dense layers train with clustering
def apply_clustering_to_dense(layer):
if isinstance(layer, tf.keras.layers.Dense):
return cluster_weights(layer, **clustering_params)
return layer
# Use `tf.keras.models.clone_model` to apply `apply_clustering_to_dense`
# to the layers of the model.
clustered_model = tf.keras.models.clone_model(
base_model,
clone_function=apply_clustering_to_dense,
)
clustered_model.summary()
Model: "sequential_3" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= cluster_dense_3 (ClusterWeig (None, 20) 423 _________________________________________________________________ flatten_3 (Flatten) (None, 20) 0 ================================================================= Total params: 423 Trainable params: 23 Non-trainable params: 400 _________________________________________________________________
בדוק וערוק מחדש של מודל מקובץ
מקרה השימוש שלך: קוד זה נחוץ רק לפורמט הדגם HDF5 (לא משקולות HDF5 או פורמטים אחרים).
# Define the model.
base_model = setup_model()
base_model.load_weights(pretrained_weights)
clustered_model = cluster_weights(base_model, **clustering_params)
# Save or checkpoint the model.
_, keras_model_file = tempfile.mkstemp('.h5')
clustered_model.save(keras_model_file, include_optimizer=True)
# `cluster_scope` is needed for deserializing HDF5 models.
with tfmot.clustering.keras.cluster_scope():
loaded_model = tf.keras.models.load_model(keras_model_file)
loaded_model.summary()
WARNING:tensorflow:No training configuration found in the save file, so the model was *not* compiled. Compile it manually. Model: "sequential_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= cluster_dense_4 (ClusterWeig (None, 20) 423 _________________________________________________________________ cluster_flatten_4 (ClusterWe (None, 20) 0 ================================================================= Total params: 423 Trainable params: 23 Non-trainable params: 400 _________________________________________________________________
שפר את הדיוק של המודל המקובץ
למקרה השימוש הספציפי שלך, יש טיפים שתוכל לשקול:
אתחול של Centroid ממלא תפקיד מפתח בדיוק הסופי של המודל. באופן כללי, אתחול ליניארי עולה על הצפיפות והאתחול האקראי מכיוון שהוא אינו נוטה להחמיץ משקלים גדולים. עם זאת, אתחול צפיפות נצפה כדי לתת דיוק טוב יותר למקרה של שימוש במקבצים מעטים מאוד על משקלים עם התפלגויות דו-מודליות.
הגדר קצב למידה נמוך מזה המשמש באימונים בעת כוונון עדין של המודל המקובץ.
לקבלת רעיונות כלליים לשיפור דיוק המודל, חפש טיפים למקרי השימוש שלך תחת "הגדר מודל מקובץ".
פְּרִיסָה
דגם ייצוא עם דחיסת גודל
טעות נפוצה : הן strip_clustering
והן החלת אלגוריתם דחיסה סטנדרטי (למשל באמצעות gzip) נחוצים כדי לראות את יתרונות הדחיסה של אשכולות.
model = setup_model()
clustered_model = cluster_weights(model, **clustering_params)
clustered_model.compile(
loss=tf.keras.losses.categorical_crossentropy,
optimizer='adam',
metrics=['accuracy']
)
clustered_model.fit(
x_train,
y_train
)
final_model = tfmot.clustering.keras.strip_clustering(clustered_model)
print("final model")
final_model.summary()
print("\n")
print("Size of gzipped clustered model without stripping: %.2f bytes"
% (get_gzipped_model_size(clustered_model)))
print("Size of gzipped clustered model with stripping: %.2f bytes"
% (get_gzipped_model_size(final_model)))
1/1 [==============================] - 0s 984us/step - loss: 16.1181 - accuracy: 0.0000e+00 final model Model: "sequential_5" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_5 (Dense) (None, 20) 420 _________________________________________________________________ flatten_5 (Flatten) (None, 20) 0 ================================================================= Total params: 420 Trainable params: 420 Non-trainable params: 0 _________________________________________________________________ Size of gzipped clustered model without stripping: 1809.00 bytes Size of gzipped clustered model with stripping: 1399.00 bytes