[英]how to obtain the number of classes using tf.keras.preprocessing.image_dataset_from_directory?
[英]How can I explore and modify the created dataset from tf.keras.preprocessing.image_dataset_from_directory()?
以下是我如何使用該功能:
dataset = tf.keras.preprocessing.image_dataset_from_directory(
main_directory,
labels='inferred',
image_size=(299, 299),
validation_split=0.1,
subset='training',
seed=123
)
我想像在這個例子中一樣探索創建的數據集,特別是它被轉換為pandas
數據幀的部分。 但我的最低目標是檢查標簽和附加到它的文件數量,只是為了檢查它是否確實按預期創建了數據集(子目錄是其中圖像的相應標簽)。
需要明確的是, main_directory
是這樣設置的:
main_directory
- class_a
- 000.jpg
- ...
- class_b
- 100.jpg
- ...
我希望看到數據集以如下方式顯示其信息:
label number of images
class_a 100
class_b 100
此外,是否可以刪除數據集中的標簽和相應的圖像? 這個想法是如果相應的圖像數量小於某個數量或不同的度量標准,則刪除它們。 它當然可以通過其他方式在這個函數之外完成,但我想知道它是否確實可能,如果是,如何。
編輯:對於額外的上下文,所有這些的最終目標是訓練一個像這樣的預訓練模型,將本地圖像划分為以類別命名的文件夾。 如果有更好的方法,包括不使用該功能並滿足此最終目標,則同樣歡迎。 謝謝!
我認為使用glob2
獲取所有文件名,根據需要處理它們,然后創建一個簡單的加載函數來替換image_dataset_from_directory
會image_dataset_from_directory
。
獲取所有文件:
files = glob2.glob('class_*\\*.jpg')
然后根據需要操作此文件名列表。
然后,創建一個函數來加載圖像:
def load(file_path):
img = tf.io.read_file(file_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, size=(299, 299))
label = tf.strings.split(file_path, os.sep)[0]
label = tf.cast(tf.equal(label, 'class_a'), tf.int32)
return img, label
然后創建用於訓練的數據集:
train_ds = tf.data.Dataset.from_tensor_slices(files).map(load).batch(4)
然后訓練:
model.fit(train_ds)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.