先代码:注释都有
#导入包
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential,Model
from keras.layers.core import Dense,Activation,Dropout
import matplotlib.pyplot as plt
import matplotlib.image as processimage
from keras.utils import np_utils
from pickletools import optimize
#加载数据集 ,两个元组接受
(xTrain,yTrain),(xTest,yTest) = mnist.load_data();
#打印样本的数量
#print(xTrain.shape,yTrain.shape);
#print(xTest.shape,yTest.shape)
#准备数据
#reshape 格式 因为灰色图片 是28 *28 彩色的话 是28*28*3 RGB
#全连接层 做数据量不变,维度变成1
xTrain = xTrain.reshape(60000,784);
xTest = xTest.reshape(10000,784);
#设置成小数浮点型 astype -> set as type into 转换格式
xTrain = xTrain.astype("float32");
xTest = xTest.astype("float32")
#归一化
xTrain = xTrain/255;
xTest = xTest/255;
#超参数
batchSize = 1024 #一次训练多少个数据
nbClass = 10 # 这里是分多少类
epochs = 30 # 训练的次数
#把分类变成vectors [0000000100]
yTest =np_utils.to_categorical(yTest, nbClass); #LABLE
yTrain = np_utils.to_categorical(yTrain, nbClass);
#开始
model = Sequential();
#第一个网络 Dense 全连接
model.add(Dense(512,input_shape=(784,))); #512 给下一层的个数, 第一层接受 784 必须要有,
model.add(Activation('relu')) #激活函数
model.add(Dropout(0.2)); #丢掉百分之20
#第二层
model.add(Dense(256));
model.add(Activation('relu'));
model.add(Dropout(0.2));
#第三层
model.add(Dense(128));
model.add(Activation('relu'));
model.add(Dropout(0.2));
#第四层
model.add(Dense(10));
model.add(Activation('softmax')); #用于分类的 激活函数
#编译
model.compile(
#损失函数
loss = 'categorical_crossentropy',
#优化函数
optimizer='rmsprop',
#矩阵要求
metrics=['accuracy'],
);
#启动网络训练 参数1:训练的数据,2:训练的标签.3一次读取多少数据,4训练多少次,5,可以检测测试数据#validation_data=(xTest,yTest)
training = model.fit(
xTrain,
yTrain,
batch_size=batchSize,
epochs =epochs,
validation_data=(xTest,yTest)
);