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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

TensorFlow构建模型(图片数据加载)六

發布時間:2023/12/10 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TensorFlow构建模型(图片数据加载)六 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

概要

本文內容來源于TensorFlow教程
本文主要介紹了三種圖片數據的加載和預處理方法:

  • 使用高級的Keras預處理工具(如tf.keras.utils.image_dataset_from_directory)和預處理層(如tf.keras.layers.Rescaling)從磁盤的圖片目錄中加載數據。
  • 使用tf.data的框架寫你自己的輸入通道。
  • 在TensorFlow Datasets中從可用的類別加載數據集。
  • 內容

    import numpy as np import os import PIL import PIL.Image import tensorflow as tf import tensorflow_datasets as tfds import pathlib# 下載花的數據集 dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz" data_dir = tf.keras.utils.get_file(origin=dataset_url,fname='flower_photos',untar=True) data_dir = pathlib.Path(data_dir) os.listdir(data_dir) # ['LICENSE.txt', 'tulips', 'roses', 'dandelion', 'daisy', 'sunflowers'] image_count = len(list(data_dir.glob('*/*.jpg'))) print(image_count) # 3670

    數據集的目錄格式:

    flowers_photos/
    ????????? daisy/
    ??????????dandelion/
    ????????? roses/
    ????????? sunflowers/
    ????????? tulips/

    # 畫圖展示 roses = list(data_dir.glob('roses/*')) PIL.Image.open(str(roses[0]))


    使用tf.keras.utils.image_dataset_from_directory將圖片數據集加載存入內存

    batch_size = 32 img_height = 180 img_width = 180train_ds = tf.keras.utils.image_dataset_from_directory(data_dir,validation_split=0.2,subset="training",seed=123,image_size=(img_height, img_width),batch_size=batch_size)val_ds = tf.keras.utils.image_dataset_from_directory(data_dir,validation_split=0.2,subset="validation",seed=123,image_size=(img_height, img_width),batch_size=batch_size)# 可視化圖片 import matplotlib.pyplot as pltplt.figure(figsize=(10, 10)) for images, labels in train_ds.take(1):for i in range(9):ax = plt.subplot(3, 3, i + 1)plt.imshow(images[i].numpy().astype("uint8"))plt.title(class_names[labels[i]])plt.axis("off")# 查看訓練集中數據的shape for image_batch, labels_batch in train_ds:print(image_batch.shape) # (32, 180, 180, 3) 32是batch size的大小,180 * 180是圖片的維度,3是圖片的通道數RGB格式print(labels_batch.shape) # (32,) batch_size=32break# RGB通道圖像的像素值在[0,255],為了更好的模型訓練,進行放縮到[0,1]。 normalization_layer = tf.keras.layers.Rescaling(1./255)# 也可以將其放縮到[-1,1] # normalization_layer = tf.keras.layers.Rescaling(1./127.5, offset=-1)normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y)) image_batch, labels_batch = next(iter(normalized_ds)) first_image = image_batch[0] # Notice the pixel values are now in `[0,1]`. print(np.min(first_image), np.max(first_image))

    這里注意,我們在使用tf.keras.utils.image_dataset_from_directory加載數據的時候使用image_size參數重新定義了圖片的大小。這個步驟也可以定義在模型中,通過使用tf.keras.layers.Resizing。
    大數據集的情況數據加載有可能會成為模型訓練的瓶頸,可以通過以下兩種方法使用緩存的方式加載數據:

  • Dataset.cache,數據集從磁盤上加載放入內存中,如果數據集太大內存放不下,則可以使用此方法創建一個性能磁盤緩存。
  • Dataset.prefetch,訓練時重疊數據預處理和模型執行。
  • AUTOTUNE = tf.data.AUTOTUNEtrain_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE) val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

    以上是使用tf.keras.utils.image_dataset_from_directory加載數據的方法,下面使用tf.data更好的控制數據輸入,通過使用tf.data編寫自己的數據輸入通道。

    list_ds = tf.data.Dataset.list_files(str(data_dir/'*/*'), shuffle=False) list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)for f in list_ds.take(5):print(f.numpy())# 使用文件的樹結構生成類別組數 class_names = np.array(sorted([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"])) print(class_names) # 劃分訓練集和驗證集 val_size = int(image_count * 0.2) train_ds = list_ds.skip(val_size) val_ds = list_ds.take(val_size)print(tf.data.experimental.cardinality(train_ds).numpy()) print(tf.data.experimental.cardinality(val_ds).numpy())# 轉換文件路徑成(img, label)對 def get_label(file_path):# Convert the path to a list of path componentsparts = tf.strings.split(file_path, os.path.sep)# The second to last is the class-directoryone_hot = parts[-2] == class_names# Integer encode the labelreturn tf.argmax(one_hot)def decode_img(img):# Convert the compressed string to a 3D uint8 tensorimg = tf.io.decode_jpeg(img, channels=3)# Resize the image to the desired sizereturn tf.image.resize(img, [img_height, img_width])def process_path(file_path):label = get_label(file_path)# Load the raw data from the file as a stringimg = tf.io.read_file(file_path)img = decode_img(img)return img, label# 使用`Dataset.map`創建一個image,label對數據集 # Set `num_parallel_calls` so multiple images are loaded/processed in parallel. train_ds = train_ds.map(process_path, num_parallel_calls=AUTOTUNE) val_ds = val_ds.map(process_path, num_parallel_calls=AUTOTUNE)for image, label in train_ds.take(1):print("Image shape: ", image.numpy().shape)print("Label: ", label.numpy())

    為了性能配置數據集。

    def configure_for_performance(ds):ds = ds.cache() # 緩存ds = ds.shuffle(buffer_size=1000) # 打亂數據ds = ds.batch(batch_size) # 批處理ds = ds.prefetch(buffer_size=AUTOTUNE) # 保證批量數據盡快可用return dstrain_ds = configure_for_performance(train_ds) val_ds = configure_for_performance(val_ds)# 可視化數據 image_batch, label_batch = next(iter(train_ds))plt.figure(figsize=(10, 10)) for i in range(9):ax = plt.subplot(3, 3, i + 1)plt.imshow(image_batch[i].numpy().astype("uint8"))label = label_batch[i]plt.title(class_names[label])plt.axis("off")

    使用TensorFlow數據集

    (train_ds, val_ds, test_ds), metadata = tfds.load('tf_flowers',split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],with_info=True,as_supervised=True, )num_classes = metadata.features['label'].num_classes print(num_classes)get_label_name = metadata.features['label'].int2strimage, label = next(iter(train_ds)) _ = plt.imshow(image) _ = plt.title(get_label_name(label))train_ds = configure_for_performance(train_ds) val_ds = configure_for_performance(val_ds) test_ds = configure_for_performance(test_ds)

    為了完整性,我們構建了一個卷積網絡訓練模型。三個帶最大池化的卷積層,一個全連接層

    num_classes = 5model = tf.keras.Sequential([tf.keras.layers.Rescaling(1./255),tf.keras.layers.Conv2D(32, 3, activation='relu'),tf.keras.layers.MaxPooling2D(),tf.keras.layers.Conv2D(32, 3, activation='relu'),tf.keras.layers.MaxPooling2D(),tf.keras.layers.Conv2D(32, 3, activation='relu'),tf.keras.layers.MaxPooling2D(),tf.keras.layers.Flatten(),tf.keras.layers.Dense(128, activation='relu'),tf.keras.layers.Dense(num_classes) ])model.compile(optimizer='adam',loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])model.fit(train_ds,validation_data=val_ds,epochs=3 )

    我們也可以自己寫一個訓練循環器替代model.fit,詳情參考:從頭編寫訓練循環

    總結

    以上是生活随笔為你收集整理的TensorFlow构建模型(图片数据加载)六的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。