TF2.0張量及其操作、numpy兼容、GPU加速 (tensorflow2.0官方教程翻譯)
最全TensorFlow2.0學習路線 www.mashangxue123.com
這是一個基礎入門的TensorFlow教程,展示了如何:
- 導入所需的包
- 創建和使用張量
- 使用GPU加速
- 演示
tf.data.Dataset
from __future__ import absolute_import, division, print_function
1. 導入TensorFlow
要開始,請導入tensorflow模塊。從TensorFlow 2.0開始,默認情況下用會啟用Eager execution,這使得TensorFlow能夠實現更加互動的前端,我們將在稍後討論這些細節。
import tensorflow as tf
2. 張量
張量是一個多維數組,與NumPy的 ndarray
對象類似,tf.Tensor
對象具有數據類型和形狀,此外,tf.Tensor
可以駐留在加速器內存中(如GPU)。TensorFlow提供了豐富的操作庫((tf.add, tf.matmul, tf.linalg.inv 等),它們使用和生成tf.Tensor
。這些操作會自動轉換本機Python類型,例如:
print(tf.add(1, 2))
print(tf.add([1, 2], [3, 4]))
print(tf.square(5))
print(tf.reduce_sum([1, 2, 3]))
# 操作符重載也支持
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
有一個形狀和數據類型:
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>
NumPy數組和 tf.Tensor
之間最明顯的區別是:
- 張量可以有加速器內存(如GPU,TPU)支持。
- 張量是不可改變的。
2.1 NumPy兼容性
在TensorFlow的 tf.Tensor
和NumPy的 ndarray
之間轉換很容易:
- TensorFlow操作自動將NumPy ndarray轉換為Tensor
- NumPy操作自動將Tensor轉換為NumPy ndarray
使用.numpy()
方法將張量顯式轉換為NumPy ndarrays
。這些轉換通常很便宜,因為如果可能的話,數組和tf.Tensor
共享底層的內存表示。但是,共享底層表示並不總是可行的,因為tf.Tensor
可以託管在GPU內存中,而NumPy陣列總是由主機內存支持,並且轉換涉及從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.]]
3. GPU加速
使用GPU進行計算可以加速許多TensorFlow操作,如果沒有任何注釋,TensorFlow會自動決定是使用GPU還是CPU進行操作,如果有必要,可以複製CPU和GPU內存之間的張量,操作產生的張量通常由執行操作的設備的存儲器支持,例如:
x = tf.random.uniform([3, 3])
print("Is there a GPU available: "),
print(tf.test.is_gpu_available())
print("Is the Tensor on GPU #0: "),
print(x.device.endswith(GPU:0))
3.1 設備名稱
Tensor.device
屬性提供託管張量內容的設備的完全限定字元串名稱。此名稱編碼許多詳細信息,例如正在執行此程序的主機的網路地址的標識符以及該主機中的設備。這是分散式執行TensorFlow程序所必需的。如果張量位於主機上的第N個GPU上,則字元串以 GPU:<N>
結尾。
3.2 顯式設備放置
在TensorFlow中,placement (放置)指的是如何分配(放置)設備以執行各個操作,如上所述,如果沒有提供明確的指導,TensorFlow會自動決定執行操作的設備,並在需要時將張量複製到該設備。但是,可以使用 tf.device
上下文管理器將TensorFlow操作顯式放置在特定設備上,例如:
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.test.is_gpu_available():
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: 88.60ms
4. 數據集
本節使用 tf.data.Dataset API 構建管道,以便為模型提供數據。
tf.data.Dataset
API用於從簡單,可重複使用的部分構建高性能,複雜的輸入管道,這些部分將為模型的訓練或評估循環提供支持。
4.1 創建源數據集
使用其中一個工廠函數(如 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)
4.2 應用轉換
使用 map
, batch
, 和 shuffle
等轉換函數將轉換應用於數據集記錄。
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)
4.3 迭代(Iterate)
tf.data.Dataset
對象支持迭代循環:
print(Elements of ds_tensors:)
for x in ds_tensors:
print(x)
print(
Elements in ds_file:)
for x in ds_file:
print(x)
Elements of ds_tensors:
tf.Tensor([1 9], shape=(2,), dtype=int32)
tf.Tensor([ 4 25], shape=(2,), dtype=int32)
tf.Tensor([16 36], shape=(2,), dtype=int32)
Elements in ds_file:
tf.Tensor([bLine 1 bLine 2], shape=(2,), dtype=string)
tf.Tensor([bLine 3 b ], shape=(2,), dtype=string)
最新版本:https://www.mashangxue123.com/tensorflow/tf2-tutorials-eager-basics.html
英文版本:https://tensorflow.google.cn/alpha/tutorials/eager/basics最全TensorFlow2.0學習路線 www.mashangxue123.com
推薦閱讀: