عرض على TensorFlow.org | تشغيل في Google Colab | عرض على جيثب | تحميل دفتر |
ملخص
يوفر هذا الدليل قائمة بأفضل الممارسات لكتابة التعليمات البرمجية باستخدام TensorFlow 2 (TF2) ، وهو مكتوب للمستخدمين الذين انتقلوا مؤخرًا من TensorFlow 1 (TF1). راجع قسم الترحيل في الدليل للحصول على مزيد من المعلومات حول ترحيل رمز TF1 الخاص بك إلى TF2.
يثبت
قم باستيراد TensorFlow والتبعيات الأخرى للأمثلة الواردة في هذا الدليل.
import tensorflow as tf
import tensorflow_datasets as tfds
توصيات TensorFlow الاصطلاحية 2
أعد بناء الكود الخاص بك إلى وحدات أصغر
من الممارسات الجيدة إعادة تشكيل الكود الخاص بك إلى وظائف أصغر يتم استدعاؤها حسب الحاجة. للحصول على أفضل أداء ، يجب أن تحاول تزيين أكبر الكتل الحسابية التي يمكنك القيام بها في tf.function (لاحظ أن وظائف python المتداخلة التي تسمى دالة tf.function لا تتطلب زخارف منفصلة خاصة بها ، إلا إذا كنت تريد استخدام jit_compile مختلف إعدادات tf.function ). اعتمادًا على حالة الاستخدام الخاصة بك ، قد تكون هذه خطوات تدريب متعددة أو حتى حلقة التدريب بأكملها. بالنسبة لحالات استخدام الاستدلال ، قد يكون نموذجًا واحدًا تمريرة للأمام.
اضبط معدل التعلم الافتراضي لبعض tf.keras.optimizer s
بعض محسّني Keras لديهم معدلات تعلم مختلفة في TF2. إذا رأيت تغييرًا في سلوك التقارب لنماذجك ، فتحقق من معدلات التعلم الافتراضية.
لا توجد تغييرات على optimizers.SGD أو optimizers.Adam أو optimizers.RMSprop .
تغيرت معدلات التعلم الافتراضية التالية:
-
optimizers.Adagradمن0.01إلى0.001 -
optimizers.Adadeltaمن1.0إلى0.001 -
optimizers.Adamaxمن0.002إلى0.001 -
optimizers.Nadam. نظام من0.002إلى0.001
استخدم tf.Module s وطبقات Keras لإدارة المتغيرات
tf.Module s و tf.keras.layers.Layer variables الملائمة وخصائص المتغيرات القابلة trainable_variables ، والتي تجمع بشكل متكرر جميع المتغيرات التابعة. هذا يجعل من السهل إدارة المتغيرات محليًا إلى حيث يتم استخدامها.
ترث طبقات / نماذج Keras من tf.train.Checkpointable ويتم دمجها مع @tf.function ، مما يجعل من الممكن مباشرة نقطة فحص أو تصدير SavedModels من كائنات Keras. لا يتعين عليك بالضرورة استخدام Model.fit API في Keras للاستفادة من عمليات الدمج هذه.
اقرأ القسم الخاص بنقل التعلم والضبط في دليل Keras لمعرفة كيفية جمع مجموعة فرعية من المتغيرات ذات الصلة باستخدام Keras.
اجمع بين tf.data.Dataset و tf.function
تحتوي حزمة TensorFlow Datasets ( tfds ) على أدوات مساعدة لتحميل مجموعات البيانات المحددة مسبقًا ككائنات tf.data.Dataset . في هذا المثال ، يمكنك تحميل مجموعة بيانات MNIST باستخدام tfds :
datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test']
ثم قم بإعداد البيانات للتدريب:
- أعد قياس كل صورة.
- تبديل ترتيب الأمثلة.
- اجمع دفعات من الصور والتسميات.
BUFFER_SIZE = 10 # Use a much larger value for real code
BATCH_SIZE = 64
NUM_EPOCHS = 5
def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label
للإبقاء على المثال قصيرًا ، قم بقص مجموعة البيانات لإرجاع 5 دفعات فقط:
train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
test_data = mnist_test.map(scale).batch(BATCH_SIZE)
STEPS_PER_EPOCH = 5
train_data = train_data.take(STEPS_PER_EPOCH)
test_data = test_data.take(STEPS_PER_EPOCH)
image_batch, label_batch = next(iter(train_data))
2021-12-08 17:15:01.637157: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead.
استخدم تكرار Python المعتاد للتكرار على بيانات التدريب التي تناسب الذاكرة. خلاف ذلك ، فإن tf.data.Dataset هي أفضل طريقة لدفق بيانات التدريب من القرص. مجموعات البيانات هي عناصر متكررة (وليست مكررات) ، وتعمل تمامًا مثل متكررات بايثون الأخرى في التنفيذ الحثيث. يمكنك الاستفادة الكاملة من ميزات الجلب المسبق / التدفق غير المتزامن لمجموعة البيانات عن طريق تغليف الكود الخاص بك في tf.function ، والتي تحل محل تكرار Python بعمليات الرسم البياني المكافئة باستخدام AutoGraph.
@tf.function
def train(model, dataset, optimizer):
for x, y in dataset:
with tf.GradientTape() as tape:
# training=True is only needed if there are layers with different
# behavior during training versus inference (e.g. Dropout).
prediction = model(x, training=True)
loss = loss_fn(prediction, y)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
إذا كنت تستخدم Keras Model.fit API ، فلن تقلق بشأن تكرار مجموعة البيانات.
model.compile(optimizer=optimizer, loss=loss_fn)
model.fit(dataset)
استخدم حلقات تدريب Keras
إذا لم تكن بحاجة إلى مستوى منخفض من التحكم في عملية التدريب الخاصة بك ، فمن المستحسن استخدام أساليب fit المضمنة evaluate predict . توفر هذه الطرق واجهة موحدة لتدريب النموذج بغض النظر عن التنفيذ (متسلسل أو وظيفي أو مصنف فرعي).
تشمل مزايا هذه الطرق ما يلي:
- يقبلون مصفوفات Numpy ومولدات Python و
tf.data.Datasets. - يطبقون التنظيم وخسائر التنشيط تلقائيًا.
- أنها تدعم
tf.distributeحيث يظل رمز التدريب كما هو بغض النظر عن تكوين الأجهزة . - أنها تدعم الاستدعاء التعسفي كخسائر ومقاييس.
- أنها تدعم عمليات الاسترجاعات مثل
tf.keras.callbacks.TensorBoardوعمليات رد الاتصال المخصصة. - إنها فعالة ، تستخدم تلقائيًا الرسوم البيانية TensorFlow.
فيما يلي مثال لتدريب نموذج باستخدام مجموعة Dataset . للحصول على تفاصيل حول كيفية عمل ذلك ، تحقق من البرامج التعليمية .
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(10)
])
# Model is the full model w/o custom layers
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_data, epochs=NUM_EPOCHS)
loss, acc = model.evaluate(test_data)
print("Loss {}, Accuracy {}".format(loss, acc))
Epoch 1/5 5/5 [==============================] - 9s 7ms/step - loss: 1.5762 - accuracy: 0.4938 Epoch 2/5 2021-12-08 17:15:11.145429: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. 5/5 [==============================] - 0s 6ms/step - loss: 0.5087 - accuracy: 0.8969 Epoch 3/5 2021-12-08 17:15:11.559374: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. 5/5 [==============================] - 2s 5ms/step - loss: 0.3348 - accuracy: 0.9469 Epoch 4/5 2021-12-08 17:15:13.860407: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. 5/5 [==============================] - 0s 5ms/step - loss: 0.2445 - accuracy: 0.9688 Epoch 5/5 2021-12-08 17:15:14.269850: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. 5/5 [==============================] - 0s 6ms/step - loss: 0.2006 - accuracy: 0.9719 2021-12-08 17:15:14.717552: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. 5/5 [==============================] - 1s 4ms/step - loss: 1.4553 - accuracy: 0.5781 Loss 1.4552843570709229, Accuracy 0.578125 2021-12-08 17:15:15.862684: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead.
خصص التدريب واكتب الحلقة الخاصة بك
إذا كانت نماذج Keras تعمل من أجلك ، لكنك بحاجة إلى مزيد من المرونة والتحكم في خطوة التدريب أو حلقات التدريب الخارجية ، فيمكنك تنفيذ خطوات التدريب الخاصة بك أو حتى حلقات التدريب بالكامل. راجع دليل Keras حول تخصيص fit لمعرفة المزيد.
يمكنك أيضًا تنفيذ العديد من الأشياء مثل tf.keras.callbacks.Callback .
تتمتع هذه الطريقة بالعديد من المزايا المذكورة سابقًا ، ولكنها تمنحك التحكم في خطوة القطار وحتى الحلقة الخارجية.
هناك ثلاث خطوات لحلقة التدريب القياسية:
- كرر عبر منشئ Python أو
tf.data.Datasetللحصول على مجموعات من الأمثلة. - استخدم
tf.GradientTapeلتجميع التدرجات. - استخدم أحد
tf.keras.optimizersلتطبيق تحديثات الوزن على متغيرات النموذج.
يتذكر:
- قم دائمًا بتضمين حجة
trainingعلى طريقةcallللطبقات والنماذج المصنفة. - تأكد من استدعاء النموذج مع تعيين وسيطة
trainingبشكل صحيح. - اعتمادًا على الاستخدام ، قد لا توجد متغيرات النموذج حتى يتم تشغيل النموذج على دفعة من البيانات.
- تحتاج إلى التعامل يدويًا مع أشياء مثل خسائر التنظيم للنموذج.
ليست هناك حاجة لتشغيل مُهيِّئات متغيرة أو لإضافة تبعيات تحكم يدوي. تتعامل tf.function مع تبعيات التحكم التلقائي والتهيئة المتغيرة عند الإنشاء نيابة عنك.
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.BatchNormalization(),
tf.keras.layers.Dense(10)
])
optimizer = tf.keras.optimizers.Adam(0.001)
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
@tf.function
def train_step(inputs, labels):
with tf.GradientTape() as tape:
predictions = model(inputs, training=True)
regularization_loss=tf.math.add_n(model.losses)
pred_loss=loss_fn(labels, predictions)
total_loss=pred_loss + regularization_loss
gradients = tape.gradient(total_loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
for epoch in range(NUM_EPOCHS):
for inputs, labels in train_data:
train_step(inputs, labels)
print("Finished epoch", epoch)
2021-12-08 17:15:16.714849: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Finished epoch 0 2021-12-08 17:15:17.097043: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Finished epoch 1 2021-12-08 17:15:17.502480: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Finished epoch 2 2021-12-08 17:15:17.873701: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Finished epoch 3 Finished epoch 4 2021-12-08 17:15:18.344196: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead.
استفد من tf.function مع تدفق التحكم في Python
توفر tf.function طريقة لتحويل تدفق التحكم المعتمد على البيانات إلى معادلات وضع الرسم البياني مثل tf.cond و tf. tf.while_loop .
أحد الأماكن الشائعة حيث يظهر تدفق التحكم المعتمد على البيانات هو نماذج التسلسل. يلف tf.keras.layers.RNN خلية RNN ، مما يسمح لك بإلغاء التكرار بشكل ثابت أو ديناميكي. على سبيل المثال ، يمكنك إعادة تنفيذ ميزة إلغاء التسجيل الديناميكي على النحو التالي.
class DynamicRNN(tf.keras.Model):
def __init__(self, rnn_cell):
super(DynamicRNN, self).__init__(self)
self.cell = rnn_cell
@tf.function(input_signature=[tf.TensorSpec(dtype=tf.float32, shape=[None, None, 3])])
def call(self, input_data):
# [batch, time, features] -> [time, batch, features]
input_data = tf.transpose(input_data, [1, 0, 2])
timesteps = tf.shape(input_data)[0]
batch_size = tf.shape(input_data)[1]
outputs = tf.TensorArray(tf.float32, timesteps)
state = self.cell.get_initial_state(batch_size = batch_size, dtype=tf.float32)
for i in tf.range(timesteps):
output, state = self.cell(input_data[i], state)
outputs = outputs.write(i, output)
return tf.transpose(outputs.stack(), [1, 0, 2]), state
lstm_cell = tf.keras.layers.LSTMCell(units = 13)
my_rnn = DynamicRNN(lstm_cell)
outputs, state = my_rnn(tf.random.normal(shape=[10,20,3]))
print(outputs.shape)
(10, 20, 13)
اقرأ دليل tf.function للحصول على مزيد من المعلومات.
المقاييس والخسائر بأسلوب جديد
المقاييس والخسائر هي كائنات تعمل بلهفة وفي tf.function .
كائن الخسارة قابل للاستدعاء ، ويتوقع ( y_true ، y_pred ) كوسيطات:
cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
cce([[1, 0]], [[-1.0,3.0]]).numpy()
4.01815
استخدم المقاييس لجمع البيانات وعرضها
يمكنك استخدام tf.metrics لتجميع البيانات و tf.summary لتسجيل الملخصات وإعادة توجيهها إلى كاتب باستخدام مدير السياق. يتم إرسال الملخصات مباشرة إلى الكاتب مما يعني أنه يجب عليك تقديم قيمة step في موقع الاتصال.
summary_writer = tf.summary.create_file_writer('/tmp/summaries')
with summary_writer.as_default():
tf.summary.scalar('loss', 0.1, step=42)
استخدم tf.metrics لتجميع البيانات قبل تسجيلها كملخصات. المقاييس ذات الحالة ؛ يقومون بتجميع القيم وإرجاع نتيجة تراكمية عند استدعاء طريقة result (مثل Mean.result ). امسح القيم المتراكمة باستخدام Model.reset_states .
def train(model, optimizer, dataset, log_freq=10):
avg_loss = tf.keras.metrics.Mean(name='loss', dtype=tf.float32)
for images, labels in dataset:
loss = train_step(model, optimizer, images, labels)
avg_loss.update_state(loss)
if tf.equal(optimizer.iterations % log_freq, 0):
tf.summary.scalar('loss', avg_loss.result(), step=optimizer.iterations)
avg_loss.reset_states()
def test(model, test_x, test_y, step_num):
# training=False is only needed if there are layers with different
# behavior during training versus inference (e.g. Dropout).
loss = loss_fn(model(test_x, training=False), test_y)
tf.summary.scalar('loss', loss, step=step_num)
train_summary_writer = tf.summary.create_file_writer('/tmp/summaries/train')
test_summary_writer = tf.summary.create_file_writer('/tmp/summaries/test')
with train_summary_writer.as_default():
train(model, optimizer, dataset)
with test_summary_writer.as_default():
test(model, test_x, test_y, optimizer.iterations)
تصور الملخصات التي تم إنشاؤها عن طريق توجيه TensorBoard إلى دليل السجل الموجز:
tensorboard --logdir /tmp/summaries
استخدم tf.summary API لكتابة بيانات موجزة للتصور في TensorBoard. لمزيد من المعلومات ، اقرأ دليل tf.summary .
# Create the metrics
loss_metric = tf.keras.metrics.Mean(name='train_loss')
accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
@tf.function
def train_step(inputs, labels):
with tf.GradientTape() as tape:
predictions = model(inputs, training=True)
regularization_loss=tf.math.add_n(model.losses)
pred_loss=loss_fn(labels, predictions)
total_loss=pred_loss + regularization_loss
gradients = tape.gradient(total_loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
# Update the metrics
loss_metric.update_state(total_loss)
accuracy_metric.update_state(labels, predictions)
for epoch in range(NUM_EPOCHS):
# Reset the metrics
loss_metric.reset_states()
accuracy_metric.reset_states()
for inputs, labels in train_data:
train_step(inputs, labels)
# Get the metric results
mean_loss=loss_metric.result()
mean_accuracy = accuracy_metric.result()
print('Epoch: ', epoch)
print(' loss: {:.3f}'.format(mean_loss))
print(' accuracy: {:.3f}'.format(mean_accuracy))
2021-12-08 17:15:19.339736: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Epoch: 0 loss: 0.142 accuracy: 0.991 2021-12-08 17:15:19.781743: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Epoch: 1 loss: 0.125 accuracy: 0.997 2021-12-08 17:15:20.219033: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Epoch: 2 loss: 0.110 accuracy: 0.997 2021-12-08 17:15:20.598085: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead. Epoch: 3 loss: 0.099 accuracy: 0.997 Epoch: 4 loss: 0.085 accuracy: 1.000 2021-12-08 17:15:20.981787: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead.
أسماء مترية Keras
نماذج Keras متسقة بشأن التعامل مع الأسماء المترية. عند تمرير سلسلة في قائمة المقاييس ، يتم استخدام تلك السلسلة بالضبط name للمقياس. تظهر هذه الأسماء في كائن المحفوظات الذي model.fit ، وفي السجلات التي تم تمريرها إلى keras.callbacks . تم تعيينه على السلسلة التي مررتها في قائمة المقاييس.
model.compile(
optimizer = tf.keras.optimizers.Adam(0.001),
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics = ['acc', 'accuracy', tf.keras.metrics.SparseCategoricalAccuracy(name="my_accuracy")])
history = model.fit(train_data)
5/5 [==============================] - 1s 5ms/step - loss: 0.0963 - acc: 0.9969 - accuracy: 0.9969 - my_accuracy: 0.9969 2021-12-08 17:15:21.942940: W tensorflow/core/kernels/data/cache_dataset_ops.cc:768] The calling iterator did not fully read the dataset being cached. In order to avoid unexpected truncation of the dataset, the partially cached contents of the dataset will be discarded. This can happen if you have an input pipeline similar to `dataset.cache().take(k).repeat()`. You should use `dataset.take(k).cache().repeat()` instead.
history.history.keys()
dict_keys(['loss', 'acc', 'accuracy', 'my_accuracy'])
تصحيح
استخدم التنفيذ الحثيث لتشغيل التعليمات البرمجية خطوة بخطوة لفحص الأشكال وأنواع البيانات والقيم. تم تصميم واجهات برمجة تطبيقات معينة ، مثل tf.function و tf.keras وما إلى ذلك ، لاستخدام تنفيذ الرسم البياني للأداء وإمكانية النقل. عند تصحيح الأخطاء ، استخدم tf.config.run_functions_eagerly(True) لاستخدام التنفيذ الحثيث داخل هذا الرمز.
فمثلا:
@tf.function
def f(x):
if x > 0:
import pdb
pdb.set_trace()
x = x + 1
return x
tf.config.run_functions_eagerly(True)
f(tf.constant(1))
>>> f()
-> x = x + 1
(Pdb) l
6 @tf.function
7 def f(x):
8 if x > 0:
9 import pdb
10 pdb.set_trace()
11 -> x = x + 1
12 return x
13
14 tf.config.run_functions_eagerly(True)
15 f(tf.constant(1))
[EOF]
يعمل هذا أيضًا داخل نماذج Keras وواجهات برمجة التطبيقات الأخرى التي تدعم التنفيذ الحثيث:
class CustomModel(tf.keras.models.Model):
@tf.function
def call(self, input_data):
if tf.reduce_mean(input_data) > 0:
return input_data
else:
import pdb
pdb.set_trace()
return input_data // 2
tf.config.run_functions_eagerly(True)
model = CustomModel()
model(tf.constant([-2, -4]))
>>> call()
-> return input_data // 2
(Pdb) l
10 if tf.reduce_mean(input_data) > 0:
11 return input_data
12 else:
13 import pdb
14 pdb.set_trace()
15 -> return input_data // 2
16
17
18 tf.config.run_functions_eagerly(True)
19 model = CustomModel()
20 model(tf.constant([-2, -4]))
ملحوظات:
طرق
tf.keras.Modelمثلfitevaluatepredictبالتنفيذ كرسم بياني معtf.functionتحت الغطاء.عند استخدام
tf.keras.Model.compile، اضبطrun_eagerly = Trueلتعطيل منطقModelبحيث لا يتم تغليفهtf.function.استخدم
tf.data.experimental.enable_debug_modeلتمكين وضع التصحيح لـtf.data. اقرأ مستندات API لمزيد من التفاصيل.
لا تحتفظ tf.Tensors في الأشياء الخاصة بك
قد يتم إنشاء كائنات الموتر هذه إما في tf.function أو في سياق متحمس ، وتتصرف هذه الموترات بشكل مختلف. استخدم دائمًا tf.Tensor s للقيم الوسيطة فقط.
لتتبع الحالة ، استخدم tf.Variable s لأنها قابلة للاستخدام دائمًا من كلا السياقين. اقرأ دليل tf.Variable لمعرفة المزيد.
الموارد والقراءات الإضافية
اقرأ أدلة TF2 والبرامج التعليمية لمعرفة المزيد حول كيفية استخدام TF2.
إذا سبق لك استخدام TF1.x ، فيوصى بشدة بترحيل الرمز الخاص بك إلى TF2. اقرأ أدلة الترحيل لمعرفة المزيد.
عرض على TensorFlow.org
تشغيل في Google Colab
عرض على جيثب
تحميل دفتر