text_plain_output_1.png
from IPython.display import Image

from sklearn.model_selection import train_test_split

from tensorflow.keras import layers

import cv2

import matplotlib.pyplot as plt

import numpy as np

import os

import tensorflow as tf

import numpy as np
import pandas as pd
import cv2
from IPython.display import Image
import matplotlib.pyplot as plt
import os
import tensorflow as tf
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split

onlyfiles = os.listdir('../input/utkface_aligned_cropped/UTKFace')
y = np.array([[[i.split('_')[0]], [i.split('_')[1]]] for i in onlyfiles])

X_data = []
for file in onlyfiles:
    face = cv2.imread('../input/utkface_aligned_cropped/UTKFace/' + file, cv2.IMREAD_COLOR)
    face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
    face = cv2.resize(face, (32, 32))
    X_data.append(face)
X_data = np.array(X_data)
X_data.shape

X = np.squeeze(X_data)
(plt.xticks([]), plt.yticks([]))

X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.33)
y_train = [y_train[:, 1], y_train[:, 0]]
y_valid = [y_valid[:, 1], y_valid[:, 0]]

def gen_model():
    inputs = tf.keras.layers.Input(shape=(32, 32, 3))
    x = inputs
    x = layers.Conv2D(32, 3, activation='relu')(x)
    x = layers.Conv2D(32, 3, activation='relu')(x)
    x = layers.MaxPool2D(2)(x)
    x = layers.Dropout(0.3)(x)
    x = layers.Conv2D(64, 3, activation='relu')(x)
    x = layers.Conv2D(64, 3, activation='relu')(x)
    x = layers.MaxPool2D(2)(x)
    x = layers.Dropout(0.3)(x)
    x = layers.Conv2D(84, 3, activation='relu')(x)
    x = layers.Dropout(0.3)(x)
    x = layers.Flatten()(x)
    x1 = layers.Dense(64, activation='relu')(x)
    x2 = layers.Dense(64, activation='relu')(x)
    x1 = layers.Dense(1, activation='sigmoid', name='sex_out')(x1)
    x2 = layers.Dense(1, activation='relu', name='age_out')(x2)
    model = tf.keras.models.Model(inputs=inputs, outputs=[x1, x2])
    model.compile(optimizer='Adam', loss=['binary_crossentropy', 'mae'])
    return model
model = gen_model()
Image('model.png')

model.summary()
model.fit(X_train, y_train, epochs=200, batch_size=120, validation_data=(X_valid, y_valid))

print(y_valid[0][24], y_valid[1][24])
print(model.predict([[X_valid[24]]]))