keras框架下的MINIST

# 手写数字分类

from __future__ import  print_function
from keras.datasets import mnist

import numpy as np
import os

(x_train, y_train), (x_test, y_test) = mnist.load_data()
# os.getcwd() + '/mnist.npz'
x_train = x_train.reshape(60000, 784)    # 28*28的二维灰度值向量变成784*1的一维向量便于计算,有60000张
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32') # 转换为浮点类型,便于转换为0到1的数
x_test = x_test.astype('float32')
x_train /= 255  # 灰度值转换为0到1的数
x_test /= 255
print(x_train.shape[0], 'train samples')    # 训练集的大小
print(x_test.shape[0], 'text samples')

print(y_train)  # [5 0 4 ... 5 6 8]     输出训练集的标签
print(y_test)   # [7 2 1 ... 4 5 6]

from keras.utils import to_categorical

num_classes = 10    # 10个类别

y_train = to_categorical(y_train, num_classes)  # 把标签变成向量,便于计算
y_test = to_categorical(y_test, num_classes)
print(y_train)  # 输出标签向量化后的训练集,如标签5在10分类里变成了[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
print(y_test)

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()    # 顺序模型
# 添加网络层
# 输出512, 激活函数,输入图像的大小, 这层网络的名字
model.add(Dense(512, activation='relu', input_shape=(784,), name='Dense_0'))    # 激活函数 relu
model.add(Dense(512, activation='relu', name='Dense_1'))    # 512个神经元
model.add(Dense(num_classes, activation='softmax', name='Dense_2'))     # softmax为分类器

model.summary()

from keras.utils import plot_model
plot_model(model, to_file='minist.png')     # 画出神经网络

from keras.optimizers import RMSprop

model.compile(loss='categorical_crossentropy',  # 损失函数,10分类函数
              optimizer=RMSprop(),  # 优化函数
              metrics=['accuracy'])     # 关注准确率
# 开始训练
history = model.fit(x_train, y_train,
                    batch_size=128,     # 每次提度更新的样本数。如果未指定,默认为 32.
                    epochs=10,  # 训练十次
                    verbose=1,  # 日志显示模式。 0 = 安静模式, 1 = 进度条, 2 = 每轮一行。
                    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])

model.save('mnist.h5')  # 保存模型

Keras中文文档:https://keras.io/zh/models/sequential/

你可能感兴趣的:(计算机视觉)