TensorFlow2.X使用圖片制作簡單的數(shù)據(jù)集訓(xùn)練模型
Tensorflow內(nèi)置了許多數(shù)據(jù)集,但是實際自己應(yīng)用的時候還是需要使用自己的數(shù)據(jù)集,這里TensorFlow 官網(wǎng)也給介紹文檔,官方文檔。這里對整個流程做一個總結(jié)(以手勢識別的數(shù)據(jù)集為例)。
1、 收集手勢圖片
方法多種多樣了。我通過攝像頭自己采集了一些手勢圖片。保存成如下形式,
以同樣的形式在建立一個測試集,當(dāng)然也可以不弄,在程序里處理。
2、構(gòu)建數(shù)據(jù)集
導(dǎo)入相關(guān)的包
import tensorflow as tf from tensorflow import keras from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 import os import pathlib import random import matplotlib.pyplot as plt
讀取文件
data_root = pathlib.Path('D:\code\PYTHON\gesture_recognition\Dataset') print(data_root) for item in data_root.iterdir(): print(item)
讀取圖片路徑到list中
all_image_paths = list(data_root.glob('*/*')) all_image_paths = [str(path) for path in all_image_paths] random.shuffle(all_image_paths) image_count = len(all_image_paths) print(image_count) ##統(tǒng)計共有多少圖片 for i in range(10): print(all_image_paths[i])
label_names = sorted(item.name for item in data_root.glob('*/') if item.is_dir()) print(label_names) #其實就是文件夾的名字 label_to_index = dict((name, index) for index, name in enumerate(label_names)) print(label_to_index) all_image_labels = [label_to_index[pathlib.Path(path).parent.name] for path in all_image_paths] print("First 10 labels indices: ", all_image_labels[:10])
預(yù)處理
def preprocess_image(image): image = tf.image.decode_jpeg(image, channels=3) image = tf.image.resize(image, [100, 100]) image /= 255.0 # normalize to [0,1] range # image = tf.reshape(image,[100*100*3]) return image def load_and_preprocess_image(path,label): image = tf.io.read_file(path) return preprocess_image(image),label
構(gòu)建一個 tf.data.Dataset
ds = tf.data.Dataset.from_tensor_slices((all_image_paths, all_image_labels)) train_data = ds.map(load_and_preprocess_image).batch(16)
同樣的方式在制作一個測試集,就可以用于模型訓(xùn)練和測試了。
總結(jié)
到此這篇關(guān)于TensorFlow2.X使用圖片制作簡單的數(shù)據(jù)集訓(xùn)練模型的文章就介紹到這了,更多相關(guān)TensorFlow數(shù)據(jù)集訓(xùn)練模型內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用with torch.no_grad():顯著減少測試時顯存占用
這篇文章主要介紹了使用with torch.no_grad():顯著減少測試時顯存占用問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08Python HTML解析模塊HTMLParser用法分析【爬蟲工具】
這篇文章主要介紹了Python HTML解析模塊HTMLParser用法,結(jié)合實例形式分析了HTMLParser模塊功能、常用函數(shù)及作為爬蟲工具相關(guān)使用技巧,需要的朋友可以參考下2019-04-04python3文件復(fù)制、延遲文件復(fù)制任務(wù)的實現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于python3文件復(fù)制、延遲文件復(fù)制任務(wù)的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用python3具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09