導入TensorFlow
運行tensorflow程序,需要導入tensorflow模塊。
從TensorFlow 2.0開始,默認情況下會啟用eager模式執行。 這為TensorFlow提供了一個更加互動的前端節。
from __future__ import absolute_import, division, print_function
import tensorflow as tf
1 Tensors
張量是一個多維數組。 與NumPy ndarray對象類似,tf.Tensor對象具有數據類型和形狀。 此外,tf.Tensors可以駐留在加速器內存中(如GPU)。 TensorFlow提供了豐富的操作庫(tf.add,tf.matmul,tf.linalg.inv等),它們使用和生成tf.Tensors。 這些操作會自動轉換原生Python類型,例如:
print(tf.add(1,2))
print(tf.add([3,8], [2,5]))
print(tf.square(6))
print(tf.reduce_sum([7,8,9]))
print(tf.square(3)+tf.square(4))
tf.Tensor(3, shape=(), dtype=int32)
tf.Tensor([ 5 13], shape=(2,), dtype=int32)
tf.Tensor(36, shape=(), dtype=int32)
tf.Tensor(24, shape=(), dtype=int32)
tf.Tensor(25, shape=(), dtype=int32)
每個Tensor都有形狀和類型
x = tf.matmul([[3], [6]], [[2]])
print(x)
print(x.shape)
print(x.dtype)
tf.Tensor(
[[ 6]
[12]], shape=(2, 1), dtype=int32)
(2, 1)
NumPy數組和tf.Tensors之間最明顯的區別是:
張量可以由加速器內存(如GPU,TPU)支持。
張量是不可變的。
NumPy兼容性
在TensorFlow tf.Tensors和NumPy ndarray之間轉換很容易:
TensorFlow操作自動將NumPy ndarrays轉換為Tensors。
NumPy操作自動將Tensors轉換為NumPy ndarrays。
使用.numpy()方法將張量顯式轉換為NumPy ndarrays。 這些轉換通常很容易的,因為如果可能,array和tf.Tensor共享底層內存表示。 但是,共享底層表示並不總是可行的,因為tf.Tensor可以托管在GPU內存中,而NumPy陣列總是由主機內存支持,並且轉換涉及從GPU到主機內存的復制。
import numpy as np
ndarray = np.ones([2,2])
tensor = tf.multiply(ndarray, 36)
print(tensor)
# 用np.add對tensorflow進行加運算
print(np.add(tensor, 1))
# 轉換為numpy類型
print(tensor.numpy())
tf.Tensor(
[[36. 36.]
[36. 36.]], shape=(2, 2), dtype=float64)
[[37. 37.]
[37. 37.]]
[[36. 36.]
[36. 36.]]
2 GPU加速
使用GPU進行計算可以加速許多TensorFlow操作。 如果沒有任何注釋,TensorFlow會自動決定是使用GPU還是CPU進行操作 - 如有必要,可以復制CPU和GPU內存之間的張量。 由操作產生的張量通常由執行操作的設備的存儲器支持,例如:
x = tf.random.uniform([3, 3])
print('Is GPU availabel:')
print(tf.test.is_gpu_available())
print('Is the Tensor on gpu #0:')
print(x.device.endswith('GPU:0'))
Is GPU availabel:
False
Is the Tensor on gpu #0:
False
設備名稱
Tensor.device屬性提供托管張量內容的設備的完全限定字符串名稱。 此名稱編碼許多詳細信息,例如正在執行此程序的主機的網絡地址的標識符以及該主機中的設備。 這是分布式執行TensorFlow程序所必需的。 如果張量位於主機上的第N個GPU上,則字符串以GPU結尾:。
顯式設備放置(Placement)
在TensorFlow中,放置指的是如何分配(放置)設備以執行各個操作。 如上所述,如果沒有提供明確的指導,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.2}ms'.format(1000*result))
# 強制使用CPU
print('On CPU:')
with tf.device('CPU:0'):
x = tf.random.uniform([1000, 1000])
# 使用斷言驗證當前是否為CPU0
assert x.device.endswith('CPU:0')
time_matmul(x)
# 如果存在GPU,強制使用GPU
if tf.test.is_gpu_available():
print('On GPU:')
with tf.device.endswith('GPU:0'):
x = tf.random.uniform([1000, 1000])
# 使用斷言驗證當前是否為GPU0
assert x.device.endswith('GPU:0')
time_matmul(x)
On CPU:
10 loops: 1.2e+02ms
3 數據集
本節使用tf.data.Dataset API構建管道,以便為模型提供數據。 tf.data.Dataset API用於從簡單,可重復使用的部分構建高性能,復雜的輸入管道,這些部分將為模型的培訓或評估循環提供支持。
創建源數據集無錫人流多少錢 http://www.bhnnk120.com/
使用其中一個工廠函數(如Dataset.from_tensors,Dataset.from_tensor_slices)或使用從TextLineDataset或TFRecordDataset等文件讀取的對象創建源數據集。 有關詳細信息,請參閱TensorFlow數據集指南。
# 從列表中獲取tensor
ds_tensors = tf.data.Dataset.from_tensor_slices([6,5,4,3,2,1])
# 創建csv文件
import tempfile
_, filename = tempfile.mkstemp()
print(filename)
with open(filename, 'w') as f:
f.write("""Line 1
Line 2
Line 3""")
# 獲取TextLineDataset數據集實例
ds_file = tf.data.TextLineDataset(filename)
/tmp/tmpvl0kyn0w
應用轉換
使用map,batch和shuffle等轉換函數將轉換應用於數據集記錄。
ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)
ds_file = ds_file.batch(2)
迭代
tf.data.Dataset對象支持迭代循環記錄:
print('ds_tensors中的元素:')
for x in ds_tensors:
print(x)
# 從文件中讀取的對象創建的數據源
print('\nds_file中的元素:')
for x in ds_file:
print(x)
ds_tensors中的元素:
tf.Tensor([36 25], shape=(2,), dtype=int32)
tf.Tensor([16 9], shape=(2,), dtype=int32)
tf.Tensor([4 1], shape=(2,), dtype=int32)
ds_file中的元素:
tf.Tensor([b'Line 1' b'Line 2'], shape=(2,), dtype=string)
tf.Tensor([b'Line 3'], shape=(1,), dtype=string)