Tensorflow 实战 Google 深度学习框架(第2版)---- 10.2.2节 P272 代码

#-*-coding:utf-8-*-
import keras
from keras.datasets import mnist
from keras.layers import Input,Dense
from keras.models import Model
from keras import backend as K


num_classes = 10
img_rows, img_cols = 28, 28

# 通过Keras封装好的API加载MNIST数据。其中trainX就是一个60000 * 28 * 28的数组,
# trainY是每一张图片对应的数字。
(trainX, trainY), (testX, testY) = mnist.load_data()
trainX = trainX.reshape(-1,784)
testX = testX.reshape(-1,784)

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)


inputs = Input(shape=(784,))

x = Dense(500,activation='relu')(inputs)
predictions = Dense(10,activation = 'softmax')(x)

model = Model(inputs=inputs,outputs=predictions)
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer = keras.optimizers.SGD(),
              metrics=['accuracy'])
model.fit(trainX,trainY,
          batch_size=128,
          epochs=20,
          validation_data = (testX,testY))

 

你可能感兴趣的:(tensorflow)