Skip to main content
 首页 » 编程设计

python之如何在多个数据集上正确实现 Keras 的 fit_generator

2025年01月19日11落叶无声

我在实现 Keras 的 fit_generator 函数时遇到问题。我已经关注了 Keras 文档和许多其他在线文档。但我似乎无法让这件事发挥作用。

当我运行 fit_generator 时,它没有抛出错误。我可以看出某些东西正在后台运行,因为我的任务管理器上的 GPU 使用率飙升至 70% 处理。但是,没有文字/详细说明正在为我的卷积神经网络处理批处理。

这是我的模型

import keras 
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D 
from keras.layers import Dropout, Flatten, Dense 
from keras.models import Sequential 
 
model = Sequential() 
 
model.add(Conv2D(filters=80, kernel_size=4, strides=1, activation='relu', input_shape=(180, 180, 3))) 
model.add(Dropout(rate = 0.2)) 
model.add(MaxPooling2D(pool_size=2, strides=2)) 
model.add(Conv2D(filters=60, kernel_size=2, strides=1, activation='relu')) 
model.add(Dropout(rate = 0.2)) 
model.add(MaxPooling2D(pool_size=2, strides=2)) 
model.add(Dense(units = 40, activation = 'relu')) 
model.add(Dense(units = 20, activation = 'relu')) 
model.add(Flatten()) 
model.add(Dense(units=5270, activation='softmax')) 
 
model.compile(loss="categorical_crossentropy", optimizer="rmsprop", metrics=['accuracy']) 
model.summary() 

这是我的批处理生成器

我有六个我想要循环的 hdf5 文件,每个文件包含 40,000 张图像。它们已经被格式化为 Numpy 数组。我每次生成的批量大小为 20。

def train_generator(): 
    counter = 1 
    batch_size = 20 
 
    while True: 
 
        # Create arrays to contain x_train and y_train. There are six of these files in total, so 40000*6 = 240,000 items in the entire training set. 
        # 240,000 images for each epoch 
        h5f = h5py.File('x_train' + str(counter) + 'catID.h5','r') 
        pic_arr = h5f['dataset'][0:40000] 
 
        h5f = h5py.File('y_train' + str(counter) + 'catID.h5','r') 
        cat_arr = h5f['dataset'][0:40000] 
        h5f.close() 
 
        # Since training size for first dataset is 40,000 and batch_size is 20, loop 2000 times because 40000/20 = 2000  
        for i in range(1,2001): 
            if (i == 1): 
                x_train = pic_arr[0:batch_size] 
                y_train = cat_arr[0:batch_size] 
 
                index = batch_size 
                yield (x_train, y_train) 
            else: 
                x_train = pic_arr[index:index + batch_size] 
                y_train = cat_arr[index:index + batch_size] 
 
                index += batch_size 
                yield (x_train, y_train) 
 
        del pic_arr 
        del cat_arr 
        counter += 1 

拟合我的模型

当我用我的生成器拟合我的模型时,我知道我的 GPU 正在处理数据;我有一个 NVIDIA GTX 1070。但是在下面运行这段代码时没有显示详细/文本。我也试过在没有 GPU 的情况下运行,但仍然没有成功。我在这里做错了什么吗?

from keras.callbacks import ModelCheckpoint 
import tensorflow as tf 
 
# This is used to store the best weights for our trained model. 
checkpointer = ModelCheckpoint(filepath='weights_bestcatID.hdf5',  
                           verbose=1, save_best_only=True) 
 
# steps_per_epoch=12000 because --> 240,000 (total samples) / 20 (batch size) = 12000  
with tf.device('/device:GPU:0'): 
    model.fit_generator(train_generator(), steps_per_epoch=12000, nb_epoch=4, verbose = 1, callbacks=[checkpointer]) 

请您参考如下方法:

没关系。我尝试再次运行相同的代码并且成功了...如果有人需要引用如何实现 Keras 的 fit_generator,上面的代码有效。