keras 一:mnist_mlp.py

mnist_mlp.py 在mnist数据集上训练一个多层感知机

'''Trains a simple deep NN on the MNIST dataset.

Gets to 98.40% test accuracy after 20 epochs
(there is *a lot* of margin for parameter tuning).
2 seconds per epoch on a K520 GPU.
'''

from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
#Dense 全连接层
#Dropout 对于神经网络按一定概率将其从网络中丢弃,解决过拟合问题
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

#epochs 训练过程中数据被轮的次数,向前向后传播时数据所有批次的单次训练迭代
#one epoch = numbers of iterations = N =训练样本数量/batch_size
batch_size = 128
num_classes = 10
epochs = 20

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

#输入数据维度(x_train.shape[0],x_train.shape[1]*x_train.shape[2])(图像数量,行×列)
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
#数据归一化处理 减去均值除以范围 最终为0-1先把数据转换成float32  
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
#把类别0-9变为二进制 方便训练
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

#在sequential类添加不同的神经网络层
model = Sequential()
#512为全连接层的节点个数 激活函数为relu 第一层定义输入节点的接收信息维数
model.add(Dense(512, activation='relu', input_shape=(784,)))
##dropout函数原型为keras.layers.core.Dropout(rate, noise_shape=None, seed=None)
#用于去掉一定比例的结点防止过学习
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

#网络结构信息表
model.summary()


model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(),
              metrics=['accuracy'])

#参数优化过程 verbose=1即输出训练过程进度条 若为0则不输出进度条
#validation_data 与测试集标签进行比对,得到分类准确率
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])
keras 一:mnist_mlp.py_第1张图片

你可能感兴趣的:(keras)