import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential, Model
from keras.utils import to_categorical
from keras.layers import Dense,Input, Embedding, LSTM
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Flatten
f = np.load('mnist.npz')#npz是压缩文件,里面包含f['x_train'], f['y_train'],f['x_test'], f['y_test']四个文件
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
print(x_train.shape)#(60000, 28, 28)有 60000 张图片作为训练数据
print(x_test.shape)#(10000, 28, 28)
print(y_train.shape)#(60000,)
print(y_test.shape)#(10000,)
# 可视化查看一下
fig = plt.figure(figsize = (20, 20))
for i in range(6):
ax = fig.add_subplot(1, 6,i + 1, xticks = [], yticks = [])
ax.imshow(x_train[i], cmap = 'gray')
ax.set_title(str(y_train[i]))
x_train=x_train / 255
x_test=x_test / 255
x_train=x_train.reshape(-1,784)#(60000, 784) 784=28*28 转换成为一维向量
x_test=x_test.reshape(-1,784)#(10000, 784)
#把数字转换为one-hot编码 十个类型 0-9十种
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
#选择模型 为model加入一个784输入,784个输出的隐藏层,激活函数使用relu
model=Sequential()
model.add(Dense(units=784, activation='relu', input_dim=784))
#在之前的基础上为model加入10个输出的输出层,激活函数使用softmax
model.add(Dense(units=10,activation="softmax"))
model.summary()
#使用.compile() 来配置学习过程,代价函数loss使用categorical_crossentropy,优化算法optimizer使用sgd,性能的指标使用accuracy
model.compile(loss="categorical_crossentropy",optimizer='sgd',metrics=['accuracy'])
#训练模型
model.fit(x_train, y_train, epochs=5, batch_size=32)#一个epoch指代所有的数据送入网络中完成一次前向计算及反向传播的过程。batch就是每次送入网络中训练的一部分数据
score = model.evaluate(x_test, y_test, batch_size=128)
print("loss:",score[0])
print("accu:",score[1])
predictions=model.predict_classes(x_test, batch_size=128)
print(predictions)#[7 2 1 ... 4 5 6]