title: Vgg16 for gender detection (male,female)
body: <p>We have used vgg16 and freeze top layers and retrain the last 4 layers on gender dataset 12k male and 12k female. It gives very low accuracy especially for male. We are using the IMDB dataset. On female test data it gives female as output but on male it gives same output.</p>
  
  <pre><code>vgg_conv=VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
  
  Freeze the layers except the last 4 layers
  for layer in vgg_conv.layers[:-4]: 
      layer.trainable = False
  
  Create the model
  model = models.Sequential()
  
  Add the vgg convolutional base model
  model.add(vgg_conv)
  
  Add new layers
  model.add(layers.Flatten()) 
  model.add(layers.Dense(4096, activation='relu')) 
  model.add(layers.Dense(4096, activation='relu')) 
  model.add(layers.Dropout(0.5)) model.add(layers.Dense(2, activation='softmax'))
  
  nTrain=16850 nTest=6667
  
  train_datagen = image.ImageDataGenerator(rescale=1./255)
  
  test_datagen = image.ImageDataGenerator(rescale=1./255)
  
  batch_size = 12 batch_size1 = 12
  
  train_generator = train_datagen.flow_from_directory(train_dir, target_size=(224, 224), batch_size=batch_size, class_mode='categorical', shuffle=False)
  
  test_generator = test_datagen.flow_from_directory(test_dir, target_size=(224, 224), batch_size=batch_size1, class_mode='categorical', shuffle=False)
  
  model.compile(optimizer=optimizers.RMSprop(lr=1e-6), loss='categorical_crossentropy', metrics=['acc'])
  
  history = model.fit_generator( train_generator, steps_per_epoch=train_generator.samples/train_generator.batch_size, epochs=3, validation_data=test_generator, validation_steps=test_generator.samples/test_generator.batch_size, verbose=1)
  
  model.save('gender.h5')
  </code></pre>
  
  <p>Testing Code:</p>
  
  <pre><code>model=load_model('age.h5') 
  img=load_img('9358807_1980-12-28_2010.jpg', target_size=(224,224)) 
  img=img_to_array(img) 
  img=img.reshape((1,img.shape[0],img.shape[1],img.shape[2])) 
  img=preprocess_input(img) 
  yhat=model.predict(img) 
  print(yhat.size) 
  label=decode_predictions(yhat)
  
  label=label[0][0]
  
  print('%s(%.2f%%)'% (label[1],label[2]*100))
  </code></pre>