一、代码演示
keras_mnist.py:
"""
MNIST数据集
70000张图像(每位数字7000个图像 0-9:10个数字)。
每个数据点用一个784-d的向量表示,对应于MNIST数据像素28*28
TensorFlow1.14 Keras2.2.5
"""
#LabelBinarizer将单个整数标签编码为向量标签
from sklearn.preprocessing import LabelBinarizer
#train_test_split用于从MNIST数据集分割训练集和测试集
from sklearn.model_selection import train_test_split
#classification_report显示我们的模型的总精度,以及每个数字的分类精度
from sklearn.metrics import classification_report
#Sequential用于顺序添加每一层网
from keras.models import Sequential
#Dense实现全连接层
from keras.layers.core import Dense
#gradient_descent_v2随机梯度优化网络
from keras.optimizers import SGD
#datasets获取数据
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
import argparse
import scipy.io as scio
#解析参数
ap = argparse.ArgumentParser()
"将绘制的损失图保存"
ap.add_argument("-o","--output",required=True,help="path to the output loss/accuracy plot")
args = vars(ap.parse_args())
"下载数据"
print("[INFO] loading MNIST(full) dataset...")
#dataset = datasets.fetch_openml("MNIST Original",data_home='D:/DLCV/DLCV\my_study/datasets')
dataset = scio.loadmat('D:/DLCV/DLCV\my_study/datasets/openml/mnist-original.mat')
data = dataset['data']
label = dataset['label']
"将原始图像强度压缩到0-1"
data = data.astype("float")/255.0
(trainX, testX, trainY, testY) = train_test_split(data.T, label.T, test_size=0.25)
"编码标签"
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
"构建网络784-256-128-10"
model = Sequential()
model.add(Dense(256,input_shape=(784,),activation='sigmoid'))
model.add(Dense(128,activation='sigmoid'))
model.add(Dense(10,activation='softmax'))
"随机梯度训练网络"
print("[INFO]traing network...")
sdg = SGD(0.01) #学习率0.01
#categorical_crossentropy交叉熵损失函数
model.compile(loss='categorical_crossentropy',optimizer=sdg,metrics=['accuracy'])
#H为字典型数据
H = model.fit(trainX,trainY,validation_data=(testX,testY),epochs=100,batch_size=128)
"评估网络"
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=128)
print(classification_report(testY.argmax(axis=1),predictions.argmax(axis=1),target_names=[str(x) for x in lb.classes_]))
"绘图"
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, 100), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, 100), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, 100), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, 100), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(args["output"])
二、注意事项
1.本代码运用TensorFlow1.14 +Keras2.2.5(TensorFlow和Keras版本要对应)
2.MNIST Original数据集下载提示错误,在网上下载后,放入当前程序所在的文件夹
3.当前程序所在目录新建一个output文件夹,来保存最后的图片
4.执行该程序
方法一:最好从电脑终端(或pycharm终端执行)进入 该程序所在路径 执行语句:python keras_mnist.py --output output/keras_mnist.png
方法二: