from keras.datasets import mnist
from keras import models
from keras import layers
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt

# importer data
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
digit = train_images[4]
train_images = train_images.reshape((60000,28*28))
train_images = train_images.astype('float32') / 255
train_labels = to_categorical(train_labels)

test_images = test_images.reshape((10000,28*28))
test_images = test_images.astype('float32') / 255
test_labels = to_categorical(test_labels)


# print(digit.shape)
# plt.imshow(digit, cmap='gray')
# plt.show()

# build net
network=models.Sequential() # Sequential-线性层堆叠网络架构
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,))) # Dense-全连接神经层
network.add(layers.Dense(10,activation='softmax'))

network.compile(optimizer='rmsprop',
                loss='categorical_crossentropy',
                metrics=['accuracy'])

# fit data
network.fit(train_images,train_labels,epochs=5,batch_size=128)

# evaluate model
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)

# 函数式API定义法
# input_tensor = layers.Input(shape=(784,))
# x = layers.Dense(32,activation='relu')(input_tensor)
# output_tensor = layers.Dense(10, activation='softmax')(x)
# model = models.Model(inputs=input_tensor,outputs=output_tensor)