TensorFlow实战框架Chp10--Keras和原生态TensorFlow API联合起来解决MNIST问题

  • Keras和原生态TensorFlow API联合起来解决MNIST问题
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 20:50:33 2018

@author: muli
"""
# 使用的是 输入层--全连接层--输出层
# 单层的全连接层

import keras
from keras.datasets import mnist
from keras.layers import Input, Dense
from keras.models import Model

# 1. 数据预处理
num_classes = 10
img_rows, img_cols = 28, 28

# 通过Keras封装好的API加载MNIST数据。
(trainX, trainY), (testX, testY) = mnist.load_data()
trainX = trainX.reshape(trainX.shape[0], img_rows * img_cols)
testX = testX.reshape(testX.shape[0], img_rows * img_cols)

# 将图像像素转化为0到1之间的实数。
trainX = trainX.astype('float32')
testX = testX.astype('float32')
trainX /= 255.0
testX /= 255.0

# 将标准答案转化为需要的格式(one-hot编码)。
trainY = keras.utils.to_categorical(trainY, num_classes)
testY = keras.utils.to_categorical(testY, num_classes)


# 2. 通过返回值的方式定义模型
# 这里指定的维度,不用考虑batch的大小
inputs = Input(shape=(784,))

# 定义一层全连接层,使用ReLu激活函数
x = Dense(500, activation='relu')(inputs)
# 定义输出层,神经网络的输出经过softmax
predictions = Dense(10, activation='softmax')(x)

# 创建Model类创建模型
model = Model(inputs=inputs, outputs=predictions)
# 定义损失函数、优化函数和评测方法
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.SGD(),
              metrics=['accuracy'])

# 3. 训练模型
model.fit(trainX, trainY,
          batch_size=32,
          epochs=5,
          validation_data=(testX, testY))

# 模型评估
score = model.evaluate(testX, testY)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

猜你喜欢

转载自blog.csdn.net/mr_muli/article/details/80992671