Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.5 kB
10
Indexable
import numpy as np
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Conv2D, Flatten, AvgPool2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import pandas as pd
from tensorflow.keras.applications.resnet import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Sequential

optimizer = Adam(lr=0.0001)
# In[2]:


def load_train(path):
   
    labels = pd.read_csv('/datasets/faces/labels.csv')
    
    datagen = ImageDataGenerator(validation_split=0.25, 
                                 rescale=1.0/255,
                                 vertical_flip=True)
  
    train_datagen_flow = datagen.flow_from_dataframe(
        dataframe=labels,
        directory='/datasets/faces/final_files/',
        x_col='file_name',
        y_col='real_age',
        target_size=(224, 224),
        batch_size=32,
        class_mode='raw',
        subset='training',
        seed=12345)
    
    return train_datagen_flow

# In[3]:

def load_test(path):

    labels = pd.read_csv('/datasets/faces/labels.csv')
    
    datagen = ImageDataGenerator(validation_split=0.25,
                                 #vertical_flip=True, 
                                 rescale=1.0/255)
   
    test_datagen_flow = datagen.flow_from_dataframe(
        dataframe=labels,
        directory=path,
        x_col='file_name',
        y_col='real_age',
        target_size=(224, 224),
        batch_size=32,
        class_mode='raw',
        subset='validation',
        seed=12345)
    
    return test_datagen_flow

# In[4]:

def create_model(input_shape):
    
    backbone = ResNet50(input_shape=(224, 224, 3),
                        weights='imagenet',
                        include_top=False) 
    
    model = Sequential()
    
    model.add(backbone)
    model.add(GlobalAveragePooling2D())
    model.add(Dense(1, activation='relu')) 
                    
    model.compile(optimizer=optimizer, loss='mean_squared_error', 
                 metrics=['mae'])
              
    return model

# In[5]:

def train_model(model, train_data, test_data, batch_size=None, epochs=3,
                steps_per_epoch=None, validation_steps=None):

    train_datagen_flow = train_data
    test_datagen_flow = test_data
    
    
    model.fit(train_datagen_flow, validation_data = test_datagen_flow, epochs=epochs, verbose=2,
          steps_per_epoch=steps_per_epoch, batch_size=batch_size, validation_steps=validation_steps)
          
    return model