日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

TensorFlow 2.0 - TFRecord存储数据集、@tf.function图执行模式、tf.TensorArray、tf.config分配GPU

發(fā)布時間:2024/7/5 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TensorFlow 2.0 - TFRecord存储数据集、@tf.function图执行模式、tf.TensorArray、tf.config分配GPU 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 1. TFRecord 格式存儲
    • 2. tf.function 高性能
    • 3. tf.TensorArray 支持計算圖特性
    • 4. tf.config 分配GPU

學(xué)習(xí)于:簡單粗暴 TensorFlow 2

1. TFRecord 格式存儲

  • 使用該種格式,更高效地進行大規(guī)模的模型訓(xùn)練

import random import os import tensorflow as tf# 使用前一節(jié) kaggle 上的 貓狗數(shù)據(jù)集 train_data_dir = "./dogs-vs-cats/train/" test_data_dir = "./dogs-vs-cats/test/"# 訓(xùn)練文件路徑 file_dir = [train_data_dir + filename for filename in os.listdir(train_data_dir)] labels = [0 if filename[0] == 'c' else 1for filename in os.listdir(train_data_dir)]# 打包并打亂 f_l = list(zip(file_dir, labels)) random.shuffle(f_l) file_dir, labels = zip(*f_l)# 切分訓(xùn)練集,驗證集 valid_ratio = 0.1 idx = int((1 - valid_ratio) * len(file_dir)) train_files, valid_files = file_dir[:idx], file_dir[idx:] train_labels, valid_labels = labels[:idx], labels[idx:]# tfrecord 格式數(shù)據(jù)存儲路徑 train_tfrecord_file = "./dogs-vs-cats/train.tfrecords" valid_tfrecord_file = "./dogs-vs-cats/valid.tfrecords"# -------------------看下面代碼----------------------------- # 存儲過程 # 預(yù)先定義一個寫入器 with tf.io.TFRecordWriter(path=train_tfrecord_file) as writer:# 遍歷原始數(shù)據(jù)for filename, label in zip(train_files, train_labels):img = open(filename, 'rb').read() # 讀取圖片,img 是 Byte 類型的字符串# 建立 feature 的 字典 k : vfeature = {'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img])),'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))}# feature 包裹成 exampleexample = tf.train.Example(features=tf.train.Features(feature=feature))# example 序列化為字符串,寫入writer.write(example.SerializeToString())# -------------------看下面代碼----------------------------- # 讀取過程 # 讀取 tfrecord 數(shù)據(jù),得到 tf.data.Dataset 對象 raw_train_dataset = tf.data.TFRecordDataset(train_tfrecord_file) # 特征的格式、數(shù)據(jù)類型 feature_description = {'image': tf.io.FixedLenFeature(shape=[], dtype=tf.string),'label': tf.io.FixedLenFeature([], tf.int64), }def _parse_example(example_string): # 解碼每個example# tf.io.parse_single_example 反序列化feature_dict = tf.io.parse_single_example(example_string, feature_description)# 圖像解碼feature_dict['image'] = tf.io.decode_jpeg(feature_dict['image'])# 返回數(shù)據(jù) X, yreturn feature_dict['image'], feature_dict['label']# 處理數(shù)據(jù)集 train_dataset = raw_train_dataset.map(_parse_example)import matplotlib.pyplot as plt for img, label in train_dataset:plt.title('cat' if label==0 else 'dog')plt.imshow(img.numpy())plt.show()

2. tf.function 高性能

  • TF 2.0 默認(rèn) 即時執(zhí)行模式(Eager Execution),靈活、易調(diào)試
  • 追求高性能、部署模型時,使用圖執(zhí)行模式(Graph Execution)
  • TF 2.0 的 tf.function 模塊 + AutoGraph 機制,使用 @tf.function 修飾符,就可以將模型以圖執(zhí)行模式運行

注意:@tf.function修飾的函數(shù)內(nèi),盡量只用 tf 的內(nèi)置函數(shù),變量只用 tensor、numpy 數(shù)組

  • 被修飾的函數(shù) F(X, y) 可以調(diào)用get_concrete_function 方法,獲得計算圖
graph = F.get_concrete_function(X, y)

3. tf.TensorArray 支持計算圖特性

  • tf.TensorArray 支持計算圖模式的 動態(tài)數(shù)組
arr = tf.TensorArray(dtype=tf.int64, size=1, dynamic_size=True) arr = arr.write(index=1, value=512) # arr.write(index=0, value=512) # 沒有左值接受,會丟失 for i in range(arr.size()):print(arr.read(i))

4. tf.config 分配GPU

  • 列出設(shè)備 list_physical_devices
print('---device----') gpus = tf.config.list_physical_devices(device_type='GPU') cpus = tf.config.list_physical_devices(device_type='CPU') print(gpus, "\n", cpus) # 單個的 GPU, CPU [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')] [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]
  • 設(shè)置哪些可見 set_visible_devices
tf.config.set_visible_devices(devices=gpus[0:2], device_type='GPU')

或者

  • 終端輸入 export CUDA_VISIBLE_DEVICES=2,3
  • or 代碼中加入
import os os.environ['CUDA_VISIBLE_DEVICES'] = "2,3"

指定程序 只在 顯卡 2, 3 上運行

  • 顯存使用策略:
gpus = tf.config.list_physical_devices(device_type='GPU') for gpu in gpus:# 僅在需要時申請顯存tf.config.experimental.set_memory_growth(device=gpu, enable=True) gpus = tf.config.list_physical_devices(device_type='GPU') # 固定顯存使用上限,超出報錯 tf.config.set_logical_device_configuration(gpus[0],[tf.config.LogicalDeviceConfiguration(memory_limit=1024)])
  • 單 GPU 模擬多 GPU 環(huán)境

在單GPU電腦上,寫 多GPU 代碼,可以模擬實現(xiàn)

gpus = tf.config.list_physical_devices('GPU') tf.config.set_logical_device_configuration(gpus[0],[tf.config.LogicalDeviceConfiguration(memory_limit=2048),tf.config.LogicalDeviceConfiguration(memory_limit=2048)]) gpus = tf.config.list_logical_devices(device_type='GPU') print(gpus)

輸出:2個虛擬的GPU

[LogicalDevice(name='/device:GPU:0', device_type='GPU'), LogicalDevice(name='/device:GPU:1', device_type='GPU')]

總結(jié)

以上是生活随笔為你收集整理的TensorFlow 2.0 - TFRecord存储数据集、@tf.function图执行模式、tf.TensorArray、tf.config分配GPU的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。