Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/C4 - Convolutional Neural Networks/Week 4/Face Recognition/fr_utils.py
Views: 4804
#### PART OF THIS CODE IS USING CODE FROM VICTOR SY WANG: https://github.com/iwantooxxoox/Keras-OpenFace/blob/master/utils.py ####12import tensorflow as tf3import numpy as np4import os5#import cv26from numpy import genfromtxt7from tensorflow.keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate8from tensorflow.keras.models import Model9from tensorflow.keras.layers import BatchNormalization10from tensorflow.keras.layers import MaxPooling2D, AveragePooling2D11import h5py12import matplotlib.pyplot as plt13import PIL14from tensorflow.keras import backend as K1516K.set_image_data_format('channels_first')171819_FLOATX = 'float32'2021def variable(value, dtype=_FLOATX, name=None):22v = tf.Variable(np.asarray(value, dtype=dtype), name=name)23_get_session().run(v.initializer)24return v2526def shape(x):27return x.get_shape()2829def square(x):30return tf.square(x)3132def zeros(shape, dtype=_FLOATX, name=None):33return variable(np.zeros(shape), dtype, name)3435def concatenate(tensors, axis=-1):36if axis < 0:37axis = axis % len(tensors[0].get_shape())38return tf.concat(axis, tensors)3940def LRN2D(x):41return tf.nn.lrn(x, alpha=1e-4, beta=0.75)4243def conv2d_bn(x,44layer=None,45cv1_out=None,46cv1_filter=(1, 1),47cv1_strides=(1, 1),48cv2_out=None,49cv2_filter=(3, 3),50cv2_strides=(1, 1),51padding=None):52num = '' if cv2_out == None else '1'53tensor = Conv2D(cv1_out, cv1_filter, strides=cv1_strides, data_format='channels_first', name=layer+'_conv'+num)(x)54tensor = BatchNormalization(axis=1, epsilon=0.00001, name=layer+'_bn'+num)(tensor)55tensor = Activation('relu')(tensor)56if padding == None:57return tensor58tensor = ZeroPadding2D(padding=padding, data_format='channels_first')(tensor)59if cv2_out == None:60return tensor61tensor = Conv2D(cv2_out, cv2_filter, strides=cv2_strides, data_format='channels_first', name=layer+'_conv'+'2')(tensor)62tensor = BatchNormalization(axis=1, epsilon=0.00001, name=layer+'_bn'+'2')(tensor)63tensor = Activation('relu')(tensor)64return tensor6566WEIGHTS = [67'conv1', 'bn1', 'conv2', 'bn2', 'conv3', 'bn3',68'inception_3a_1x1_conv', 'inception_3a_1x1_bn',69'inception_3a_pool_conv', 'inception_3a_pool_bn',70'inception_3a_5x5_conv1', 'inception_3a_5x5_conv2', 'inception_3a_5x5_bn1', 'inception_3a_5x5_bn2',71'inception_3a_3x3_conv1', 'inception_3a_3x3_conv2', 'inception_3a_3x3_bn1', 'inception_3a_3x3_bn2',72'inception_3b_3x3_conv1', 'inception_3b_3x3_conv2', 'inception_3b_3x3_bn1', 'inception_3b_3x3_bn2',73'inception_3b_5x5_conv1', 'inception_3b_5x5_conv2', 'inception_3b_5x5_bn1', 'inception_3b_5x5_bn2',74'inception_3b_pool_conv', 'inception_3b_pool_bn',75'inception_3b_1x1_conv', 'inception_3b_1x1_bn',76'inception_3c_3x3_conv1', 'inception_3c_3x3_conv2', 'inception_3c_3x3_bn1', 'inception_3c_3x3_bn2',77'inception_3c_5x5_conv1', 'inception_3c_5x5_conv2', 'inception_3c_5x5_bn1', 'inception_3c_5x5_bn2',78'inception_4a_3x3_conv1', 'inception_4a_3x3_conv2', 'inception_4a_3x3_bn1', 'inception_4a_3x3_bn2',79'inception_4a_5x5_conv1', 'inception_4a_5x5_conv2', 'inception_4a_5x5_bn1', 'inception_4a_5x5_bn2',80'inception_4a_pool_conv', 'inception_4a_pool_bn',81'inception_4a_1x1_conv', 'inception_4a_1x1_bn',82'inception_4e_3x3_conv1', 'inception_4e_3x3_conv2', 'inception_4e_3x3_bn1', 'inception_4e_3x3_bn2',83'inception_4e_5x5_conv1', 'inception_4e_5x5_conv2', 'inception_4e_5x5_bn1', 'inception_4e_5x5_bn2',84'inception_5a_3x3_conv1', 'inception_5a_3x3_conv2', 'inception_5a_3x3_bn1', 'inception_5a_3x3_bn2',85'inception_5a_pool_conv', 'inception_5a_pool_bn',86'inception_5a_1x1_conv', 'inception_5a_1x1_bn',87'inception_5b_3x3_conv1', 'inception_5b_3x3_conv2', 'inception_5b_3x3_bn1', 'inception_5b_3x3_bn2',88'inception_5b_pool_conv', 'inception_5b_pool_bn',89'inception_5b_1x1_conv', 'inception_5b_1x1_bn',90'dense_layer'91]9293conv_shape = {94'conv1': [64, 3, 7, 7],95'conv2': [64, 64, 1, 1],96'conv3': [192, 64, 3, 3],97'inception_3a_1x1_conv': [64, 192, 1, 1],98'inception_3a_pool_conv': [32, 192, 1, 1],99'inception_3a_5x5_conv1': [16, 192, 1, 1],100'inception_3a_5x5_conv2': [32, 16, 5, 5],101'inception_3a_3x3_conv1': [96, 192, 1, 1],102'inception_3a_3x3_conv2': [128, 96, 3, 3],103'inception_3b_3x3_conv1': [96, 256, 1, 1],104'inception_3b_3x3_conv2': [128, 96, 3, 3],105'inception_3b_5x5_conv1': [32, 256, 1, 1],106'inception_3b_5x5_conv2': [64, 32, 5, 5],107'inception_3b_pool_conv': [64, 256, 1, 1],108'inception_3b_1x1_conv': [64, 256, 1, 1],109'inception_3c_3x3_conv1': [128, 320, 1, 1],110'inception_3c_3x3_conv2': [256, 128, 3, 3],111'inception_3c_5x5_conv1': [32, 320, 1, 1],112'inception_3c_5x5_conv2': [64, 32, 5, 5],113'inception_4a_3x3_conv1': [96, 640, 1, 1],114'inception_4a_3x3_conv2': [192, 96, 3, 3],115'inception_4a_5x5_conv1': [32, 640, 1, 1,],116'inception_4a_5x5_conv2': [64, 32, 5, 5],117'inception_4a_pool_conv': [128, 640, 1, 1],118'inception_4a_1x1_conv': [256, 640, 1, 1],119'inception_4e_3x3_conv1': [160, 640, 1, 1],120'inception_4e_3x3_conv2': [256, 160, 3, 3],121'inception_4e_5x5_conv1': [64, 640, 1, 1],122'inception_4e_5x5_conv2': [128, 64, 5, 5],123'inception_5a_3x3_conv1': [96, 1024, 1, 1],124'inception_5a_3x3_conv2': [384, 96, 3, 3],125'inception_5a_pool_conv': [96, 1024, 1, 1],126'inception_5a_1x1_conv': [256, 1024, 1, 1],127'inception_5b_3x3_conv1': [96, 736, 1, 1],128'inception_5b_3x3_conv2': [384, 96, 3, 3],129'inception_5b_pool_conv': [96, 736, 1, 1],130'inception_5b_1x1_conv': [256, 736, 1, 1],131}132133def load_weights_from_FaceNet(FRmodel):134# Load weights from csv files (which was exported from Openface torch model)135weights = WEIGHTS136weights_dict = load_weights()137138# Set layer weights of the model139for name in weights:140if FRmodel.get_layer(name) != None:141FRmodel.get_layer(name).set_weights(weights_dict[name])142elif model.get_layer(name) != None:143model.get_layer(name).set_weights(weights_dict[name])144145def load_weights():146# Set weights path147dirPath = './weights'148fileNames = filter(lambda f: not f.startswith('.'), os.listdir(dirPath))149paths = {}150weights_dict = {}151152for n in fileNames:153paths[n.replace('.csv', '')] = dirPath + '/' + n154155for name in WEIGHTS:156if 'conv' in name:157conv_w = genfromtxt(paths[name + '_w'], delimiter=',', dtype=None)158conv_w = np.reshape(conv_w, conv_shape[name])159conv_w = np.transpose(conv_w, (2, 3, 1, 0))160conv_b = genfromtxt(paths[name + '_b'], delimiter=',', dtype=None)161weights_dict[name] = [conv_w, conv_b]162elif 'bn' in name:163bn_w = genfromtxt(paths[name + '_w'], delimiter=',', dtype=None)164bn_b = genfromtxt(paths[name + '_b'], delimiter=',', dtype=None)165bn_m = genfromtxt(paths[name + '_m'], delimiter=',', dtype=None)166bn_v = genfromtxt(paths[name + '_v'], delimiter=',', dtype=None)167weights_dict[name] = [bn_w, bn_b, bn_m, bn_v]168elif 'dense' in name:169dense_w = genfromtxt(dirPath+'/dense_w.csv', delimiter=',', dtype=None)170dense_w = np.reshape(dense_w, (128, 736))171dense_w = np.transpose(dense_w, (1, 0))172dense_b = genfromtxt(dirPath+'/dense_b.csv', delimiter=',', dtype=None)173weights_dict[name] = [dense_w, dense_b]174175return weights_dict176177178def load_dataset():179train_dataset = h5py.File('datasets/train_happy.h5', "r")180train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features181train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels182183test_dataset = h5py.File('datasets/test_happy.h5', "r")184test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features185test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels186187classes = np.array(test_dataset["list_classes"][:]) # the list of classes188189train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))190test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))191192return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes193194def img_to_encoding(image_path, model):195#img = PIL.Image.open(image_path)196img = tf.keras.preprocessing.image.load_img(image_path)197#img = img1[...,::-1]198img = np.around(np.transpose(img, (2,0,1))/255.0, decimals=12)199x_train = np.expand_dims(img, axis=0)200print(x_train.shape)201embedding = model.predict_on_batch(x_train)202return embedding203204