# 从keras的datasets导入mnist数据集
from keras.datasets import mnist
from keras.layers import Dense #导入全连接层
from keras.utils import np_utils #keras中提供的np工具包
from keras.models import Sequential # 导入顺序结构
from tensorflow.keras.optimizers import SGD #导入SGD优化器
# 载入数据,得到训练集的数据和测试集的数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 打印出数据和标签的格式
print('x_shape:', x_train.shape) # (60000,28,28)
print('y_shape:', y_train.shape) # (60000,) 60000个数据对应的标签
'''使用reshape()将(60000,28,28)转换为(60000,784)这样一个行列的格式,就是把三维变成二维
x_train.shape[0]就是x_train格式的第0个位置,就是表示行数是60000行,列数-1不确定,可以默认的转换为最适合的列数
/255.0是将数据做一个归一化的处理
'''
x_train = x_train.reshape(x_train.shape[0], -1) / 255.0
x_test = x_test.reshape(x_test.shape[0], -1) / 255.0
# 转换为 one hot 独热编码 格式
'''这里使用的numpy下的untils中的to_categorical方法把标签数据给分类
因为有10个数字,所以设置num_classes为10,也就是10个类'''
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
# 创建模型:输入784个神经元,输出10个神经元
'''Sequential是采用的顺序结构,Dense是全连接层
units=10表示输出为10个神经元,input_dim=784表示输入为784个神经元
bis_initializer='one'是设置偏执值为1,如果不设置默认为0,激活函数
sofmax是将输出转成概率
'''
model = Sequential([
Dense(units=10, input_dim=784, bias_initializer='one', activation='softmax')
])
# 定义优化器,设置学习率
sgd = SGD(lr=0.5)
# 定义优化器以及loss function即损失函数,训练过程中计算准确率
model.compile(
optimizer=sgd, # 使用的优化为sgd随机梯度下降法
loss="mse", # mse均方差
metrics=['accuracy'] # 计算准确率
)
# 训练模型,使用训练集
'''batch_size=32表示每次会训练32张图片,把60000张图片训练完为1个周期
epochs是迭代周期,'''
model.fit(x_train, y_train, batch_size=32, epochs=10)
# 评估模型,使用测试集
loss, accuracy = model.evaluate(x_test, y_test)
# 打印loss和accuracy的值
print('loss:', loss)
print('accuracy:', accuracy)
结果如下所示: