-
Notifications
You must be signed in to change notification settings - Fork 14
/
age_and_sex_prediction_from_image_convolutional_neural_network_with_artificial_intelligence.py
272 lines (207 loc) · 6.85 KB
/
age_and_sex_prediction_from_image_convolutional_neural_network_with_artificial_intelligence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# -*- coding: utf-8 -*-
"""Age and Sex Prediction from Image - Convolutional Neural Network with Artificial Intelligence.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/12nC4Vqq2KvassVZw7_2hRqPX-y4o5MsR
"""
!unzip utkface-new.zip
fldr="/content/UTKFace"
import os
files=os.listdir(fldr)
print(int(files[0].split('_')[0]))
print(files[0])
import cv2
ages=[]
genders=[]
images=[]
for i, fle in enumerate(files):
age=int(fle.split('_')[0])
gender=int(fle.split('_')[1])
total=fldr+'/'+fle
image=cv2.imread(total)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image= cv2.resize(image,(48,48))
images.append(image)
# if i % 1000 == 0:
# print(i)
for fle in files:
age=int(fle.split('_')[0])
gender=int(fle.split('_')[1])
ages.append(age)
genders.append(gender)
# from google.colab.patches import cv2_imshow
# cv2_imshow(images[24])
print(ages[24])
print(genders[24])
# cv2_imshow(images[53])
print(ages[53])
print(genders[53])
import numpy as np
images_f=np.array(images)
genders_f=np.array(genders)
ages_f=np.array(ages)
np.save('image.npy',images_f)
np.save('gender.npy',genders_f)
np.save('age.npy',ages_f)
"""Male = 0
Female= 1
"""
values, counts = np.unique(genders_f, return_counts=True)
print(counts)
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
gender = ['Male', 'Female']
values=[4372,5047]
ax.bar(gender,values)
plt.show()
values, counts = np.unique(ages_f, return_counts=True)
print(counts)
val=values.tolist()
cnt=counts.tolist()
plt.plot(counts)
plt.xlabel('ages')
plt.ylabel('distribution')
plt.show()
labels=[]
i=0
while i<len(ages):
label=[]
label.append([ages[i]])
label.append([genders[i]])
labels.append(label)
i+=1
images_f_2=images_f/255
labels_f=np.array(labels)
images_f_2.shape
import tensorflow as tf
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test= train_test_split(images_f_2, labels_f,test_size=0.25)
Y_train[0:5]
Y_train_2=[Y_train[:,1],Y_train[:,0]]
Y_test_2=[Y_test[:,1],Y_test[:,0]]
Y_train_2[0][0:5]
Y_train_2[1][0:5]
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten,BatchNormalization
from tensorflow.keras.layers import Dense, MaxPooling2D,Conv2D
from tensorflow.keras.layers import Input,Activation,Add
from tensorflow.keras.models import Model
from tensorflow.keras.regularizers import l2
from tensorflow.keras.optimizers import Adam
import tensorflow as tf
def Convolution(input_tensor,filters):
x = Conv2D(filters=32,kernel_size=(3, 3),padding = 'same',kernel_regularizer=l2(0.01))(input_tensor)
x = Dropout(0.2)(x)
x= Activation('relu')(x)
return x
def model(input_shape):
inputs = Input((input_shape))
conv_1= Convolution(inputs,64)
maxp_1 = MaxPooling2D(pool_size = (2,2)) (conv_1)
conv_2 = Convolution(maxp_1,32)
maxp_2 = MaxPooling2D(pool_size = (2, 2)) (conv_2)
conv_3 = Convolution(maxp_2,64)
maxp_3 = MaxPooling2D(pool_size = (2, 2)) (conv_3)
conv_4 = Convolution(maxp_3,512)
maxp_4 = MaxPooling2D(pool_size = (2, 2)) (conv_4)
flatten= Flatten() (maxp_4)
dense_1= Dense(64,activation='relu')(flatten)
dense_2= Dense(64,activation='relu')(flatten)
drop_1=Dropout(0.2)(dense_1)
drop_2=Dropout(0.2)(dense_2)
output_1= Dense(1,activation="sigmoid",name='sex_out')(drop_1)
output_2= Dense(1,activation="relu",name='age_out')(drop_2)
model = Model(inputs=[inputs], outputs=[output_1,output_2])
model.compile(loss=["binary_crossentropy","mae"], optimizer="Adam",
metrics=["accuracy"])
return model
from tensorflow.keras.callbacks import ModelCheckpoint
import tensorflow as tf
fle_s='model_prediction.h5'
checkpointer = ModelCheckpoint(fle_s, monitor='val_loss',verbose=1,save_best_only=True,save_weights_only=False, mode='auto',save_freq='epoch')
Early_stop=tf.keras.callbacks.EarlyStopping(patience=80, monitor='val_loss',restore_best_weights=True),
callback_list=[checkpointer,Early_stop]
History=Model.fit(X_train,Y_train_2,batch_size=64,validation_data=(X_test,Y_test_2),epochs=160,callbacks=[callback_list])
from tensorflow.keras.models import load_model
Model = load_model('model_prediction_1.h5')
Model.evaluate(X_test,Y_test_2)
pred=Model.predict(X_test)
pred[1]
plt.plot(History.history['loss'])
plt.plot(History.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.subplots_adjust(top=1.00, bottom=0.0, left=0.0, right=0.95, hspace=0.25,
wspace=0.35)
plt.plot(History.history['sex_out_accuracy'])
plt.plot(History.history['val_sex_out_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.subplots_adjust(top=1.00, bottom=0.0, left=0.0, right=0.95, hspace=0.25,
wspace=0.35)
fig, ax = plt.subplots()
ax.scatter(Y_test_2[1], pred[1])
ax.plot([Y_test_2[1].min(),Y_test_2[1].max()], [Y_test_2[1].min(), Y_test_2[1].max()], 'k--', lw=4)
ax.set_xlabel('Actual Age')
ax.set_ylabel('Predicted Age')
plt.show()
i=0
Pred_l=[]
while(i<len(pred[0])):
Pred_l.append(int(np.round(pred[0][i])))
i+=1
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
report=classification_report(Y_test_2[0], Pred_l)
print(report)
results = confusion_matrix(Y_test_2[0], Pred_l)
import seaborn as sns
sns.heatmap(results, annot=True)
def test_image(ind,images_f,images_f_2,Model):
# cv2_imshow(images_f[ind])
plt.imshow(images_f[ind])
image_test=images_f_2[ind]
pred_1=Model.predict(np.array([image_test]))
#print(pred_1)
sex_f=['Male','Female']
age=int(np.round(pred_1[1][0]))
sex=int(np.round(pred_1[0][0]))
print("Predicted Age: "+ str(age))
print("Predicted Sex: "+ sex_f[sex])
age=int(np.round(pred_1[1][0]))-1310
sex=int(np.round(pred_1[0][0]))
img = cv2.imread('/content/emirhan.jpg')
img = cv2.resize(img,(48,48))
img = np.reshape(img,[48,48,3])
pred_1=Model.predict(np.array([img]))
#print(pred_1)
sex_f=['Male','Female']
print("Predicted Age: "+ str(age))
print("Predicted Sex: "+ sex_f[sex])
from google.colab.patches import cv2_imshow
images = cv2.imread('/content/emirhan.jpg')
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB)
plt.imshow(images)
plt.show()
img = cv2.imread('/content/emirhan_1.jpg')
img = cv2.resize(img,(48,48))
img = np.reshape(img,[48,48,3])
pred_1=Model.predict(np.array([img]))
#print(pred_1)
sex_f=['Male','Female']
print("Predicted Age: "+ str(age))
print("Predicted Sex: "+ sex_f[sex])
from google.colab.patches import cv2_imshow
images = cv2.imread('/content/emirhan_1.jpg')
images = cv2.cvtColor(images, cv2.COLOR_BGR2RGB)
plt.imshow(images)
plt.show()
test_image(57,images_f,images_f_2,Model)
test_image(137,images_f,images_f_2,Model)
test_image(502,images_f,images_f_2,Model)
test_image(24,images_f,images_f_2,Model)