【发布时间】:2020-07-29 13:08:39
【问题描述】:
我正在使用 Tensorflow 2(尤其是 Tensorflow 2.2)
下面的函数允许我们从文件夹中读取图像
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'data/train',
target_size=(150, 150),
batch_size=32,
class_mode='binary')
但它要求我们根据cat 和dog 分类为
data/train/cat 和 data/train/dog
现在说,我们在文件夹 data/train/(比如 data/train/1.jpg 等)中有所有训练图像,我在下面有 train_set X 和标签 y:
X=['1.jpg','2.jpg',...]
y=[0,1,...]
其中0 表示dog 和1 表示cat 表示y,我想达到与上面的代码相同的效果(例如,图像八月像水平翻转等+ 与batchsize指定),我该怎么做?
我尝试过的一种方法:
我使用下面的代码
def preprocess(image):
img_shape=np.array(image).shape
image = tf.cast(np.array(image), tf.float32)
image = (image / 127.5) - 1
return image
image_path=pathlib.Path.joinpath("train", "data")
class_names=[x.name.lower() for x in image_path.glob('*') if x.is_dir()]
X=[]
y=[]
for path in image_path.glob('**/*'):
if path.is_file():
if path.name.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif')):
X.append(preprocess(Image.open(path).resize((224,224),resample=Image.BICUBIC)))
y.append(class_names.index(path.parent.name.lower()))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1 - train_ratio, stratify=y)
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test,
test_size=test_ratio / (test_ratio + validation_ratio),
stratify=y_test)
train_data = tf.data.Dataset.from_tensor_slices((X_train, y_train)).batch(batch_size)
validation_data = tf.data.Dataset.from_tensor_slices((X_val, y_val)).batch(batch_size)
test_data = tf.data.Dataset.from_tensor_slices((X_test, y_test)).batch(batch_size)
我出现内存不足错误(因为我将所有图像都存储在 X 中),我应该如何解决这个问题?
【问题讨论】:
标签: python python-3.x tensorflow tensorflow2.0