Skip to content

Instantly share code, notes, and snippets.

@Mynuddin-dev
Last active November 4, 2022 07:13
Show Gist options
  • Save Mynuddin-dev/b270db9d39874c9d6fdf39e7f100f192 to your computer and use it in GitHub Desktop.
Save Mynuddin-dev/b270db9d39874c9d6fdf39e7f100f192 to your computer and use it in GitHub Desktop.
train image data with cnn
import glob
from importlib.resources import path
from os import listdir
from os.path import isfile, join
import cv2
import os
import numpy as np
from random import shuffle
# from tqdm import tqdm
import pandas as pd
train_data=[]
path="/home/myn/Computer_Vision/Age detection/face_age"
for label in os.listdir(path):
images = glob.glob(path+'/'+label+'/*.png')
# df = pd.DataFrame(list(zip(images, label)),
# columns =['Image', 'Label'])
for i in images:
img = cv2.imread(i, cv2.IMREAD_GRAYSCALE)
train_data.append([np.array(img), np.array(label)])
# print(train_data[1])
np.save('train_data.npy', train_data)
# Splitting the testing data and training data
train = train_data[:-6000]
test = train_data[-6000:]
IMG_SIZE = 200
'''Setting up the features and labels'''
# X-Features & Y-Labels
X = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
Y = [i[1] for i in train]
test_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)
test_y = [i[1] for i in test]
LR = 1e-3
MODEL_NAME = 'dogsvscats-{}-{}.model'.format(LR, '6conv-basic')
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
import tensorflow as tf
tf.reset_default_graph()
convnet = input_data(shape =[None, IMG_SIZE, IMG_SIZE , 1], name ='input')
convnet = conv_2d(convnet, 32, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 64, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 128, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 64, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = conv_2d(convnet, 32, 5, activation ='relu')
convnet = max_pool_2d(convnet, 5)
convnet = fully_connected(convnet, 1024, activation ='relu')
convnet = dropout(convnet, 0.8)
convnet = fully_connected(convnet, 2, activation ='softmax')
convnet = regression(convnet, optimizer ='adam', learning_rate = LR,
loss ='categorical_crossentropy', name ='targets')
model = tflearn.DNN(convnet, tensorboard_dir ='log')
# '''Fitting the data into our model'''
# epoch = 5 taken
model.fit({'input': X}, {'targets': Y}, n_epoch = 5,
validation_set =({'input': test_x}, {'targets': test_y}),
snapshot_step = 6000, show_metric = True, run_id = MODEL_NAME)
model.save(MODEL_NAME)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment