from keras.models import Sequential
from keras.layers import Dense,Activation,Dropout
from keras.optimizers import RMSprop
import keras 
from keras.datasets import mnist

batch_size = 128  %% 批量训练的值
num_classes = 10  %%标签种类
epochs = 20       %% 重复训练的次数

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255                %% 标准化数据
x_test /= 255
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)  %% 稀疏编码
y_test = keras.utils.to_categorical(y_test, num_classes)

model = Sequential()                                            %% 创建一个多层序列
model.add(Dense(512, activation='relu', input_shape=(784,)))     %% 第一次512 个神经元,使用relu激活函数,输入格式为784 x n  n 为btach num
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))                         %% 第二层 512 个神经元  激活函数 relu 
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))               %% 最后一层使用softmax 得出概率最大者
 
model.summary()                                                   %% 打印网络结构

model.compile(loss='categorical_crossentropy',                    %% 编译损失函数  优化器  结果输出矩阵
              optimizer=RMSprop(),
              metrics=['accuracy'])

history = model.fit(x_train, y_train,
                    batch_size=batch_size,                      %% 训练数据
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)            %% 检验结果
print('Test loss:', score[0])
print('Test accuracy:', score[1])