深度学习

01 Apr 2019 » keras
from keras.datasets import mnist
import matplotlib.pyplot as plt
from keras.utils import np_utils

# 读取数据集
# x_train (60000, 28, 28), y_train(60000, 1)
# x_test (10000, 28, 28), y_test(10000, 1) 
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 得到图片的像素. 因为模型的输入数据结构是:行数(图片数)*特征(特征数), 所有二维的图片数# 据结构需要转为一维的特征.
num_pixels = x_train.shape[1] * x_train.shape[2]
# 将图片(28, 28) 转成(1,28*28), 即数据集(60000, 28, 28)=>(60000, 28*28)
x_train = x_train.reshape(x_train.shape[0], num_pixels)
x_test = x_test.reshape(x_test.shape[0], num_pixels)
# 像素灰度值是(0~255), 归一化为,0~1之间.
x_train = x_train/255
x_test = x_test/255
# 标签的结构是:(60000,1), 共10个分类, 独热编码为(60000,10);
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
# ====================================================================

from keras.models import Sequential
from keras.layers import Dense
# 实例化一个顺序模型
model = Sequential()
# 创建num_pixels个节点的隐含层
model.add(Dense(num_pixels, input_dim=num_pixels,activation='relu'))
# 用softmax转换为概率
model.add(Dense(10, activation='softmax'))
# 设置损失函数, 优化器(adam, sgb...)等, 度量指标
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
# epochs:训练次数
# batch_size:每次参加更新参数的训练样本个数
model.fit(x_train, y_train, validation_data=(X_test, y_test), batch_size=200, epochs=5)
# 评估模型性能
scores = model.evaluate(x_test, y_test)

print("成绩:",scores)