简体   繁体   English

在 Python 中使用生成器输入 Keras model.fit_generator

[英]Using generator in Python to feed into Keras model.fit_generator

I am learning how to use generator in Python and feed it into Keras model.fit_generator.我正在学习如何在 Python 中使用生成器并将其输入 Keras model.fit_generator。

from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
import pandas as pd
import os
import cv2

class Generator:
    def __init__(self,path):
        self.path = path

    def gen(self, feat, labels):
        i=0
        while (True):
            im = cv2.imread(feat[i],0)
            im = im.reshape(28,28,1)
            yield im,labels[i]
            i+=1

if __name__ == "__main__":
    input_dir = './mnist'
    output_file = 'dataset.csv'

    filename = []
    label = []
    for root,dirs,files in os.walk(input_dir):
        for file in files:
            full_path = os.path.join(root,file)
            filename.append(full_path)
            label.append(os.path.basename(os.path.dirname(full_path)))

    data = pd.DataFrame(data={'filename': filename, 'label':label})
    data.to_csv(output_file,index=False)

    feat = data.iloc[:,0]
    labels = pd.get_dummies(data.iloc[:,1]).as_matrix()

    image_gen = Generator(input_dir)

    # #create model
    model = Sequential()
    model.add(Conv2D(64, kernel_size=3, activation="relu", input_shape=(28,28,1)))
    model.add(Conv2D(32, kernel_size=3, activation="relu"))
    model.add(Flatten())
    model.add(Dense(2, activation="softmax"))

    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
    model.fit_generator(image_gen.gen(filename,labels), steps_per_epoch=5 ,epochs=5, verbose=1)

I have 2 subfolders inside ./mnist folder, corresponding to each class in my dataset.我在./mnist文件夹中有 2 ./mnist文件夹,对应于我数据集中的每个类。 I created a Dataframe that contains the path of each image and the label (which is the name of the corresponding subfolder).我创建了一个 Dataframe,其中包含每个图像的路径和标签(即相应子文件夹的名称)。

I created Generator class that loads the image whose path is written in the DataFrame.我创建了Generator类来加载路径写在 DataFrame 中的图像。

It gave me error: ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (28, 28, 1)它给了我错误: ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (28, 28, 1)

Could anyone please help?有人可以帮忙吗? And also, is it the correct way to implement generator in general?而且,一般来说,这是实现生成器的正确方法吗?

Thanks!谢谢!

I think answers to your questions can be found in Keras documentation.我认为您的问题的答案可以在 Keras 文档中找到。

In terms of the input shape, Conv2D layers expects 4-dimensional input, but you explicitly reshape to (28,28,1) in your generator, so 3 dimensions.就输入形状而言, Conv2D层需要 4 维输入,但您在生成器中明确地将其重塑为(28,28,1) ,因此是 3 维。 On the Conv2D info and the input format, see this documentation .关于 Conv2D 信息和输入格式,请参阅此文档

In terms of the generator itself, Keras documentation provides an example with generator being a function, the same is discussed in Python Wiki .就生成器本身而言, Keras 文档提供了一个示例,其中生成器是一个函数,这在Python Wiki 中也有讨论。 But your particular implementation seem to work, at least for the first iteration, if you get to the point of feeding the data into the convolution layer.但是您的特定实现似乎有效,至少在第一次迭代中,如果您达到将数据输入卷积层的程度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM