In [1]:
%matplotlib inline
import pandas as pd
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from termcolor import colored

face_cascade = cv2.CascadeClassifier('/home/mckc/Downloads/opencv-2.4.13/data/haarcascades_GPU/haarcascade_frontalface_default.xml')

In [2]:
def load_data():
    import pandas as pd
    import numpy as np
    from PIL import Image
    import cv2 
    from skimage.transform import resize
    
    train = pd.read_csv('/home/mckc/TwoClass//train.csv')
    test = pd.read_csv('/home/mckc/TwoClass//test.csv')
    print 'the training data shape is ',train.shape
    print 'the test data shape is ', test.shape
    
    train_faces = np.zeros((1,96,96),dtype=np.uint8)
    Y_train=[]
    missing = []
    multiple = []
    for i in range(train.shape[0]):
        image = np.array(cv2.imread(train.values[i,0], cv2.CV_LOAD_IMAGE_GRAYSCALE))
        #print image
        faces  = face_cascade.detectMultiScale(image,scaleFactor=1.2,minNeighbors=6,minSize=(70, 70))
        n_faces = len(faces)
        if n_faces is 1:
            for (x,y,w,h) in faces:
                fac = np.array(image)[y:(y+h),x:(x+h)]
                out = (resize(fac,(96,96))).reshape((1,96,96))
                train_faces = np.vstack((train_faces,out))
                Y_train = np.append(Y_train,train.values[i,1])
        else:
            if n_faces > 1:
                missing = np.append(missing,i)
            else:
                multiple = np.append(multiple,i)
        if i % 20==0:
            print colored((float(i)/train.shape[0]*100 ,' Percentage complete'), 'green')
    print 'missing count:',len(missing),'\nmuiltiple images count',len(multiple)
    train_faces = train_faces[1:,:,:]
    
    test_faces = np.zeros((1,96,96),dtype=np.uint8)
    Y_test = []
    file_names = []
    for i in range(test.shape[0]):
        image = np.array(cv2.imread(test.values[i,0], cv2.CV_LOAD_IMAGE_GRAYSCALE))
        faces  = face_cascade.detectMultiScale(image,scaleFactor=1.2,minNeighbors=6,minSize=(70, 70))
        n_faces = len(faces)
        if n_faces is 1:
            for (x,y,w,h) in faces:
                fac = np.array(image)[y:(y+h),x:(x+h)]
                out = (resize(fac,(96,96))).reshape((1,96,96))
                test_faces = np.vstack((test_faces,out))
                Y_test = np.append(Y_test,test.values[i,1])
                file_names = np.append(file_names,test.values[i,0])
        else:
            if n_faces > 1:
                missing = np.append(missing,i)
            else:
                multiple = np.append(multiple,i)
        if i % 20==0:
            print colored((float(i)/train.shape[0]*100 ,' Percentage complete'), 'green')
    test_faces = test_faces[1:,:,:]
    print len(missing),len(multiple)
    
    print 'the training file shape',train_faces.shape,Y_train.shape
    print 'the testing file shape',test_faces.shape,Y_test.shape
    
    return train_faces,test_faces,Y_train,Y_test,file_names

In [3]:
def simulate(X,Y):
    import scipy as sp
    import scipy.ndimage
    complete = np.zeros((1,96,96),dtype=np.uint8)
    Y_complete = []
    for i in range(len(X)):
        complete = np.vstack((complete,X[i,:,:].reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(X[i,:,:], angle = 5,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(X[i,:,:], angle = 10,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(X[i,:,:], angle = 15,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(X[i,:,:], angle = -5,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(X[i,:,:], angle = -15,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(X[i,:,:], angle = -10,reshape=False,cval=1).reshape(1,96,96)))
        rotated = np.fliplr(X[i,:,:])
        complete = np.vstack((complete,scipy.ndimage.rotate(rotated, angle = 5,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(rotated, angle = 10,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(rotated, angle = 15,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(rotated, angle = -5,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(rotated, angle = -10,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,scipy.ndimage.rotate(rotated, angle = -15,reshape=False,cval=1).reshape(1,96,96)))
        complete = np.vstack((complete,rotated.reshape(1,96,96)))
        Y_complete = np.append(Y_complete,([Y[i]]*14))
        if i % 10==0:
            print colored((float(i)/len(X)*100 ,' Percentage complete'),'green')
    complete = complete[1:,:,:]
    return complete,Y_complete

In [4]:
X_tr,X_tst,Y_tr,Y_tst,file_names = load_data()


the training data shape is  (159, 2)
the test data shape is  (53, 2)
(0.0, ' Percentage complete')
(12.578616352201259, ' Percentage complete')
(25.157232704402517, ' Percentage complete')
(37.735849056603776, ' Percentage complete')
(50.314465408805034, ' Percentage complete')
(62.893081761006286, ' Percentage complete')
(75.47169811320755, ' Percentage complete')
(88.0503144654088, ' Percentage complete')
missing count: 9 
muiltiple images count 7
(0.0, ' Percentage complete')
(12.578616352201259, ' Percentage complete')
(25.157232704402517, ' Percentage complete')
11 11
the training file shape (143, 96, 96) (143,)
the testing file shape (47, 96, 96) (47,)

In [5]:
import time
start_time = time.clock()
X,Y = simulate(X_tr,Y_tr)
print X.shape,Y.shape
print time.clock() - start_time, "seconds"


(0.0, ' Percentage complete')
(6.993006993006993, ' Percentage complete')
(13.986013986013987, ' Percentage complete')
(20.97902097902098, ' Percentage complete')
(27.972027972027973, ' Percentage complete')
(34.96503496503497, ' Percentage complete')
(41.95804195804196, ' Percentage complete')
(48.95104895104895, ' Percentage complete')
(55.94405594405595, ' Percentage complete')
(62.93706293706294, ' Percentage complete')
(69.93006993006993, ' Percentage complete')
(76.92307692307693, ' Percentage complete')
(83.91608391608392, ' Percentage complete')
(90.9090909090909, ' Percentage complete')
(97.9020979020979, ' Percentage complete')
(2002, 96, 96) (2002,)
21.992412 seconds

In [6]:
def standard(X):
    return (X - X.mean())/X.max()

In [7]:
X_test = standard(X_tst)
X = standard(X)

In [8]:
X_normal = X.reshape(-1,9216)
X_test_normal = X_test.reshape(-1,9216)
map, Y_number = np.unique(Y, return_inverse=True)
Y_test_numer = np.unique(Y_tst, return_inverse=True)[1]

In [9]:
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

clf = LogisticRegression(verbose=0,n_jobs=-1) clf.fit(X_normal,Y_number) Y_logictic= clf.predict(X_test.reshape(-1,9216))

Y_log_vales = map[Y_logictic]

print 'Accuracy of the model is ',accuracy_score(Y_tst,Y_log_vales) confusion_matrix(Y_log_vales,Y_tst)


In [10]:
recognizer = RandomForestClassifier(500,verbose=0,oob_score=True,n_jobs=-1)
recognizer.fit(X_normal,Y_number)

Y_rf= recognizer.predict(X_test.reshape(-1,9216))
Y_rf_vales = map[Y_rf]

print 'Accuracy of the model is ',accuracy_score(Y_tst,Y_rf_vales)
confusion_matrix(Y_tst,Y_rf_vales)


Accuracy of the model is  1.0
Out[10]:
array([[22,  0],
       [ 0, 25]])

In [11]:
importances = recognizer.feature_importances_
importance_image = importances.reshape(96,96)
#plt.figure(figsize=(7,7))
plt.imshow(importance_image,cmap=cm.Greys_r)


Out[11]:
<matplotlib.image.AxesImage at 0x7f5cd3bf0450>

In [12]:
for i in range(len(Y_test_numer)):
    print file_names[i],Y_rf_vales[i]


/home/mckc/TwoClass/Gopika_mobile_3.jpg Gopika
/home/mckc/TwoClass/Gopika_mobile_23.jpg Gopika
/home/mckc/TwoClass/Abhay_specs_6.jpg Abhay
/home/mckc/TwoClass/Gopika_31.jpg Gopika
/home/mckc/TwoClass/Gopika_39.jpg Gopika
/home/mckc/TwoClass/Gopika_17.jpg Gopika
/home/mckc/TwoClass/Abhay_43.jpg Abhay
/home/mckc/TwoClass/Abhay_mobile_6.jpg Abhay
/home/mckc/TwoClass/Gopika_32.jpg Gopika
/home/mckc/TwoClass/Abhay_14.jpg Abhay
/home/mckc/TwoClass/Abhay_32.jpg Abhay
/home/mckc/TwoClass/Abhay_mobile_0.jpg Abhay
/home/mckc/TwoClass/Gopika_mobile_21.jpg Gopika
/home/mckc/TwoClass/Abhay_16.jpg Abhay
/home/mckc/TwoClass/Gopika_specs_cap_6.jpg Gopika
/home/mckc/TwoClass/Abhay_29.jpg Abhay
/home/mckc/TwoClass/Gopika_specs_9.jpg Gopika
/home/mckc/TwoClass/Abhay_1.jpg Abhay
/home/mckc/TwoClass/Gopika_mobile_4.jpg Gopika
/home/mckc/TwoClass/Gopika_specs_11.jpg Gopika
/home/mckc/TwoClass/Gopika_5.jpg Gopika
/home/mckc/TwoClass/Abhay_specs_3.jpg Abhay
/home/mckc/TwoClass/Gopika_25.jpg Gopika
/home/mckc/TwoClass/Gopika_22.jpg Gopika
/home/mckc/TwoClass/Gopika_mobile_20.jpg Gopika
/home/mckc/TwoClass/Abhay_cap_specs_0.jpg Abhay
/home/mckc/TwoClass/Gopika_40.jpg Gopika
/home/mckc/TwoClass/Gopika_mobile_11.jpg Gopika
/home/mckc/TwoClass/Abhay_22.jpg Abhay
/home/mckc/TwoClass/Gopika_mobile_13.jpg Gopika
/home/mckc/TwoClass/Gopika_37.jpg Gopika
/home/mckc/TwoClass/Abhay_12.jpg Abhay
/home/mckc/TwoClass/Abhay_23.jpg Abhay
/home/mckc/TwoClass/Gopika_11.jpg Gopika
/home/mckc/TwoClass/Gopika_19.jpg Gopika
/home/mckc/TwoClass/Abhay_44.jpg Abhay
/home/mckc/TwoClass/Gopika_9.jpg Gopika
/home/mckc/TwoClass/Abhay_cap_specs_5.jpg Abhay
/home/mckc/TwoClass/Abhay_25.jpg Abhay
/home/mckc/TwoClass/Abhay_specs_8.jpg Abhay
/home/mckc/TwoClass/Abhay_20.jpg Abhay
/home/mckc/TwoClass/Abhay_45.jpg Abhay
/home/mckc/TwoClass/Gopika_44.jpg Gopika
/home/mckc/TwoClass/Abhay__8.jpg Abhay
/home/mckc/TwoClass/Abhay_34.jpg Abhay
/home/mckc/TwoClass/Gopika_mobile_2.jpg Gopika
/home/mckc/TwoClass/Gopika_specs_cap_10.jpg Gopika

In [22]:
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras import backend as K
from keras.optimizers import Adam,SGD
from keras.utils import np_utils
from keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='val_loss', patience=2)


Y_Keras = np_utils.to_categorical(Y_number, 2)
# Create first network with Keras
from keras.models import Sequential
from keras.layers import Dense, Activation,Dropout
model = Sequential()
model.add(Dense(1000, input_dim=9216,activation='sigmoid'))
#model.add(Dense(500,activation='sigmoid'))
model.add(Dense(1000,activation='relu'))
model.add(Dense(2,activation='softmax'))
sgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)

# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

import time
model.fit(X.reshape(-1,9216), Y_Keras, nb_epoch=30, batch_size=5,verbose=1
         ,validation_data=(X_test.reshape(-1,9216), np_utils.to_categorical(Y_test_numer, 2)))

Y_kr= model.predict_classes(X_test.reshape(-1,9216))
Y_kr_vales = map[Y_kr]

print 'Accuracy of the model is ',accuracy_score(Y_tst,Y_kr_vales,'\n')
confusion_matrix(Y_tst,Y_kr_vales)


Train on 2002 samples, validate on 47 samples
Epoch 1/30
2002/2002 [==============================] - 3s - loss: 0.0640 - acc: 0.9810 - val_loss: 0.2519 - val_acc: 0.9787
Epoch 2/30
2002/2002 [==============================] - 3s - loss: 0.0031 - acc: 0.9990 - val_loss: 6.6444e-07 - val_acc: 1.0000
Epoch 3/30
2002/2002 [==============================] - 3s - loss: 4.9476e-05 - acc: 1.0000 - val_loss: 4.7923e-07 - val_acc: 1.0000
Epoch 4/30
2002/2002 [==============================] - 3s - loss: 2.5371e-07 - acc: 1.0000 - val_loss: 8.8762e-07 - val_acc: 1.0000
Epoch 5/30
2002/2002 [==============================] - 3s - loss: 1.3572e-07 - acc: 1.0000 - val_loss: 1.0170e-06 - val_acc: 1.0000
Epoch 6/30
2002/2002 [==============================] - 3s - loss: 8.6512e-08 - acc: 1.0000 - val_loss: 8.2928e-07 - val_acc: 1.0000
Epoch 7/30
2002/2002 [==============================] - 3s - loss: 7.6085e-08 - acc: 1.0000 - val_loss: 6.9234e-07 - val_acc: 1.0000
Epoch 8/30
2002/2002 [==============================] - 3s - loss: 7.2869e-08 - acc: 1.0000 - val_loss: 6.3648e-07 - val_acc: 1.0000
Epoch 9/30
2002/2002 [==============================] - 3s - loss: 7.1021e-08 - acc: 1.0000 - val_loss: 6.1621e-07 - val_acc: 1.0000
Epoch 10/30
2002/2002 [==============================] - 3s - loss: 7.0068e-08 - acc: 1.0000 - val_loss: 4.4372e-07 - val_acc: 1.0000
Epoch 11/30
2002/2002 [==============================] - 3s - loss: 6.9351e-08 - acc: 1.0000 - val_loss: 4.3355e-07 - val_acc: 1.0000
Epoch 12/30
2002/2002 [==============================] - 3s - loss: 6.9112e-08 - acc: 1.0000 - val_loss: 3.8798e-07 - val_acc: 1.0000
Epoch 13/30
2002/2002 [==============================] - 3s - loss: 6.8874e-08 - acc: 1.0000 - val_loss: 3.4484e-07 - val_acc: 1.0000
Epoch 14/30
2002/2002 [==============================] - 3s - loss: 6.8635e-08 - acc: 1.0000 - val_loss: 3.3977e-07 - val_acc: 1.0000
Epoch 15/30
2002/2002 [==============================] - 3s - loss: 6.8516e-08 - acc: 1.0000 - val_loss: 2.9154e-07 - val_acc: 1.0000
Epoch 16/30
2002/2002 [==============================] - 3s - loss: 6.8396e-08 - acc: 1.0000 - val_loss: 2.6110e-07 - val_acc: 1.0000
Epoch 17/30
2002/2002 [==============================] - 3s - loss: 6.8336e-08 - acc: 1.0000 - val_loss: 2.4844e-07 - val_acc: 1.0000
Epoch 18/30
2002/2002 [==============================] - 3s - loss: 6.8336e-08 - acc: 1.0000 - val_loss: 2.3062e-07 - val_acc: 1.0000
Epoch 19/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 2.2819e-07 - val_acc: 1.0000
Epoch 20/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 2.2819e-07 - val_acc: 1.0000
Epoch 21/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 2.3827e-07 - val_acc: 1.0000
Epoch 22/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 2.2819e-07 - val_acc: 1.0000
Epoch 23/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 2.0532e-07 - val_acc: 1.0000
Epoch 24/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 1.9006e-07 - val_acc: 1.0000
Epoch 25/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 1.9006e-07 - val_acc: 1.0000
Epoch 26/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 1.9006e-07 - val_acc: 1.0000
Epoch 27/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 1.9006e-07 - val_acc: 1.0000
Epoch 28/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 1.9006e-07 - val_acc: 1.0000
Epoch 29/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 1.9006e-07 - val_acc: 1.0000
Epoch 30/30
2002/2002 [==============================] - 3s - loss: 6.8276e-08 - acc: 1.0000 - val_loss: 1.9006e-07 - val_acc: 1.0000
32/47 [===================>..........] - ETA: 0sAccuracy of the model is  1.0
Out[22]:
array([[22,  0],
       [ 0, 25]])

In [26]:
import lasagne
from lasagne.layers.cuda_convnet import Conv2DCCLayer as Conv2DLayer
from lasagne.layers.cuda_convnet import MaxPool2DCCLayer as MaxPool2DLayer
from lasagne import layers
from lasagne.objectives import categorical_crossentropy
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import BatchIterator,visualize,NeuralNet
#Conv2DLayer = layers.Conv2DLayer
#MaxPool2DLayer = layers.MaxPool2DLayer

net = NeuralNet(
    layers=[
        ('input', layers.InputLayer),
        ('conv1', Conv2DLayer),
        ('pool1', MaxPool2DLayer),
        ('dropout1', layers.DropoutLayer),
        ('conv2', Conv2DLayer),
        ('pool2', MaxPool2DLayer),
        ('dropout2', layers.DropoutLayer),
        ('conv3', Conv2DLayer),
        ('pool3', MaxPool2DLayer),
        ('dropout3', layers.DropoutLayer),
        ('hidden4', layers.DenseLayer),
        ('dropout4', layers.DropoutLayer),
        ('hidden5', layers.DenseLayer),
        ('output', layers.DenseLayer),
        ],
    input_shape=(None, 1, 96, 96),
    conv1_num_filters=32, conv1_filter_size=(3, 3), pool1_pool_size=(2, 2),
    dropout1_p=0.1,
    conv2_num_filters=64, conv2_filter_size=(2, 2), pool2_pool_size=(2, 2),
    dropout2_p=0.2,
    conv3_num_filters=128, conv3_filter_size=(2, 2), pool3_pool_size=(2, 2),
    dropout3_p=0.3,
    hidden4_num_units=1000,
    dropout4_p=0.5,
    hidden5_num_units=1000,
    output_nonlinearity=lasagne.nonlinearities.softmax,
    output_num_units=2,
    
    update = nesterov_momentum,
    update_learning_rate=0.001,
    update_momentum=0.9,
    max_epochs=30,
    verbose=1
)
net.fit(X.reshape(-1,1,96,96).astype(np.float32), Y_number.astype(np.uint8))

Y_las= net.predict(X_test.reshape(-1,9216))
Y_las_vales = map[Y_kr]

print 'Accuracy of the model is ',accuracy_score(Y_tst,Y_las_vales,'\n')
confusion_matrix(Y_tst,Y_las_vales)


# Neural Network with 16533474 learnable parameters

## Layer information

  #  name      size
---  --------  ---------
  0  input     1x96x96
  1  conv1     32x94x94
  2  pool1     32x47x47
  3  dropout1  32x47x47
  4  conv2     64x46x46
  5  pool2     64x23x23
  6  dropout2  64x23x23
  7  conv3     128x22x22
  8  pool3     128x11x11
  9  dropout3  128x11x11
 10  hidden4   1000
 11  dropout4  1000
 12  hidden5   1000
 13  output    2

  epoch    trn loss    val loss    trn/val    valid acc  dur
-------  ----------  ----------  ---------  -----------  -----
      1     0.69169     0.68892    1.00401      0.56683  2.54s
      2     0.68811     0.68556    1.00373      0.78713  2.53s
      3     0.68529     0.68165    1.00534      0.96287  2.53s
      4     0.67999     0.67738    1.00386      0.96782  2.54s
      5     0.67636     0.67261    1.00558      0.96782  2.54s
      6     0.67001     0.66688    1.00470      0.96782  2.54s
      7     0.66392     0.65986    1.00615      0.96535  2.53s
      8     0.65651     0.65113    1.00826      0.96535  2.54s
      9     0.64594     0.63982    1.00956      0.96535  2.53s
     10     0.63374     0.62502    1.01395      0.96535  2.54s
     11     0.61581     0.60546    1.01709      0.97030  2.54s
     12     0.59326     0.57840    1.02569      0.97030  2.53s
     13     0.56124     0.54094    1.03754      0.97030  2.54s
     14     0.51788     0.48877    1.05957      0.97277  2.53s
     15     0.45555     0.41869    1.08805      0.97525  2.53s
     16     0.37775     0.33316    1.13382      0.97525  2.53s
     17     0.29782     0.24610    1.21015      0.97525  2.53s
     18     0.21832     0.17465    1.25002      0.97525  2.53s
     19     0.16162     0.12656    1.27699      0.97525  2.53s
     20     0.12564     0.09754    1.28808      0.97525  2.54s
     21     0.10326     0.08040    1.28436      0.97525  2.54s
     22     0.09027     0.06989    1.29162      0.97525  2.54s
     23     0.07668     0.06321    1.21321      0.97525  2.54s
     24     0.07551     0.05823    1.29669      0.97772  2.54s
     25     0.06740     0.05496    1.22622      0.97772  2.54s
     26     0.05510     0.05247    1.05017      0.97525  2.54s
     27     0.05936     0.04908    1.20953      0.97772  2.54s
     28     0.05180     0.04738    1.09318      0.97772  2.53s
     29     0.04803     0.04620    1.03967      0.97772  2.54s
     30     0.04848     0.04490    1.07991      0.97772  2.53s
Out[26]:
NeuralNet(X_tensor_type=None,
     batch_iterator_test=<nolearn.lasagne.base.BatchIterator object at 0x7fb380563790>,
     batch_iterator_train=<nolearn.lasagne.base.BatchIterator object at 0x7fb380563650>,
     check_input=True, conv1_filter_size=(3, 3), conv1_num_filters=32,
     conv2_filter_size=(2, 2), conv2_num_filters=64,
     conv3_filter_size=(2, 2), conv3_num_filters=128, custom_scores=None,
     dropout1_p=0.1, dropout2_p=0.2, dropout3_p=0.3, dropout4_p=0.5,
     hidden4_num_units=1000, hidden5_num_units=1000,
     input_shape=(None, 1, 96, 96),
     layers=[('input', <class 'lasagne.layers.input.InputLayer'>), ('conv1', <class 'lasagne.layers.cuda_convnet.Conv2DCCLayer'>), ('pool1', <class 'lasagne.layers.cuda_convnet.MaxPool2DCCLayer'>), ('dropout1', <class 'lasagne.layers.noise.DropoutLayer'>), ('conv2', <class 'lasagne.layers.cuda_convnet.Co..., <class 'lasagne.layers.dense.DenseLayer'>), ('output', <class 'lasagne.layers.dense.DenseLayer'>)],
     loss=None, max_epochs=30, more_params={},
     objective=<function objective at 0x7fb38055fde8>,
     objective_loss_function=<function categorical_crossentropy at 0x7fb3805e0d70>,
     on_batch_finished=[],
     on_epoch_finished=[<nolearn.lasagne.handlers.PrintLog instance at 0x7fb3130cfe18>],
     on_training_finished=[],
     on_training_started=[<nolearn.lasagne.handlers.PrintLayerInfo instance at 0x7fb325addb90>],
     output_nonlinearity=<function softmax at 0x7fb380828f50>,
     output_num_units=2, pool1_pool_size=(2, 2), pool2_pool_size=(2, 2),
     pool3_pool_size=(2, 2), regression=False, scores_train=[],
     scores_valid=[],
     train_split=<nolearn.lasagne.base.TrainSplit object at 0x7fb380563810>,
     update=<function nesterov_momentum at 0x7fb3805efaa0>,
     update_learning_rate=0.001, update_momentum=0.9,
     use_label_encoder=False, verbose=1,
     y_tensor_type=TensorType(int32, vector))

In [25]:
def plot_loss(net):
    train_loss = [row['train_loss'] for row in net.train_history_]
    valid_loss = [row['valid_loss'] for row in net.train_history_]
    plt.plot(train_loss, label='train loss')
    plt.plot(valid_loss, label='valid loss')
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.legend(loc='best')
    return plt
plot_loss(net)


Out[25]:
<module 'matplotlib.pyplot' from '/home/mckc/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.pyc'>

In [29]:



Train on 2016 samples, validate on 47 samples
Epoch 1/30
2016/2016 [==============================] - 9s - loss: 0.0425 - acc: 0.9866 - val_loss: 4.8941 - val_acc: 0.3404
Epoch 2/30
2016/2016 [==============================] - 9s - loss: 0.0022 - acc: 1.0000 - val_loss: 6.0184 - val_acc: 0.3404
Epoch 3/30
2016/2016 [==============================] - 9s - loss: 8.8368e-04 - acc: 1.0000 - val_loss: 6.3761 - val_acc: 0.3404
Epoch 4/30
2016/2016 [==============================] - 9s - loss: 5.6341e-04 - acc: 1.0000 - val_loss: 6.6288 - val_acc: 0.3404
Epoch 5/30
2016/2016 [==============================] - 9s - loss: 4.2142e-04 - acc: 1.0000 - val_loss: 6.8067 - val_acc: 0.3404
Epoch 6/30
2016/2016 [==============================] - 9s - loss: 3.3960e-04 - acc: 1.0000 - val_loss: 6.9632 - val_acc: 0.3404
Epoch 7/30
2016/2016 [==============================] - 9s - loss: 2.8831e-04 - acc: 1.0000 - val_loss: 7.0738 - val_acc: 0.3404
Epoch 8/30
2016/2016 [==============================] - 9s - loss: 2.4627e-04 - acc: 1.0000 - val_loss: 7.1567 - val_acc: 0.3404
Epoch 9/30
2016/2016 [==============================] - 9s - loss: 2.1489e-04 - acc: 1.0000 - val_loss: 7.2485 - val_acc: 0.3404
Epoch 10/30
2016/2016 [==============================] - 9s - loss: 1.9237e-04 - acc: 1.0000 - val_loss: 7.3268 - val_acc: 0.3404
Epoch 11/30
2016/2016 [==============================] - 9s - loss: 1.7142e-04 - acc: 1.0000 - val_loss: 7.3801 - val_acc: 0.3404
Epoch 12/30
2016/2016 [==============================] - 9s - loss: 1.5651e-04 - acc: 1.0000 - val_loss: 7.4432 - val_acc: 0.3404
Epoch 13/30
2016/2016 [==============================] - 9s - loss: 1.4304e-04 - acc: 1.0000 - val_loss: 7.5077 - val_acc: 0.3404
Epoch 14/30
2016/2016 [==============================] - 9s - loss: 1.3167e-04 - acc: 1.0000 - val_loss: 7.5586 - val_acc: 0.3404
Epoch 15/30
2016/2016 [==============================] - 9s - loss: 1.2128e-04 - acc: 1.0000 - val_loss: 7.5912 - val_acc: 0.3404
Epoch 16/30
2016/2016 [==============================] - 9s - loss: 1.1347e-04 - acc: 1.0000 - val_loss: 7.6409 - val_acc: 0.3404
Epoch 17/30
2016/2016 [==============================] - 9s - loss: 1.0584e-04 - acc: 1.0000 - val_loss: 7.6775 - val_acc: 0.3404
Epoch 18/30
2016/2016 [==============================] - 9s - loss: 9.9481e-05 - acc: 1.0000 - val_loss: 7.7183 - val_acc: 0.3404
Epoch 19/30
2016/2016 [==============================] - 9s - loss: 9.3549e-05 - acc: 1.0000 - val_loss: 7.7555 - val_acc: 0.3404
Epoch 20/30
2016/2016 [==============================] - 9s - loss: 8.8415e-05 - acc: 1.0000 - val_loss: 7.7836 - val_acc: 0.3404
Epoch 21/30
2016/2016 [==============================] - 9s - loss: 8.3776e-05 - acc: 1.0000 - val_loss: 7.8155 - val_acc: 0.3404
Epoch 22/30
2009/2016 [============================>.] - ETA: 0s - loss: 7.9509e-05 - acc: 1.0000
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-d79441e8c5e4> in <module>()
     22 import time
     23 model.fit(X.reshape(-1,9216), Y_Keras, nb_epoch=30, batch_size=1,verbose=1
---> 24          ,validation_data=(X_test.reshape(-1,9216), np_utils.to_categorical(Y_test_numer, 2)))

/home/mckc/anaconda/lib/python2.7/site-packages/keras/models.pyc in fit(self, x, y, batch_size, nb_epoch, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, **kwargs)
    618                               shuffle=shuffle,
    619                               class_weight=class_weight,
--> 620                               sample_weight=sample_weight)
    621 
    622     def evaluate(self, x, y, batch_size=32, verbose=1,

/home/mckc/anaconda/lib/python2.7/site-packages/keras/engine/training.pyc in fit(self, x, y, batch_size, nb_epoch, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight)
   1102                               verbose=verbose, callbacks=callbacks,
   1103                               val_f=val_f, val_ins=val_ins, shuffle=shuffle,
-> 1104                               callback_metrics=callback_metrics)
   1105 
   1106     def evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None):

/home/mckc/anaconda/lib/python2.7/site-packages/keras/engine/training.pyc in _fit_loop(self, f, ins, out_labels, batch_size, nb_epoch, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics)
    826                     batch_logs[l] = o
    827 
--> 828                 callbacks.on_batch_end(batch_index, batch_logs)
    829 
    830                 if batch_index == len(batches) - 1:  # last batch

/home/mckc/anaconda/lib/python2.7/site-packages/keras/callbacks.pyc in on_batch_end(self, batch, logs)
     59         t_before_callbacks = time.time()
     60         for callback in self.callbacks:
---> 61             callback.on_batch_end(batch, logs)
     62         self._delta_ts_batch_end.append(time.time() - t_before_callbacks)
     63         delta_t_median = np.median(self._delta_ts_batch_end)

/home/mckc/anaconda/lib/python2.7/site-packages/keras/callbacks.pyc in on_batch_end(self, batch, logs)
    187         # will be handled by on_epoch_end
    188         if self.verbose and self.seen < self.params['nb_sample']:
--> 189             self.progbar.update(self.seen, self.log_values)
    190 
    191     def on_epoch_end(self, epoch, logs={}):

/home/mckc/anaconda/lib/python2.7/site-packages/keras/utils/generic_utils.pyc in update(self, current, values, force)
     74             prev_total_width = self.total_width
     75             sys.stdout.write("\b" * prev_total_width)
---> 76             sys.stdout.write("\r")
     77 
     78             numdigits = int(np.floor(np.log10(self.target))) + 1

/home/mckc/anaconda/lib/python2.7/site-packages/ipykernel/iostream.pyc in write(self, string)
    315 
    316             is_child = (not self._is_master_process())
--> 317             self._buffer.write(string)
    318             if is_child:
    319                 # newlines imply flush in subprocesses

ValueError: I/O operation on closed file

In [16]:
from PIL import Image
from skimage.transform import resize
jpgfile = Image.open("/home/mckc/Downloads/1.jpg")
grey = rgb2gray(np.array(jpgfile))
faces  = face_cascade.detectMultiScale(grey.astype(np.uint8),scaleFactor=1.1,minNeighbors=3,minSize=(30, 30))
print faces


for (x,y,w,h) in faces:
    fac = np.array(grey[y:(y+h),x:(x+h)])
    out = resize(fac,(96,96))
    
plt.imshow(out,cmap=cm.Greys_r)


trial = standard(out)
print 'Linear Regression Value',map,clf.predict_proba(trial.reshape(-1,9216)),map[clf.predict((trial.reshape(-1,9216)))]
print 'Random Forest Value',map,recognizer.predict_proba(trial.reshape(-1,9216)),map[recognizer
                                                                                     .predict((trial.reshape(-1,9216)))]
print 'Lasagne Value',map,net.predict_proba(trial.reshape(-1,1,96,96).astype(np.float16)),map[net.predict((trial.reshape(-1,1,96,96).astype(np.float16)))]
print 'Keras Value',map,model.predict(trial.reshape(-1,9216).astype(np.float64))


[[70 37 59 59]]
Linear Regression Value ['Abhay' 'Gopika'] [[ 0.92610094  0.07389906]] ['Abhay']
Random Forest Value ['Abhay' 'Gopika'] [[ 0.498  0.502]]
[Parallel(n_jobs=5)]: Done  40 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 190 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 440 tasks      | elapsed:    0.1s
[Parallel(n_jobs=5)]: Done 500 out of 500 | elapsed:    0.1s finished
[Parallel(n_jobs=5)]: Done  40 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 190 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 440 tasks      | elapsed:    0.1s
[Parallel(n_jobs=5)]: Done 500 out of 500 | elapsed:    0.1s finished
 ['Gopika']
Lasagne Value ['Abhay' 'Gopika'] [[ 0.95883393  0.04116604]] ['Abhay']
Keras Value ['Abhay' 'Gopika'] [[ 0.80408061  0.19591942]]

In [17]:
from PIL import Image
from skimage.transform import resize
jpgfile = Image.open("/home/mckc/Downloads/2.jpg")
grey = rgb2gray(np.array(jpgfile))
faces  = face_cascade.detectMultiScale(grey.astype(np.uint8),scaleFactor=1.1,minNeighbors=4,minSize=(30, 30))
print faces


for (x,y,w,h) in faces:
    fac = np.array(grey[y:(y+h),x:(x+h)])
    out = resize(fac,(96,96))
    
plt.imshow(out,cmap=cm.Greys_r)


trial = standard(out)
print 'Linear Regression Value',map,clf.predict_proba(trial.reshape(-1,9216)),map[clf.predict((trial.reshape(-1,9216)))]
print 'Random Forest Value',map,recognizer.predict_proba(trial.reshape(-1,9216)),map[recognizer
                                                                                     .predict((trial.reshape(-1,9216)))]
print 'Lasagne Value',map,net.predict_proba(trial.reshape(-1,1,96,96).astype(np.float16)),map[net.predict((trial.reshape(-1,1,96,96).astype(np.float16)))]
print 'Keras Value',map,model.predict(trial.reshape(-1,9216).astype(np.float64))


[[372 287  64  64]
 [ 43 135 321 321]]
Linear Regression Value ['Abhay' 'Gopika'] [[  1.12036980e-06   9.99998880e-01]] ['Gopika']
Random Forest Value ['Abhay' 'Gopika'] [[ 0.08  0.92]]
[Parallel(n_jobs=5)]: Done  40 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 190 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 440 tasks      | elapsed:    0.1s
[Parallel(n_jobs=5)]: Done 500 out of 500 | elapsed:    0.1s finished
[Parallel(n_jobs=5)]: Done  40 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 190 tasks      | elapsed:    0.0s
[Parallel(n_jobs=5)]: Done 440 tasks      | elapsed:    0.1s
[Parallel(n_jobs=5)]: Done 500 out of 500 | elapsed:    0.1s finished
 ['Gopika']
Lasagne Value ['Abhay' 'Gopika'] [[  1.42235919e-07   9.99999881e-01]] ['Gopika']
Keras Value ['Abhay' 'Gopika'] [[  1.73029803e-05   9.99982715e-01]]

In [26]:
import sys
sys.setrecursionlimit(150000)

In [35]:
from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

In [30]:
import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
    cPickle.dump(model, fid)    

# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
    gnb_loaded = cPickle.load(fid)

In [34]:
model = load_model('my_model.h5')


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-34-4068f221f547> in <module>()
----> 1 model = load_model('my_model.h5')

/home/mckc/anaconda/lib/python2.7/site-packages/keras/models.pyc in load_model(filepath, custom_objects)
    119 
    120     import h5py
--> 121     f = h5py.File(filepath, mode='r')
    122 
    123     # instantiate model

/home/mckc/anaconda/lib/python2.7/site-packages/h5py/_hl/files.pyc in __init__(self, name, mode, driver, libver, userblock_size, swmr, **kwds)
    258 
    259                 fapl = make_fapl(driver, libver, **kwds)
--> 260                 fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr)
    261 
    262                 if swmr_support:

/home/mckc/anaconda/lib/python2.7/site-packages/h5py/_hl/files.pyc in make_fid(name, mode, userblock_size, fapl, fcpl, swmr)
     87         if swmr and swmr_support:
     88             flags |= h5f.ACC_SWMR_READ
---> 89         fid = h5f.open(name, flags, fapl=fapl)
     90     elif mode == 'r+':
     91         fid = h5f.open(name, h5f.ACC_RDWR, fapl=fapl)

h5py/_objects.pyx in h5py._objects.with_phil.wrapper (/home/ilan/minonda/conda-bld/work/h5py/_objects.c:2579)()

h5py/_objects.pyx in h5py._objects.with_phil.wrapper (/home/ilan/minonda/conda-bld/work/h5py/_objects.c:2538)()

h5py/h5f.pyx in h5py.h5f.open (/home/ilan/minonda/conda-bld/work/h5py/h5f.c:1816)()

IOError: Unable to open file (Unable to open file: name = 'my_model.h5', errno = 2, error message = 'no such file or directory', flags = 0, o_flags = 0)

In [ ]: