![]() | ![]() | ![]() | ![]() |
זהו מדריך מבוא של TensorFlow המראה כיצד:
- ייבא את החבילה הנדרשת
- צרו והשתמשו בטנזורים
- השתמש בהאצת GPU
tf.data.Dataset
ייבא את TensorFlow
כדי להתחיל, ייבא את מודול tensorflow
. החל מ- TensorFlow 2, ביצוע להוט מופעל כברירת מחדל. זה מאפשר חזית אינטראקטיבית יותר ל- TensorFlow, שפרטיה נדון בהמשך.
import tensorflow as tf
טנזורים
טנסור הוא מערך רב מימדי. בדומה לאובייקטים ndarray
tf.Tensor
, לאובייקטים של tf.Tensor
יש סוג נתונים וצורה. בנוסף, tf.Tensor
s יכול להתגורר בזיכרון מאיץ (כמו GPU). TensorFlow מציעה ספרייה עשירה של פעולות ( tf.add , tf.matmul , tf.linalg.inv וכו ') הצורכות ומייצרות tf.Tensor
. tf.Tensor
s. פעולות אלה ממירות אוטומטית סוגי פיתון מקוריים, למשל:
print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))
# Operator overloading is also supported
print(tf.square(2) + tf.square(3))
tf.Tensor(3, shape=(), dtype=int32) tf.Tensor([4 6], shape=(2,), dtype=int32) tf.Tensor(25, shape=(), dtype=int32) tf.Tensor(6, shape=(), dtype=int32) tf.Tensor(13, shape=(), dtype=int32)
לכל tf.Tensor
יש צורה tf.Tensor
נתונים:
x = tf.matmul([[1]], [[2, 3]])
print(x)
print(x.shape)
print(x.dtype)
tf.Tensor([[2 3]], shape=(1, 2), dtype=int32) (1, 2) <dtype: 'int32'>
ההבדלים הברורים ביותר בין מערכי tf.Tensor
ו- tf.Tensor
. tf.Tensor
הם:
- ניתן לגבות טנזורים בזיכרון מאיץ (כמו GPU, TPU).
- המשתנים אינם ניתנים לשינוי.
תאימות NumPy
המרה בין TensorFlow tf.Tensor
s ו- ndarray
קלה:
- פעולות TensorFlow ממירות באופן אוטומטי מערכי NumPy ל- Tensors.
- פעולות NumPy ממירות באופן אוטומטי Tensors ל- NumPy ndarrays.
טנזורים מומרים במפורש ל- NumPy ndarrays בשיטת .numpy()
שלהם. המרות אלו בדרך כלל זולות מכיוון tf.Tensor
ו- tf.Tensor
חולקים את ייצוג הזיכרון הבסיסי, אם אפשר. עם זאת, שיתוף הייצוג הבסיסי לא תמיד אפשרי מכיוון tf.Tensor
עשוי להתארח בזיכרון GPU בעוד tf.Tensor
מגובים תמיד בזיכרון המארח, וההמרה כוללת העתק מ- GPU לזיכרון המארח.
import numpy as np
ndarray = np.ones([3, 3])
print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)
print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))
print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())
TensorFlow operations convert numpy arrays to Tensors automatically tf.Tensor( [[42. 42. 42.] [42. 42. 42.] [42. 42. 42.]], shape=(3, 3), dtype=float64) And NumPy operations convert Tensors to numpy arrays automatically [[43. 43. 43.] [43. 43. 43.] [43. 43. 43.]] The .numpy() method explicitly converts a Tensor to a numpy array [[42. 42. 42.] [42. 42. 42.] [42. 42. 42.]]
האצת GPU
פעולות רבות של TensorFlow מואצות באמצעות GPU לחישוב. ללא שום הערות, TensorFlow מחליט אוטומטית אם להשתמש ב- GPU או ב- CPU לצורך פעולה - העתקת הטנסור בין זיכרון ה- CPU ל- GPU, במידת הצורך. טנזורים המיוצרים על ידי פעולה מגובים בדרך כלל בזיכרון המכשיר עליו בוצעה הפעולה, למשל:
x = tf.random.uniform([3, 3])
print("Is there a GPU available: "),
print(tf.config.experimental.list_physical_devices("GPU"))
print("Is the Tensor on GPU #0: "),
print(x.device.endswith('GPU:0'))
Is there a GPU available: [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')] Is the Tensor on GPU #0: True
שמות מכשירים
המאפיין Tensor.device
מספק שם מחרוזת מוסמך לחלוטין של המכשיר המארח את תוכן הטנסור. שם זה מקודד פרטים רבים, כגון מזהה של כתובת הרשת של המארח עליו פועלת תוכנית זו והמכשיר בתוך אותו מארח. זה נדרש לביצוע מבוזר של תוכנית TensorFlow. המחרוזת מסתיימת ב- GPU:<N>
אם הטנסור ממוקם על ה- GPU ה- N
במארח.
מיקום מכשיר מפורש
ב- TensorFlow, מיקום מתייחס לאופן בו מוקצות (ממוקמות) מכשיר לביצוע של פעולות בודדות. כאמור, כאשר אין הנחיות מפורשות, TensorFlow מחליט אוטומטית איזה מכשיר לבצע פעולה ומעתיק טנסורים למכשיר זה, במידת הצורך. עם זאת, ניתן למקם במפורש פעולות TensorFlow במכשירים ספציפיים באמצעות מנהל ההקשר tf.device
, למשל:
import time
def time_matmul(x):
start = time.time()
for loop in range(10):
tf.matmul(x, x)
result = time.time()-start
print("10 loops: {:0.2f}ms".format(1000*result))
# Force execution on CPU
print("On CPU:")
with tf.device("CPU:0"):
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("CPU:0")
time_matmul(x)
# Force execution on GPU #0 if available
if tf.config.experimental.list_physical_devices("GPU"):
print("On GPU:")
with tf.device("GPU:0"): # Or GPU:1 for the 2nd GPU, GPU:2 for the 3rd etc.
x = tf.random.uniform([1000, 1000])
assert x.device.endswith("GPU:0")
time_matmul(x)
On CPU: 10 loops: 102.06ms On GPU: 10 loops: 231.87ms
מערכי נתונים
סעיף זה משתמש בממשק ה- API tf.data.Dataset
לבניית צינור להזנת נתונים למודל שלך. ממשק ה- APItf.data.Dataset
משמש לבניית צינורות קלט מורכבים ומורכביםtf.data.Dataset
,tf.data.Dataset
לשימוש חוזר, שיאכילו את לולאות ההדרכה או ההערכה של המודל שלך.
צור Dataset
צור מערך מקור באמצעות אחת מפונקציות המפעל כמו Dataset.from_tensors
, Dataset.from_tensor_slices
, או באמצעות אובייקטים שקוראים מקבצים כמו TextLineDataset
או TFRecordDataset
. עיין במדריך למערכי הנתונים של TensorFlow למידע נוסף.
ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
# Create a CSV file
import tempfile
_, filename = tempfile.mkstemp()
with open(filename, 'w') as f:
f.write("""Line 1
Line 2
Line 3
""")
ds_file = tf.data.TextLineDataset(filename)
החל שינויים
השתמש בפונקציות הטרנספורמציה כמו map
, batch
shuffle
כדי להחיל טרנספורמציות על רשומות מערך הנתונים.
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)
לְחַזֵר
אובייקטיםtf.data.Dataset
תומכים באיטרציה לולאה על רשומות:
print('Elements of ds_tensors:')
for x in ds_tensors:
print(x)
print('\nElements in ds_file:')
for x in ds_file:
print(x)
Elements of ds_tensors: tf.Tensor([1 4], shape=(2,), dtype=int32) tf.Tensor([16 9], shape=(2,), dtype=int32) tf.Tensor([25 36], shape=(2,), dtype=int32) Elements in ds_file: tf.Tensor([b'Line 1' b'Line 2'], shape=(2,), dtype=string) tf.Tensor([b'Line 3' b' '], shape=(2,), dtype=string)