import keras
from keras.datasets import mnist #自带数据集的手写数据集
from keras.models import Sequential #序列模型,keras分为sequential和model模型
from keras.layers import Dense, Dropout, Flatten #dense神经元模型,dropout让一部分神经元不工作,防止过拟合,
# flatten,把多维的输入一维化,常用在从卷积层到全连接层的过渡
from keras.layers import Conv2D, MaxPooling2D #Conv2d,就是用来实现2d卷积核操作的,MaxPooling2D,2D 空间数据的最大池化操作。
from keras import backend as K #backend,Keras 的「后端引擎,处理诸如张量乘积和卷积等低级操作
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data() #Load_data()主要作用:解压数据集,然后从数据集中把数据取出来.
print(x_train.shape, y_train.shape)
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, 10) #y为int数组,num_classes为标签类别总数
y_test = keras.utils.to_categorical(y_test, 10)
x_train = x_train.astype('float32') #转换数据类型成了float32。深度学习中,数据量往往很大,所以在保障数据精度的同时还要考虑计算效率
x_test = x_test.astype('float32')
x_train /= 255 #图像的 RGB 数值,除以255归一到【0,1】
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
batch_size = 128 #batch_size指的就是更新梯度中使用的样本数。如果把batch_size设置为数据集的长度,
# 就成了批量梯度下降算法,batch_size设置为1就是随机梯度下降算法。
num_classes = 10 #输出神经元为10
epochs = 10 #epochs被定义为前向和反向传播中迭代次数
model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5),activation='relu',input_shape=input_shape)) #in_channels=32,输入的channels数,
# kernel_size ——卷积核的尺寸,
# 激活函数 sigmoid、tanh、relu。sigmoid可以将任何值转换为0~1概率,用于二分类。
# tanh,即双曲正切(hyperbolic tangent),类似于幅度增大sigmoid,将输入值转换为-1至1之间。
# relu,即Rectified Linear Unit,整流线性单元,激活部分神经元,增加稀疏性,当x小于0时,输出值为0,当x大于0时,输出值为x.
model.add(MaxPooling2D(pool_size=(2, 2))) #池化
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2))) #池化
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax')) #num_classes,该层有几个神经元,softmax,该层使用的激活函数,
# 将各个输出节点的输出值范围映射到[0, 1],并且约束各个输出节点的输出值的和为1的函数
model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adadelta(),metrics=['accuracy'])
# 使用model.compile()方法来配置训练方法,model.compile(optimizer = 优化器,loss = 损失函数,metrics = ["准确率”])
#binary_crossentropy 二进制交叉熵用于二分类问题中,categorical_crossentropy分类交叉熵适用于多分类问题中
#Adadelta优化器,Adagrad参数接收的更新越多,更新越小。Adadelta不是累积所有过去的梯度,而是根据渐变更新的移动窗口调整学习速率。 即使进行了许多更新仍在继续学习
#打印结果的时候你会看到每个epoch的acc和loss,Keras当中为我们定义了6种不同的accuracy,对应不同的输出
hist = model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test, y_test))
#verbose:日志显示,0为不在标准输出流输出日志信息,1为输出进度条记录,2为每个epoch输出一行记录。validation_data:形式为(X,y)的tuple,是指定的验证集
print("The model has successfully trained")
score = model.evaluate(x_test, y_test, verbose=0) #model.evaluate 用于评估您训练的模型。它的输出是准确度或损失
print('Test loss:', score[0])
print('Test accuracy:', score[1])
model.save('mnist.h5')
print("Saving the model as mnist.h5")
01-17
3676
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交