keras实现CNN

在深度学习的路上,从头开始了解一下各项技术。本人是DL小白,连续记录我自己看的一些东西,大家可以互相交流。

之前写过一些关于深度学习的简单概念,最近这段时间会看一些代码相关的东西。

本文参考:吴恩达deeplearning.ai课程

一、前言

Keras是由纯python编写的基于theano/tensorflow的深度学习框架。是一个高层神经网络API,支持快速实验,能够把你的idea迅速转换为结果。在写tensorflow实现CNN的时候,无意中搜索到一篇keras实现CNN的文章,对比发现keras实现能节省很多步骤。

keras中,不需要根据各个层去设定不同的权重,初始值等参数,直接在函数中调用即可,并且在整个model中,只需要一步步更新X值,而不是每一处有一个新的储存值。

话不多说,直接上代码,具体的都在代码里了。

二、代码实现

import numpy as np
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalAveragePooling2D, GlobalMaxPool2D
from keras.models import Model
from keras.preprocessing import image
from keras.utils import layer_utils
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
#下载训练集和数据集 classes表示图片的分类
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()

# 正则化图片集,让图片集矩阵中的值在[0, 1]之间
X_train = X_train_orig/255.
X_test = X_test_orig/255.
# 结果是图片的分类,不需要正则化,需要转置后与X对齐
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))
#用keras建立CNN模型
def HappyModel(input_shape):
    X_input = Input(input_shape) #类似于TensorFlow的placeholder

    X = ZeroPadding2D((3, 3))(X_input) #用(3, 3)去pad X_input
    X = Conv2D(32, (8, 8), strides=(1, 1), name='conv0')(X)#通过7,7的卷积核
    X = BatchNormalization(axis=3, name='bn0')(X)
    X = Activation('relu')(X)

    X = MaxPooling2D((2, 2), name='max_pool')(X)#池化层

    X = Flatten()(X)#展开
    X = Dense(1, activation='sigmoid', name = 'fc')(X) #全连接

    model = Model(inputs = X_input, outputs = X, name = 'HappyHouse')

    return model

happyModel = HappyModel(X_train.shape[1:])

happyModel.compile(optimizer="Adam", loss = "binary_crossentropy", metrics=["accuracy"])

happyModel.fit(x = X_train, y = Y_train, epochs = 10, batch_size=32)

preds = happyModel.evaluate(X_test, Y_test)

print(str(preds))


 

你可能感兴趣的:(keras实现CNN)