如何从不同的文件夹加载图像和文本标签以进行CNN回归 [英] How to load images and text labels for CNN regression from different folders

查看:125
本文介绍了如何从不同的文件夹加载图像和文本标签以进行CNN回归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件夹X_train和Y_train. X_train是图像,Y_train是矢量和.txt文件.我尝试训练CNN进行回归.

I have two folders, X_train and Y_train. X_train is images, Y_train is vector and .txt files. I try to train CNN for regression.

我不知道如何获取数据和训练网络.当我使用"ImageDataGenerator"时, ,它假设X_train和Y_train文件夹是类.

I could not figure out how to take data and train the network. When i use "ImageDataGenerator" , it suppose that X_train and Y_train folders are classes.

import os
import tensorflow as tf
os.chdir(r'C:\\Data')
from glob2 import glob

x_files = glob('X_train\\*.jpg')
y_files = glob('Y_rain\\*.txt')

上面,我找到了它们的目的地,我该如何拿走它们并准备好进行model.fit?谢谢.

Above, i found destination of them, how can i take them and be ready for model.fit ? Thank you.

推荐答案

确保将x_filesy_files排序在一起,然后可以使用类似以下的方法:

Makes sure x_files and y_files are sorted together, then you can use something like this:

import tensorflow as tf
from glob2 import glob
import os

x_files = glob('X_train\\*.jpg')
y_files = glob('Y_rain\\*.txt')

target_names = ['cat', 'dog']

files = tf.data.Dataset.from_tensor_slices((x_files, y_files))

imsize = 128

def get_label(file_path):
    label = tf.io.read_file(file_path)
    return tf.cast(label == target_names, tf.int32)

def decode_img(img):
    img = tf.image.decode_jpeg(img, channels=3)
    img = tf.image.convert_image_dtype(img, tf.float32)
    img = tf.image.resize(images=img, size=(imsize, imsize))
    return img

def process_path(file_path):
    label = get_label(file_path)
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img, label

train_ds = files.map(process_path).batch(32)

然后,train_ds可以传递给model.fit(),并将返回32对图像,标签的批次.

Then, train_ds can be passed to model.fit() and will return batches of 32 pairs of images, labels.

这篇关于如何从不同的文件夹加载图像和文本标签以进行CNN回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆