-- coding: utf-8 --
"""
Created on Sun Nov 11 19:28:04 2018
@author: ltx
"""
import numpy as np
import tensorflow as tf
import keras
import matplotlib.pyplot as plt
import kt_utils
from matplotlib.pyplot import imshow
from keras.applications.imagenet_utils import preprocess_input
载入数据集
train_x,train_y,test_x,test_y,classes=kt_utils.load_dataset()
归一化数据集
train_x=train_x/255
test_x=test_x/255
train_y=train_y.T
test_y=test_y.T
---------keras快速构建卷积模型---
def happy_model(X_shape):
input_X=keras.Input(X_shape)
#使用0填充数据集边框
X=keras.layers.ZeroPadding2D(padding=(3,3))(input_X)
#进行图像数据的卷积
X_CNN=keras.layers.Conv2D(30,(6,6),strides=(1,1),name="conv0")(X)
#batchNormal
X_BN=keras.layers.BatchNormalization(axis=3)(X_CNN)
#激活
X_JH=keras.layers.Activation(activation="relu")(X_BN)
#建立池化层
X_Pool=keras.layers.MaxPool2D((5,5))(X_JH)
#一维化池化层的值
X_YW=keras.layers.Flatten()(X_Pool)
#构建全连接层
X_FC=keras.layers.Dense(units=1,activation="sigmoid")(X_YW)
#创建微笑模型
model=keras.Model(inputs=input_X,outputs=X_FC,name="happy_model")
return model
使用卷积模型来训练
1.生成keras模型实例
happy=happy_model(train_x.shape[1:])
2.编译keras模型
happy_c=happy.compile(optimizer="adam",loss="binary_crossentropy",metrics=["accuracy"])
3.训练keras模型
happy.fit(x=train_x,y=train_y,batch_size=68,epochs=50)
评估keras模型
prediction=happy.evaluate(x=test_x,y=test_y,batch_size=32)
print("模型的误差值为:"+str(prediction[0]))
print("模型的准确度为:"+str(prediction[1]))
将训练好的keras模型用于预测自己的图片(不一定效果好)
img_path='images/smile7.jpg'
img=keras.preprocessing.image.load_img(path=img_path,target_size=(64,64))
imshow(img)
X=keras.preprocessing.image.img_to_array(img)
X=np.expand_dims(X,axis=0)
X = preprocess_input(X)
print(happy.predict(X))
-------------实验结果-------------------