Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.6 kB
21
Indexable
Never
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Conv2D, Flatten, Dense, AvgPool2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator


def load_train(path):

    train_datagen = ImageDataGenerator(horizontal_flip=True, vertical_flip=True, rescale = 1.0/255)
   # validation_datagen = ImageDataGenerator(validation_split=0.25, rescale=1.0 / 255)
                    #ImageDataGenerator(horizontal_flip=True, vertical_flip=True, rescale = 1/255)

    train_datagen_flow = train_datagen.flow_from_directory(path,
    target_size=(150, 150),
    batch_size=16,
    class_mode='sparse',
    seed=12345,)

    # val_datagen_flow = validation_datagen.flow_from_directory(path,
    # target_size=(150, 150),
    # batch_size=16,
    # class_mode='sparse',
    # subset='validation',
    # seed=12345) 

    DirectoryIterator = next(train_datagen_flow)

   # DirectoryIterator = features, target
    return DirectoryIterator


def create_model(input_shape=(150, 150, 3)):

    optimizer = Adam(lr=0.01) 
    model = Sequential()
    model.add(Conv2D(filters = 6, kernel_size = (5,5),strides=(1, 1), activation = "relu", padding='same',input_shape= input_shape))
    model.add(AvgPool2D(pool_size = (2,2), strides = None,  padding='valid'))
    # model.add(Conv2D(filters = 16, kernel_size = (5,5), activation = "relu", padding='valid',  strides=(1,1)))
    # model.add(AvgPool2D(pool_size = (2,2), strides = None,  padding='valid'))
    model.add(Flatten())
    model.add(Dense(units = 84, activation = "relu"))
    model.add(Dense(units = 12, activation = "softmax"))

    model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['acc'])

    return model


def train_model(model, train_data, test_data, batch_size=None, epochs=10, steps_per_epoch=None, validation_steps=None):
    if steps_per_epoch is None:
      steps_per_epoch = len(train_data)
    if validation_steps is None:
      validation_steps = len(test_data) 
    model.fit(train_data,
            validation_data=test_data,
            batch_size=batch_size,
            epochs=epochs,
          steps_per_epoch=steps_per_epoch,
          validation_steps=validation_steps,
          verbose=2)  
    # if steps_per_epoch is None:
    #   steps_per_epoch = len(train_data)
    # if validation_steps is None:
    #   validation_steps = len(test_data) 

    return model