数据集提供的代码放在kt_utils.py:

import keras.backend as K
import math
import numpy as np
import h5py
import matplotlib.pyplot as pltdef mean_pred(y_true, y_pred):return K.mean(y_pred)def load_dataset():train_dataset = h5py.File('datasets/train_happy.h5', "r")train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set featurestrain_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels#print(train_set_x_orig.shape) ##(600, 64, 64, 3)#print(train_set_y_orig)##(600,)test_dataset = h5py.File('datasets/test_happy.h5', "r")test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set featurestest_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels#print(test_set_x_orig.shape)#(150, 64, 64, 3)#print(test_set_y_orig.shape)#(150,)classes = np.array(test_dataset["list_classes"][:]) # the list of classes#print(classes) #[0,1]train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))#print(train_set_y_orig.shape)  (1, 600)#print(test_set_y_orig.shape)   (1, 150)return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
#load_dataset()

查看数据集:

import kt_utils
import cv2
import matplotlib.pyplot as plt
train_set_x_orig, train_set_Y, test_set_x_orig, test_set_Y, classes = kt_utils.load_dataset()
print('训练样本={}'.format(train_set_x_orig.shape))
print('训练样本标签={}'.format(train_set_Y.shape))
print('测试样本={}'.format(test_set_x_orig.shape))
print('测试样本标签={}'.format(test_set_Y.shape))
print('第五个样本={}'.format(train_set_Y[0,5]))
cv2.imshow('1.jpg',train_set_x_orig[5,:,:,:])
cv2.waitKey()
print('第六个样本={}'.format(train_set_Y[0,6]))
cv2.imshow('1.jpg',train_set_x_orig[6,:,:,:])
cv2.waitKey()
# plt.imshow(train_set_x_orig[5,:,:,:])
# plt.show()

打印结果:可看出600个训练样本,150个测试样本,size=(64,64,3),其中happy的标签为1,not happy的标签为0,故标签也要经过one-hot。

开始训练模型代码如下:

import numpy as np
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers import Input,ZeroPadding2D,Conv2D,BatchNormalization,Activation,MaxPooling2D
from keras.layers import Flatten,Dense
import kt_utils
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input
from keras.utils import plot_model
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
import time
import cv2
"""
转换成one-hot
"""
def convert_to_one_hot(Y, C):Y = np.eye(C)[Y.reshape(-1)].Treturn Y
"""
获取数据  并将标签转换成one-hot
"""
def convert_data():train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes=kt_utils.load_dataset()train_x=train_set_x_orig/255test_x = test_set_x_orig / 255train_y=convert_to_one_hot(train_set_y_orig,2).Ttest_y = convert_to_one_hot(test_set_y_orig, 2).T#print(train_y.shape)return train_x,train_y,test_x,test_y
"""
查看样本
"""
def test():train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes=kt_utils.load_dataset()X_train=train_set_x_orig/255X_test = test_set_x_orig / 255Y_train=train_set_y_orig.TY_test = test_set_y_orig.Tplt.imshow(train_set_x_orig[63,:,:,:])plt.show()
"""
构建CNN模型
"""
def model(input_shape):X_input=Input(input_shape)print('输入尺寸={}'.format(X_input.shape))#Zero paddingX=ZeroPadding2D((3,3))(X_input)print('输补完零尺寸={}'.format(X.shape))#CONV->BN->RELUX=Conv2D(32,(7,7),strides=(1,1),name='conv0')(X)print('第一次卷积尺寸={}'.format(X.shape))X=BatchNormalization(axis=-1,name='bn0')(X)X=Activation('relu')(X)#MAXPOOLX=MaxPooling2D((2,2),name='max_pool')(X)print('第一池化尺寸={}'.format(X.shape))#FLATTEN+FULLYCONNECTEDX=Flatten()(X)X=Dense(2,activation='sigmoid',name='fc')(X)model=Model(inputs=X_input,outputs=X,name='HappyModel')return model
"""
测试模型
"""
def testModel():train_x, train_y, test_x, test_y=convert_data()#定义好模型结构happyModel=model(input_shape=[64,64,3])#模型编译happyModel.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])#模型训练start_time=time.time()print('============模型开始训练=====================')happyModel.fit(x=train_x,y=train_y,epochs=1,batch_size=32)end_time=time.time()print('train_time={}'.format(end_time-start_time))# save the model#happyModel.save('my_model_v1.h5')print('============模型开始测试=====================')preds=happyModel.evaluate(x=test_x,y=test_y,batch_size=32)print()print('loss={}'.format(preds[0]))print('Test accuarcy={}'.format(preds[1]))#打印参数happyModel.summary()#可视化模型plot_model(happyModel,to_file='HappyModel.png')SVG(model_to_dot(happyModel).create(prog='dot',format='svg'))#test my_imageprint('============测试自己的照片===================')path = 'images/my_image.jpg'img = image.load_img(path, target_size=(64, 64))plt.imshow(img)plt.show()x = image.img_to_array(img)  # (64,64,3)x = x.reshape(1, 64, 64, 3)x=preprocess_input(x)y=happyModel.predict(x)print('预测值={}'.format(y))
def testPicture():# img=cv2.imread('my_image.jpg')# cv2.imshow('img',img)path='images/my_image.jpg'img=image.load_img(path,target_size=(64,64))plt.imshow(img)plt.show()print('img=',img)x=image.img_to_array(img)#(64,64,3)print('x=',x)print(x.shape)#x = np.expand_dims(x, axis=0)#(1,64,64,3)x=x.reshape(64,64,3)print('x=',x)print(x.shape)plt.imshow(x)plt.show()
if __name__=='__main__':#test()testModel()#testPicture()

打印结果:?号代表样本数,可知池化过后尺寸为(32,32,32)

训练次数是一次,结果如下:可知每张图片训练时间为17ms,600张时间为10s,跟自己记录的train_time差一点点,因为还有别的开支。

测试结果:测试精度一般

打印出模型参数,并且可视化:可看成conv0参数=7×7×3×32(W的参数)+32(b的参数)=4736

测试自己的照片:

打印结果:貌似是happy 貌似又不是 样本量少 加上训练次数少 肯定是不准的。

吴恩达作业10:用卷积神经网络识别人脸happy(基于Keras)相关推荐

  1. 吴恩达作业9:卷积神经网络实现手势数字的识别(基于tensorflow)

    数据集链接:https://download.csdn.net/download/fanzonghao/10551018 提供数据集代码放在cnn_utils.py里. import math imp ...

  2. 吴恩达深度学习笔记——卷积神经网络(Convolutional Neural Networks)

    深度学习笔记导航 前言 传送门 卷积神经网络(Convolutional Neural Networks) 卷积神经网络基础(Foundations of Convolutional Neural N ...

  3. 吴恩达深度学习 | (18) 卷积神经网络专项课程第二周学习笔记

    课程视频 第二周PPT汇总 吴恩达深度学习专项课程共分为五个部分,本篇博客将介绍第四部分卷积神经网络专项的第二周课程:深度卷积网络:实例探究. 目录 1. 为什么要进行实例探究 2. 经典网络 3. ...

  4. 吴恩达deeplearning之CNN—卷积神经网络入门

    1.边界检测示例 假如你有一张如下的图像,你想让计算机搞清楚图像上有什么物体,你可以做的事情是检测图像的垂直边缘和水平边缘. 如下是一个6*6的灰度图像,构造一个3*3的矩阵,在卷积神经网络中通常称之 ...

  5. 吴恩达 深度学习系列--卷积神经网络(Convolutional Neural Networks)-03(目标检测)

    目标检测 3.1 目标定位(Object localization) 3.1.1概念 3.1.2 监督学习任务定义目标标签y 3.2 特征点检测(Landmark detection) 3.3 基于滑 ...

  6. 吴恩达深度学习笔记——卷积神经网络(CNN)

    目录 一.计算机视觉(Computer vision) 二.边缘检测示例(Edge detection example) 三.更多的边缘检测内容(More edge detection) 四.Padd ...

  7. 2020-8-25 吴恩达DL学习-C4 卷积神经网络-第二周 CNN实例探究(2.7Inception 网络)

    1.视频网站:mooc慕课https://mooc.study.163.com/university/deeplearning_ai#/c 2.详细笔记网站(中文):http://www.ai-sta ...

  8. 吴恩达作业8:三层神经网络实现手势数字的识别(基于tensorflow)

    数据集的载入,随机产生mini-batch放在tf_utils.py,代码如下 import h5py import numpy as np import tensorflow as tf impor ...

  9. 2.5-2.7 1×1 卷积 Inception 吴恩达 第四门课 卷积神经网络 第二周 深度卷积网络

    2.5 网络中的网络以及 1×1 卷积(Network in Network and 1×1 convolutions 其中一个比较有帮助的想法是使用 1×1 卷积.过滤器为 1×1,这里是数字 2, ...

最新文章

  1. 介绍Visual Studio的Android模拟器
  2. 为什么JAVA的垃圾回收机制无法避免内存泄漏
  3. java 财付通支付_工商变更:马化腾卸任财付通支付科技有限公司法定代表人
  4. .NetCore实践篇:成功解决分布式监控ZipKin聚合依赖问题(三)
  5. FIT2CLOUD飞致云旗下开源项目DataEase成功进入GitHub趋势榜主榜
  6. python科赫雪花代码的意思_python函数和代码复用——迭代练习:科赫雪花绘制
  7. 关于2015年春运增开旅客列车的公告
  8. 关于花瓣网header条的思考
  9. C# 获取图片,Pdf中的文字
  10. POJ 3322 BFS
  11. Java实现 蓝桥杯算法提高金明的预算方案
  12. Linux 常规安装MySQL 执行启动命令报错(附安装方法)
  13. 简单的会员卡储值积分管理系统
  14. 谷歌搜索的灵魂!BERT模型的崛起与荣耀
  15. 1310327-18-4,Cbz-N-amido-PEG3-acid受保护的胺可以在酸性条件下脱保护
  16. HAL库自学笔记#2【PWM】
  17. ORB-SLAM笔记———ORB-SLAM3概述
  18. java拼音搜索排序算法_Java汉字按照拼音排序
  19. squirrelSql小松鼠数据库连接工具的安装以及连接informix(系列3,squirrelSql作为客户端连接)
  20. 关于EasyX和graphics.h的那些事(上)

热门文章

  1. centos mysql jar 驱动包_JDBC连接MySQL的数据库
  2. 可解释性:对神经网络中层特征复杂度的解释与拆分
  3. 用微前端的方式搭建类单页应用
  4. 阿里P8架构师谈:MySQL数据库的索引原理、与慢SQL优化的5大原则
  5. Wasserstein metric的通俗解释
  6. 知识图谱之语言计算与信息抽取
  7. WPF使用Canvas绘制可变矩形
  8. java编程思想第四版第十四章 类型信息习题
  9. 2017.4.07 js 中的function 实现的方式
  10. C++有符号和无符号数的转换