Skip to main content

Male Female Classification

  # %%  Importing Libraries


import numpy as np       
import pandas as pd     
import matplotlib.pyplot as plt
import os

# %%  Importing Keras Libraries

import keras.backend as K 
from keras.models import Sequential
from keras.utils import to_categorical
from keras.layers.normalization import BatchNormalization
from keras.layers import Dense, Convolution2D, Activation, MaxPooling2D, AveragePooling2D, Dropout, Flatten
from keras.preprocessing import image
from keras.layers import LeakyReLU

# %%   Importing sklearn libraries

from sklearn.metrics import confusion_matrix, classification_report
from sklearn.model_selection import train_test_split


#%%  Assining the directories

men_img_path = 'men'
women_img_path = 'women'
directory = [(0,men_img_path), (1,women_img_path)] # assing the binary symbol ; type - list

# %%  Creating ImageDataBunch

men = []
women = []
img_size = 300

train_images = []
labels = []

for num , dir in directory:
    dir = dir + '/'

    count = 0

    for file in os.listdir(_dir):
        if count >= 1000:
            break

        img = image.load_img(_dir + str(file), target_size=(300,300))
        img = image.img_to_array(img)
        img = img/255
        train_images.append(img)
        labels.append(num)
        count += 1

# %%
print(type(train_images))
# print(train_images)
print(train_images[1].shape)
print(len(train_images))

# %%

plt.axis('off')
plt.imshow(train_images[100])
plt.imshow(train_images[1500])
# %%  Converting images list to array

x = np.array(train_images)

# %%  Splitting

x_train, x_test, y_train, y_test = train_test_split(x, labels, test_size=0.1, random_state=100)

# %%  Testing the vislulization

plt.axis('off')
plt.imshow(x_train[1000])
plt.imshow(x_test[500])

# %%
plt.figure(figsize=(20,50))

for i in range(20,40):
    plt.subplot(10,5,i+1)
    plt.axis('off')
    plt.imshow(x_train[i])
    plt.xlabel(y_train[i])

# %%  Converting labels list to categorical

y_train_labels = to_categorical(y_train)  # Here I did only train part bescause of training
# to_categorical` converts this into a matrix with as many

# %%  Initializing the model along with the input shape

def build(width, height, depth, classes):
    #initialize the model along with the input shape
    model = Sequential()
    input_shape = (height, width, depth)
    chanDim = -1
    
    if K.image_data_format() == 'channels_first':
        input_shape = (depth, height, width)
        chanDim = 1
        
    # layer 1 : CONV -> RELU -> MAXPOOL
    model.add(Convolution2D(64, (3,3), padding='same', input_shape=input_shape))
    model.add(Activation('relu'))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling2D(pool_size=(3,3)))
    model.add(Dropout(0.25))
    
    # layer 2-1 : CONV -> LEAKYRELU 
    model.add(Convolution2D(128, (3,3), padding='same'))
    model.add(LeakyReLU(alpha=0.1))
    model.add(BatchNormalization(axis=chanDim))

    # layer 2-2 : CONV -> LEAKYRELU -> AVGPOOL
    model.add(Convolution2D(128, (3,3), padding='same'))
    model.add(LeakyReLU(alpha=0.1))
    model.add(BatchNormalization(axis=chanDim))
    model.add(AveragePooling2D(pool_size=(3,3)))
    model.add(Dropout(0.25))
    
    # layer 3 : CONV -> RELU -> MAXPOOL
    model.add(Convolution2D(256, (3,3), padding='same'))
    model.add(Activation('relu'))
    model.add(BatchNormalization(axis=chanDim))
    model.add(MaxPooling2D(pool_size=(3,3)))
    model.add(Dropout(0.25))
    
    # layer 4 : CONV -> LEAKYRELU -> AVGPOOL
    model.add(Convolution2D(512, (3,3), padding='same'))
    model.add(LeakyReLU(alpha=0.1))
    model.add(BatchNormalization(axis=chanDim))
    model.add(AveragePooling2D(pool_size=(3,3)))
    model.add(Dropout(0.25))
    
    # layer 5 : FLATTEN -> DENSE -> RELU
    model.add(Flatten())
    model.add(Dense(1024))
    model.add(Activation('relu'))
    model.add(BatchNormalization())
    model.add(Dropout(0.25))
    
    # DENSE -> DENSE -> RELU
    model.add(Dense(512))
    model.add(Activation('relu'))
    model.add(BatchNormalization())
    model.add(Dropout(0.25))
    
    # SIGMOID , SOFTMAX-> just to check the accuracy with this (softmax would work too)
    model.add(Dense(classes))
    model.add(Activation('sigmoid'))
    
    return model

# %%

model = build(img_size, img_size, 32)
# %%

model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

model.summary()
# %%

model.fit(
    x_train,
    y_train_labels,
    batch_size=30,
    shuffle=True,
    epochs=50,
    validation_split=0.2
)


Comments

Popular posts from this blog

Python program to check if variable is of integer or string

Let's say if you want to input something of any datatype and want to get datatype only of it. So... Whenever you input some data whether it is string, integer or float like this: i = input('enter something here: ') means without int, str or float put before the syntax, that time your given input is always consider as string  or if you make it like this to add int before syntax; i = int(input('enter something here: '))  it always consider as integer and gives value error when you input string and same thing happens with float, So here is a program to solve this problem of input and get datatype var = input('input to check if variable is of integer or string: ') if var.isdigit() == False:     print(type(var)) else:     var1 = int(var)     print(type(var1))

Multiple classification from many of directories

  # %%  Import nessacary libraries import  numpy  as  np import  pandas  as  pd import  cv2 import  matplotlib.pyplot  as  plt import  os import  glob # %%   Keras Tensorflow libraries from  keras  import  layers from  keras.models  import  Model from  keras.optimizers  import  RMSprop , Adam , Nadam from  keras.preprocessing.image  import  ImageDataGenerator from  keras.layers  import  Input, BatchNormalization, Dense, Dropout, Conv2D, Flatten, GlobalAveragePooling2D, LeakyReLU from  keras.preprocessing.image  import  ImageDataGenerator, img_to_array, load_img # %%  Path path  =   r 'G:/Machine Learning/Project/Lego Mnifigures Classification/dataset' open_dir  =  os....

Digit Recognition

Here you can import digit dataset from scikit learn library which is in-built, So you don't need to download from other else Note: If you use visual code, I recommend you to turn your color theme to Monokai because it has a few extra and important keyword and attractive colors than other theme.   # %%  Import libraries import  numpy  as  np import  pandas  as  pd import  matplotlib.pyplot  as  plt import  random  # %%   Load dataset from  sklearn.datasets  import  load_digits dataset  =  load_digits() dataset.keys() output: d ict_keys(['data', 'target', 'target_names', 'images', 'DESCR']) You have to check all to direct print them Here DESCR is a description of dataset # %%   divide the dataset into input and target inputs  =  dataset.data target  =  dataset.target # %% ...