深度学习-卷积神经网络 吴恩达第四课第二周作业1答案(Keras tutorial - the Happy House - to build a deep learning algorithm)

本文介绍了一个名为“快乐模型”的深度学习网络,该模型用于面部表情识别,特别是从图片中识别出笑脸。通过使用卷积神经网络(CNN)、批量归一化、最大池化等技术,模型在训练集上达到了99.67%的准确率,在测试集上也获得了96.67%的高准确率。

import numpy as np
#import tensorflow as tf
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing import image
from keras.utils import layer_utils
from keras.utils.data_utils import get_file
from keras.applications.imagenet_utils import preprocess_input
import pydot
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
from keras.utils import plot_model
from kt_utils import *

import keras.backend as K
K.set_image_data_format('channels_last')
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow

%matplotlib inline

X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()

# Normalize image vectors
X_train = X_train_orig/255.
X_test = X_test_orig/255.

# Reshape
Y_train = Y_train_orig.T
Y_test = Y_test_orig.T

print ("number of training examples = " + str(X_train.shape[0]))
print ("number of test examples = " + str(X_test.shape[0]))
print ("X_train shape: " + str(X_train.shape))
print ("Y_train shape: " + str(Y_train.shape))
print ("X_test shape: " + str(X_test.shape))
print ("Y_test shape: " + str(Y_test.shape))
number of training examples = 600
number of test examples = 150
X_train shape: (600, 64, 64, 3)
Y_train shape: (600, 1)
X_test shape: (150, 64, 64, 3)
Y_test shape: (150, 1)

# GRADED FUNCTION: HappyModel

def HappyModel(input_shape):
    """
    Implementation of the HappyModel.
    
    Arguments:
    input_shape -- shape of the images of the dataset

    Returns:
    model -- a Model() instance in Keras
    """
    
    ### START CODE HERE ###
    # Feel free to use the suggested outline in the text above to get started, and run through the whole
    # exercise (including the later portions of this notebook) once. The come back also try out other
    # network architectures as well. 
    X_input = Input(input_shape)
    X = Conv2D(6, (5, 5), strides=(1, 1), name="conv1")(X_input)
    X = BatchNormalization(axis=-1, name="bn1")(X)
    X = Activation('relu')(X)
    X = MaxPooling2D(pool_size=(2, 2), name="Max_pool1")(X)
    
    X = Conv2D(6, (5, 5), strides=(1, 1), name="conv2")(X)
    X = BatchNormalization(axis=-1, name="bn2")(X)
    X = Activation('relu')(X)
    X = MaxPooling2D(pool_size=(2, 2), name="Max_pool2")(X)
    
    X = Conv2D(16, (5, 5), strides=(1, 1), name="conv3")(X)
    X = BatchNormalization(axis=-1, name="bn3")(X)
    X = Activation('relu')(X)
    
    X = Conv2D(32, (5, 5), strides=(1, 1), name="conv4")(X)
    X = BatchNormalization(axis=-1, name="bn4")(X)
    X = Activation('relu')(X)
    
    # FC
    X = Flatten()(X)
    X = Dense(400, activation='relu', name="fc1")(X)
    X = Dropout(0.5)(X)
    X = Dense(120, activation='relu', name="fc2")(X)
    X = Dense(32, activation='relu', name="fc3")(X)
    Y = Dense(1, activation='sigmoid', name="Output")(X)
    
    model = Model(inputs = X_input, outputs = Y, name='HappyModel')
    ### END CODE HERE ###
    
    return model

### START CODE HERE ### (1 line)
happyModel = HappyModel(X_train[0].shape)
### END CODE HERE ###

### START CODE HERE ### (1 line)
import keras
happyModel.compile(optimizer=keras.optimizers.Adam(), loss=keras.losses.binary_crossentropy, metrics=["accuracy"])
### END CODE HERE ###
### START CODE HERE ### (1 line)
happyModel.fit(x = X_train, y = Y_train, batch_size=32, epochs=20)
### END CODE HERE ###
Epoch 1/20
600/600 [==============================] - 1s 2ms/step - loss: 0.5759 - acc: 0.6833
Epoch 2/20
600/600 [==============================] - 0s 209us/step - loss: 0.3143 - acc: 0.8433
Epoch 3/20
600/600 [==============================] - 0s 216us/step - loss: 0.2022 - acc: 0.9233
Epoch 4/20
600/600 [==============================] - 0s 212us/step - loss: 0.1409 - acc: 0.9383
Epoch 5/20
600/600 [==============================] - 0s 215us/step - loss: 0.1258 - acc: 0.9533
Epoch 6/20
600/600 [==============================] - 0s 219us/step - loss: 0.0894 - acc: 0.9650
Epoch 7/20
600/600 [==============================] - 0s 220us/step - loss: 0.0484 - acc: 0.9850
Epoch 8/20
600/600 [==============================] - 0s 214us/step - loss: 0.0532 - acc: 0.9867
Epoch 9/20
600/600 [==============================] - 0s 219us/step - loss: 0.0792 - acc: 0.9700
Epoch 10/20
600/600 [==============================] - 0s 220us/step - loss: 0.0667 - acc: 0.9783
Epoch 11/20
600/600 [==============================] - 0s 222us/step - loss: 0.0423 - acc: 0.9883
Epoch 12/20
600/600 [==============================] - 0s 216us/step - loss: 0.0203 - acc: 0.9967
Epoch 13/20
600/600 [==============================] - 0s 217us/step - loss: 0.0110 - acc: 0.9950
Epoch 14/20
600/600 [==============================] - 0s 219us/step - loss: 0.0174 - acc: 0.9950
Epoch 15/20
600/600 [==============================] - 0s 217us/step - loss: 0.0279 - acc: 0.9900
Epoch 16/20
600/600 [==============================] - 0s 221us/step - loss: 0.0424 - acc: 0.9900
Epoch 17/20
600/600 [==============================] - 0s 223us/step - loss: 0.0541 - acc: 0.9783
Epoch 18/20
600/600 [==============================] - 0s 215us/step - loss: 0.0298 - acc: 0.9900
Epoch 19/20
600/600 [==============================] - 0s 213us/step - loss: 0.0232 - acc: 0.9900
Epoch 20/20
600/600 [==============================] - 0s 213us/step - loss: 0.0098 - acc: 0.9967

### START CODE HERE ### (1 line)
preds = happyModel.evaluate(x = X_test, y = Y_test)
### END CODE HERE ###
print()
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1]))
150/150 [==============================] - 0s 3ms/step

Loss = 0.20995811382929483
Test Accuracy = 0.9666666642824808

### START CODE HERE ###
img_path = 'images/my_image.jpg'
### END CODE HERE ###
img = image.load_img(img_path, target_size=(64, 64))
imshow(img)

x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

print(happyModel.predict(x))

happyModel.summary()
Layer (type)                 Output Shape              Param #   
=================================================================
input_4 (InputLayer)         (None, 64, 64, 3)         0         
_________________________________________________________________
conv1 (Conv2D)               (None, 60, 60, 6)         456       
_________________________________________________________________
bn1 (BatchNormalization)     (None, 60, 60, 6)         24        
_________________________________________________________________
activation_1 (Activation)    (None, 60, 60, 6)         0         
_________________________________________________________________
Max_pool1 (MaxPooling2D)     (None, 30, 30, 6)         0         
_________________________________________________________________
conv2 (Conv2D)               (None, 26, 26, 6)         906       
_________________________________________________________________
bn2 (BatchNormalization)     (None, 26, 26, 6)         24        
_________________________________________________________________
activation_2 (Activation)    (None, 26, 26, 6)         0         
_________________________________________________________________
Max_pool2 (MaxPooling2D)     (None, 13, 13, 6)         0         
_________________________________________________________________
conv3 (Conv2D)               (None, 9, 9, 16)          2416      
_________________________________________________________________
bn3 (BatchNormalization)     (None, 9, 9, 16)          64        
_________________________________________________________________
activation_3 (Activation)    (None, 9, 9, 16)          0         
_________________________________________________________________
conv4 (Conv2D)               (None, 5, 5, 32)          12832     
_________________________________________________________________
bn4 (BatchNormalization)     (None, 5, 5, 32)          128       
_________________________________________________________________
activation_4 (Activation)    (None, 5, 5, 32)          0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 800)               0         
_________________________________________________________________
fc1 (Dense)                  (None, 400)               320400    
_________________________________________________________________
fc2 (Dense)                  (None, 120)               48120     
_________________________________________________________________
fc3 (Dense)                  (None, 32)                3872      
_________________________________________________________________
Output (Dense)               (None, 1)                 33        
=================================================================
Total params: 389,275
Trainable params: 389,155
Non-trainable params: 120
plot_model(happyModel, to_file='HappyModel.png')
SVG(model_to_dot(happyModel).create(prog='dot', format='svg'))

这里可显示整个网络的流程图,若报错提示无法输出pydot,则参考博客

https://blog.csdn.net/Brianone/article/details/90111736

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值