文章目录
import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils # 导入keras提供的numpy工具包
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
# 载入数据
(x_train,y_train),(x_test,y_test) = mnist.load_data()
print("x_shape:",x_train.shape,"y_shape:",y_train.shape)
# 将数据转换由(60000,28,28)转换为(60000,784),并进行归一化除以255
x_train = x_train.reshape(x_train.shape[0],-1)/255.0
x_test = x_test.reshape(x_test.shape[0], -1)/255.0
print(x_train.shape,x_test.shape)
# 将数据转换为one-hot编码的格式
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
# 创建模型,输入是784个神经元,输出为10个神经元
model = Sequential(
[Dense(units=10,input_dim=784,bias_initializer="one",activation="softmax")]
)
# 自定义优化器
sgd=SGD(lr=0.01)
# 编译模型,定义优化器,loss_function,训练过程中计算准确率
# model.compile(optimizer=sgd,loss="mse",metrics=["accuracy"],) # 使用均方差作为损失函数
model.compile(optimizer=sgd,loss="categorical_crossentropy",metrics=["accuracy"],) # 使用交叉熵作为损失函数
# 喂入数据集,并规定每次喂入32张图像,设定迭代周期
model.fit(x_train,y_train,batch_size=32,epochs=100)
# 评估模型
loss,accuracy = model.evaluate(x_test, y_test)
print("test losee:",loss,"accuracy:",accuracy)