Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

simple_race_class_model.py 5.1 KB

You have to be logged in to leave a comment. Sign In
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
  1. '''
  2. Simple initial model for race classification.
  3. Based on https://towardsdatascience.com/building-a-multi-output-convolutional-neural-network-with-keras-ed24c7bc1178
  4. '''
  5. import numpy as np
  6. import pandas as pd
  7. import os
  8. import glob
  9. import pandas as pd
  10. from PIL import Image
  11. import tensorflow as tf
  12. from tensorflow.keras.utils import to_categorical
  13. from tensorflow.keras.models import Model
  14. from tensorflow.keras.layers import BatchNormalization
  15. from tensorflow.keras.layers import Conv2D
  16. from tensorflow.keras.layers import MaxPooling2D
  17. from tensorflow.keras.layers import Activation
  18. from tensorflow.keras.layers import Dropout
  19. from tensorflow.keras.layers import Lambda
  20. from tensorflow.keras.layers import Dense
  21. from tensorflow.keras.layers import Flatten
  22. from tensorflow.keras.layers import Input
  23. #import tensorflow as tf
  24. TRAIN_TEST_SPLIT = 0.7
  25. IM_WIDTH = IM_HEIGHT = 224
  26. dataset_dict = {
  27. 'race_id': {
  28. 0: 'East Asian',
  29. 1: 'White',
  30. 2: 'Latino_Hispanic',
  31. 3: 'Southeast Asian',
  32. 4: 'Black',
  33. 5: 'Indian',
  34. 6: 'Middle Eastern'
  35. }
  36. }
  37. dataset_dict['race_alias'] = dict((r, i) for i, r in dataset_dict['race_id'].items())
  38. class FFDataGenerator():
  39. '''
  40. Data generator for the FairFace dataset. This class should be used
  41. when training our Keras multi-output model.
  42. '''
  43. def __init__(self, df):
  44. self.df = df
  45. def generate_split_indexes(self):
  46. p = np.random.permutation(len(self.df))
  47. train_up_to = int(len(self.df) * TRAIN_TEST_SPLIT)
  48. train_idx = p[:train_up_to]
  49. test_idx = p[train_up_to:]
  50. train_up_to = int(train_up_to * TRAIN_TEST_SPLIT)
  51. train_idx, valid_idx = train_idx[:train_up_to], train_idx[train_up_to:]
  52. #Reads race
  53. self.df['race_id'] = self.df['race'].map(lambda race: dataset_dict['race_alias'][race])
  54. return train_idx, valid_idx, test_idx
  55. def preprocess_image(self, img_path):
  56. '''
  57. Used to perform some minor preprocessing on the image before
  58. inputting into the network.
  59. '''
  60. im = Image.open('../1_Public_datasets/1_FairFace/' + img_path)
  61. im = im.resize((IM_WIDTH, IM_HEIGHT))
  62. im = np.array(im) / 255.0
  63. return im
  64. def generate_images(self, image_idx, is_training, batch_size = 16):
  65. '''
  66. Used to generate a batch with images when training/testing
  67. /validating our Keras model.
  68. '''
  69. # arrays to store our batched data
  70. images, races = [], []
  71. while True:
  72. for idx in image_idx:
  73. person = self.df.iloc[idx]
  74. race = person['race_id']
  75. file = person['file']
  76. im = self.preprocess_image(file)
  77. races.append(to_categorical(race, len(dataset_dict['race_id'])))
  78. images.append(im)
  79. #yielding condition
  80. if len(images) >= batch_size:
  81. yield np.array(images), [np.array(races)]
  82. images, races = [], []
  83. if not is_training:
  84. break
  85. class FFOutputModel():
  86. '''
  87. Used to generate our multi-output model. Convolutional Layers is
  88. defined on the make_default_hidden_layers method.
  89. '''
  90. def make_default_hidden_layers(self, inputs):
  91. '''
  92. Used to generate a default set of hidden layers. The
  93. structure used in this network is defined as:
  94. Conv2d -> BatchNormalization -> Pooling -> Dropout
  95. '''
  96. x = Conv2D(16, (3, 3), padding = 'same')(inputs)
  97. x = Activation('relu')(x)
  98. x = BatchNormalization(axis = -1)(x)
  99. x = MaxPooling2D(pool_size = (3, 3))(x)
  100. x = Dropout(0.25)(x)
  101. x = Conv2D(32, (3, 3), padding = 'same')(inputs)
  102. x = Activation('relu')(x)
  103. x = BatchNormalization(axis = -1)(x)
  104. x = MaxPooling2D(pool_size = (2, 2))(x)
  105. x = Dropout(0.25)(x)
  106. x = Conv2D(32, (3, 3), padding = 'same')(inputs)
  107. x = Activation('relu')(x)
  108. x = BatchNormalization(axis = -1)(x)
  109. x = MaxPooling2D(pool_size = (2, 2))(x)
  110. x = Dropout(0.25)(x)
  111. return x
  112. def build_race_branch(self, inputs, num_races):
  113. '''
  114. Used to build the race branch of our face recognition
  115. network.
  116. This branch is composed of thre Conv -> BN -> Pool ->
  117. Dropout blocks,
  118. followed by the Dense output layer.
  119. '''
  120. x = Lambda(lambda c: tf.image.rgb_to_grayscale(c))(inputs)
  121. x = self.make_default_hidden_layers(inputs)
  122. x = Flatten()(x)
  123. x = Dense(128)(x)
  124. x = Activation('relu')(x)
  125. x = BatchNormalization()(x)
  126. x = Dropout(0.5)(x)
  127. x = Dense(num_races)(x)
  128. x = Activation('softmax', name = 'race_output')(x)
  129. return x
  130. def assemble_full_model(self, width, height, num_races):
  131. '''
  132. Used to assemble our model CNN.
  133. '''
  134. input_shape = (height, width, 3)
  135. inputs = Input(shape = input_shape)
  136. race_branch = self.build_race_branch(inputs, num_races)
  137. model = Model(inputs = inputs, outputs = [race_branch], name = 'face_net')
  138. return model
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...