<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Transfer Learning and Fine Tuning
Train a simple convnet on the MNIST dataset the first 5 digits [0..4].
Freeze convolutional layers and fine-tune dense layers for the classification of digits [5..9].
Using GPU (highly recommended)
-> If using theano backend
Step1:  Settings
Step2:  Dataset Preparation
Step3:  Your Turn
Try to Fine Tune a VGG16 Network
Step4:  ```python
...
...
Plugging new Layers
model.add(Dense(768, activation='sigmoid'))
model.add(Dropout(0.0))
model.add(Dense(768, activation='sigmoid'))
model.add(Dropout(0.0))
model.add(Dense(n_labels, activation='softmax'))
```
<ASSISTANT_TASK:>
Python Code:
import numpy as np
import datetime
np.random.seed(1337)  # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
from numpy import nan
import keras
print keras.__version__
now = datetime.datetime.now
Explanation: Transfer Learning and Fine Tuning
Train a simple convnet on the MNIST dataset the first 5 digits [0..4].
Freeze convolutional layers and fine-tune dense layers for the classification of digits [5..9].
Using GPU (highly recommended)
-> If using theano backend:
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32
End of explanation
now = datetime.datetime.now
batch_size = 128
nb_classes = 5
nb_epoch = 5
# input image dimensions
img_rows, img_cols = 28, 28
# number of convolutional filters to use
nb_filters = 32
# size of pooling area for max pooling
pool_size = 2
# convolution kernel size
kernel_size = 3
if K.image_data_format() == 'channels_first':
    input_shape = (1, img_rows, img_cols)
else:
    input_shape = (img_rows, img_cols, 1)
def train_model(model, train, test, nb_classes):
    
    X_train = train[0].reshape((train[0].shape[0],) + input_shape)
    X_test = test[0].reshape((test[0].shape[0],) + input_shape)
    X_train = X_train.astype('float32')
    X_test = X_test.astype('float32')
    X_train /= 255
    X_test /= 255
    
    print('X_train shape:', X_train.shape)
    print(X_train.shape[0], 'train samples')
    print(X_test.shape[0], 'test samples')
    # convert class vectors to binary class matrices
    Y_train = np_utils.to_categorical(train[1], nb_classes)
    Y_test = np_utils.to_categorical(test[1], nb_classes)
    model.compile(loss='categorical_crossentropy',
                  optimizer='adadelta',
                  metrics=['accuracy'])
    t = now()
    model.fit(X_train, Y_train,
              batch_size=batch_size, nb_epoch=nb_epoch,
              verbose=1,
              validation_data=(X_test, Y_test))
    print('Training time: %s' % (now() - t))
    score = model.evaluate(X_test, Y_test, verbose=0)
    print('Test score:', score[0])
    print('Test accuracy:', score[1])
Explanation: Settings
End of explanation
# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# create two datasets one with digits below 5 and one with 5 and above
X_train_lt5 = X_train[y_train < 5]
y_train_lt5 = y_train[y_train < 5]
X_test_lt5 = X_test[y_test < 5]
y_test_lt5 = y_test[y_test < 5]
X_train_gte5 = X_train[y_train >= 5]
y_train_gte5 = y_train[y_train >= 5] - 5  # make classes start at 0 for
X_test_gte5 = X_test[y_test >= 5]         # np_utils.to_categorical
y_test_gte5 = y_test[y_test >= 5] - 5
# define two groups of layers: feature (convolutions) and classification (dense)
feature_layers = [
    Convolution2D(nb_filters, kernel_size, kernel_size,
                  border_mode='valid',
                  input_shape=input_shape),
    Activation('relu'),
    Convolution2D(nb_filters, kernel_size, kernel_size),
    Activation('relu'),
    MaxPooling2D(pool_size=(pool_size, pool_size)),
    Dropout(0.25),
    Flatten(),
]
classification_layers = [
    Dense(128),
    Activation('relu'),
    Dropout(0.5),
    Dense(nb_classes),
    Activation('softmax')
]
# create complete model
model = Sequential(feature_layers + classification_layers)
# train model for 5-digit classification [0..4]
train_model(model,
            (X_train_lt5, y_train_lt5),
            (X_test_lt5, y_test_lt5), nb_classes)
# freeze feature layers and rebuild model
for l in feature_layers:
    l.trainable = False
# transfer: train dense layers for new classification task [5..9]
train_model(model,
            (X_train_gte5, y_train_gte5),
            (X_test_gte5, y_test_gte5), nb_classes)
Explanation: Dataset Preparation
End of explanation
from keras.applications import VGG16
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
from keras.layers import Input, Flatten, Dense
from keras.models import Model
import numpy as np
#Get back the convolutional part of a VGG network trained on ImageNet
model_vgg16_conv = VGG16(weights='imagenet', include_top=False)
model_vgg16_conv.summary()
#Create your own input format (here 3x200x200)
inp = Input(shape=(48,48,3),name = 'image_input')
#Use the generated model 
output_vgg16_conv = model_vgg16_conv(inp)
#Add the fully-connected layers 
x = Flatten(name='flatten')(output_vgg16_conv)
x = Dense(4096, activation='relu', name='fc1')(x)
x = Dense(4096, activation='relu', name='fc2')(x)
x = Dense(5, activation='softmax', name='predictions')(x)
#Create your own model 
my_model = Model(input=inp, output=x)
#In the summary, weights and layers from VGG part will be hidden, but they will be fit during the training
my_model.summary()
Explanation: Your Turn
Try to Fine Tune a VGG16 Network
End of explanation
import scipy
new_shape = (48,48)
X_train_new = np.empty(shape=(X_train_gte5.shape[0],)+(48,48,3))
for idx in xrange(X_train_gte5.shape[0]):
    X_train_new[idx] = np.resize(scipy.misc.imresize(X_train_gte5[idx], (new_shape)), (48, 48, 3))
    X_train_new[idx] = np.resize(X_train_new[idx], (48, 48, 3))
    
#X_train_new = np.expand_dims(X_train_new, axis=-1)
print X_train_new.shape
X_train_new = X_train_new.astype('float32')
X_train_new /= 255
    
print('X_train shape:', X_train_new.shape)
print(X_train_new.shape[0], 'train samples')
print(X_train_new.shape[0], 'test samples')
# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train_gte5, nb_classes)
Y_test = np_utils.to_categorical(y_test_gte5, nb_classes)
print y_train.shape
my_model.compile(loss='categorical_crossentropy',
                  optimizer='adadelta',
                  metrics=['accuracy'])
my_model.fit(X_train_new, Y_train,
              batch_size=batch_size, nb_epoch=nb_epoch,
              verbose=1)
#print('Training time: %s' % (now() - t))
#score = my_model.evaluate(X_test, Y_test, verbose=0)
#print('Test score:', score[0])
#print('Test accuracy:', score[1])
    
    
    
#train_model(my_model,
#            (X_train_new, y_train_gte5),
#            (X_test_gte5, y_test_gte5), nb_classes)
Explanation: ```python
...
...
Plugging new Layers
model.add(Dense(768, activation='sigmoid'))
model.add(Dropout(0.0))
model.add(Dense(768, activation='sigmoid'))
model.add(Dropout(0.0))
model.add(Dense(n_labels, activation='softmax'))
```
End of explanation
<END_TASK>