How does keras create his own generator

tags: AI

keras.utils.Sequence Is a base class

class Sequence(object):
    """Base object for fitting to a sequence of data, such as a dataset.
    Every `Sequence` must implement the `__getitem__` and the `__len__` methods.
    If you want to modify your dataset between epochs you may implement
    `on_epoch_end`. The method `__getitem__` should return a complete batch.
    # Notes
    `Sequence` are a safer way to do multiprocessing. This structure guarantees
    that the network will only train once on each sample per epoch which is not
    the case with generators.
    # Examples
    ```python
        from skimage.io import imread
        from skimage.transform import resize
        import numpy as np
        # Here, `x_set` is list of path to the images
        # and `y_set` are the associated classes.
        class CIFAR10Sequence(Sequence):
            def __init__(self, x_set, y_set, batch_size):
                self.x, self.y = x_set, y_set
                self.batch_size = batch_size
            def __len__(self):
                return int(np.ceil(len(self.x) / float(self.batch_size)))
            def __getitem__(self, idx):
                batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
                batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
                return np.array([
                    resize(imread(file_name), (200, 200))
                       for file_name in batch_x]), np.array(batch_y)
    ```
    """

    use_sequence_api = True

    @abstractmethod
    def __getitem__(self, index):
        """Gets batch at position `index`.
        # Arguments
            index: position of the batch in the Sequence.
        # Returns
            A batch
        """
        raise NotImplementedError

    @abstractmethod
    def __len__(self):
        """Number of batch in the Sequence.
        # Returns
            The number of batches in the Sequence.
        """
        raise NotImplementedError

    def on_epoch_end(self):
        """Method called at the end of every epoch.
        """
        pass

    def __iter__(self):
        """Create a generator that iterate over the Sequence."""
        for item in (self[i] for i in range(len(self))):
            yield item

So we need to implement his method __len__, __getitem__

import keras
import numpy as np
import cv2


class DataGenerator(keras.utils.Sequence):
    def __init__(self,img_files=None, labels=None,batch_size=32,n_classes=11,shuffle=True,dim=(224,224,3)):
        self.dim = dim
        self.batch_size = batch_size
        self.img_files = img_files
        self.labels = labels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.cls2id={item:i for i,item  in enumerate(sorted(list(set(self.labels))))}
        self.on_epoch_end()
        

Inherited from the keras.utils.Sequence class, the __init__ function is mainly responsible for initializing img_files, labels, etc.

Where self.on_epoch_end() is mainly used to initialize the index for the subsequent index of the generator

    def on_epoch_end(self):
        self.indexes = np.arange(len(self.labels))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

__getitem__ is used to get the data of each batch

    def __getitem__(self,index):
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
        X, y =self.__data_generation(indexes)
        return X,y

__data_generation is mainly to iteratively read in the image and preprocess the image

    def __data_generation(self,list_IDs_temp):
        X = np.empty((self.batch_size,*self.dim))
        y = np.empty((self.batch_size),dtype=int)
        for i, ID in enumerate(list_IDs_temp):
            img = cv2.imread(self.img_files[ID]).astype('float')
            label = self.labels[ID]
            img = cv2.resize(img,(224,224))
            img = img/255
            X[i,] = img
            y[i] = self.cls2id[label]
        return X,keras.utils.to_categorical(y,num_classes=self.n_classes)

The complete training code is as follows

import keras
import numpy as np
import cv2


class DataGenerator(keras.utils.Sequence):
    def __init__(self,img_files=None, labels=None,batch_size=32,n_classes=11,shuffle=True,dim=(224,224,3)):
        self.dim = dim
        self.batch_size = batch_size
        self.img_files = img_files
        self.labels = labels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.cls2id={item:i for i,item  in enumerate(sorted(list(set(self.labels))))}
        self.on_epoch_end()
        
    def __len__(self):
        return int(len(self.img_files)/self.batch_size)
    
    def on_epoch_end(self):
        self.indexes = np.arange(len(self.labels))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)
            
    def __getitem__(self,index):
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
        X, y =self.__data_generation(indexes)
        return X,y
        
    def __data_generation(self,list_IDs_temp):
        X = np.empty((self.batch_size,*self.dim))
        y = np.empty((self.batch_size),dtype=int)
        for i, ID in enumerate(list_IDs_temp):
            img = cv2.imread(self.img_files[ID]).astype('float')
            label = self.labels[ID]
            img = cv2.resize(img,(224,224))
            img = img/255
            X[i,] = img
            y[i] = self.cls2id[label]
        return X,keras.utils.to_categorical(y,num_classes=self.n_classes)


import osimport os
files = []
ids = []
for item in os.listdir('dog_classes/train/'):
    for dog in os.listdir('dog_classes/train/'+item):
        files.append('dog_classes/train/'+item+'/'+dog)
        ids.append(item)
ids = []
for item in os.listdir('dog_classes/train/'):
    for dog in os.listdir('dog_classes/train/'+item):
        files.append('dog_classes/train/'+item+'/'+dog)
        ids.append(item)

from keras.applications import ResNet50
from keras.models import Sequential
from keras.layers import Dense, Flatten, GlobalAveragePooling2D, Activation, Flatten, Dropout, BatchNormalization
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
import h5py
##Building a model, initializing with imagenet
resnet_weights_path='resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'
my_new_model = Sequential()
my_new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path))
my_new_model.add(Dense(512))
my_new_model.add(Activation('relu'))
my_new_model.add(Dropout(0.5))
my_new_model.add(Dense(3, activation='softmax'))


my_new_model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

from tensorflow.python.keras.applications.resnet50 import preprocess_input
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator

image_size = 224
bs = 32
resnet_weights_path='resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5'
my_new_model = Sequential()
my_new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path))
my_new_model.add(Dense(512))
my_new_model.add(Activation('relu'))
my_new_model.add(Dropout(0.5))
my_new_model.add(Dense(11, activation='softmax'))


my_new_model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

my_new_model.fit_generator(generator=cls_gen,
                           steps_per_epoch=40,
                           epochs=50                      
                            )

my_new_model.fit_generator(generator=cls_gen,
                           steps_per_epoch=40,
                           epochs=50                      
                            )

 

Intelligent Recommendation

How does Android Studio create its own library for others to use?

This question is worth learning, and this is the only way to achieve modularity. Let's start without further ado. . . Step 1: Create a Demo project The above is our project. Step 2: Create Module 1,Fi...

How does Baidu Map create a map of its own and attach it to the project?

Create a map-Baidu map generator 1. Open the URL of Baidu Map Generator Website: http://api.map.baidu.com/lbsapi/creatmap/ It can be seen that the official has given two steps: Step 1: Create a map St...

Keras read large data sets - write your own generator

In use keras of model.fit (x, y) training model, you need to load all of the training data, if the data is small (such as mnist data set), load all of the data no problem, but when their own data set ...

Use matlab to create your own password generator

guide LEAD language thankattentionmatlab enthusiast public number! If the public account article is helpful to you, don’t forget to clickshare itwith"look in"Oh! If you have any commen...

How does tensorflow and Keras correspond?

Tensorflow has been updated to 2.0.0. Compared with tensorflow1.x.x, the changes are larger. The official website gives some updated advantages, which will not be repeated here. Provide a quick conver...

More Recommendation

018 The wrong resolution of his own MYBATIS does not match

Write a database and JavaBean mapping relationship under the mapping file namespace ** Note: ** Property fills in the properties of the bean, and colum is filled in the field of the database table. Of...

How keras in model.compile set their own loss and parameters

keras If you can not set up their own loss function is still a white, so be sure to try it yourself to do all possible things. Fromkeras officialChinese documents found in the definition of loss is y_...

How does Android studio create and create third-party libraries to generate its own jar (Module)

1. Create moulde (1)File --- New Moudle File --- New Moudle1.png (2) Select Android Library --- Next File --- New Moudle2.png (3) Fill in Moudle name --- Finish. A new Moudle is complete. Fill in Moud...

How does a programmer find his favorite object?

❝ Today, the editor brings a small benefit to programmers, and teaches you how to follow the programfind a partner。❞ First exclude this form of finding objects 1. Usenew Create a new object. 2. PassCl...

What is an iterator, generator, how to create

Iterator The iterator is a special object that contains onenextMethod, each callnextAfter the method, a result object will be returned, and one of the result objects contains one.valueAttribute anddon...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top