仅仅为了学习Keras的使用,使用一个四层的全连接网络对MNIST数据集进行分类,网络模型各层结点数为:3072: : 1024 : 512:10;

  使用50000张图片进行训练,10000张测试:

              precision    recall  f1-score   support

    airplane       0.61      0.69      0.65      1000
automobile 0.69 0.67 0.68 1000
bird 0.43 0.49 0.45 1000
cat 0.40 0.32 0.36 1000
dear 0.49 0.50 0.50 1000
dog 0.45 0.48 0.47 1000
frog 0.58 0.65 0.61 1000
horse 0.63 0.60 0.62 1000
ship 0.72 0.66 0.69 1000
truck 0.63 0.58 0.60 1000 micro avg 0.56 0.56 0.56 10000
macro avg 0.56 0.56 0.56 10000
weighted avg 0.56 0.56 0.56 10000

训练过程中,损失和正确率曲线:

  可以看到,训练集的损失在一直降低,而测试集的损失出现大范围波动,并趋于上升,说明在一些epoch之后,出现过拟合;

  训练集的正确率也在一直上升,并接近100%;而测试集的正确率达到50%就趋于平稳了;

代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 19-5-9 """
implement classification for CIFAR-10 with Keras
""" __author__ = 'Zhen Chen' # import the necessary packages
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
from keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
import argparse # construct the argument parse and parse the arguments
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", default="./Training Loss and Accuracy_CIFAR10.png")
args = parser.parse_args() # load the training and testing data, scale it into the range [0, 1],
# then reshape the design matrix
print("[INFO] loading CIFAR-10 data...")
((trainX, trainY), (testX, testY)) = cifar10.load_data()
trainX = trainX.astype("float") / 255.0
testX = testX.astype("float") / 255.0
trainX = trainX.reshape((trainX.shape[0], 3072))
testX = testX.reshape((testX.shape[0], 3072)) # convert the labels from integers to vectors
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.fit_transform(testY) # initialize the label names for the CIFAR-10 dataset
labelNames = ["airplane", "automobile", "bird", "cat", "dear", "dog", "frog", "horse", "ship", "truck"] # define the 2072-1024-512-10 architecture Keras
model = Sequential()
model.add(Dense(1024, input_shape=(3072,), activation="relu"))
model.add(Dense(512, activation="relu"))
model.add(Dense(10, activation="softmax")) # train the model using SGD
print("[INFO] training network...")
sgd = SGD(0.01)
model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])
H = model.fit(trainX, trainY, validation_data=(testX, testY), epochs=100, batch_size=32)
model.save_weights('SGD_100_32.h5') # evaluate the network
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=32)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=labelNames)) # plot the training losss and accuracy
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 on CIRFAR-10")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(args.output)

Keras实现CIFAR-10分类的更多相关文章

  1. DL Practice:Cifar 10分类

    Step 1:数据加载和处理 一般使用深度学习框架会经过下面几个流程: 模型定义(包括损失函数的选择)——>数据处理和加载——>训练(可能包括训练过程可视化)——>测试 所以自己写代 ...

  2. keras系列︱图像多分类训练与利用bottleneck features进行微调(三)

    引自:http://blog.csdn.net/sinat_26917383/article/details/72861152 中文文档:http://keras-cn.readthedocs.io/ ...

  3. 【翻译】TensorFlow卷积神经网络识别CIFAR 10Convolutional Neural Network (CNN)| CIFAR 10 TensorFlow

    原网址:https://data-flair.training/blogs/cnn-tensorflow-cifar-10/ by DataFlair Team · Published May 21, ...

  4. keras系列︱人脸表情分类与识别:opencv人脸检测+Keras情绪分类(四)

    引自:http://blog.csdn.net/sinat_26917383/article/details/72885715 人脸识别热门,表情识别更加.但是表情识别很难,因为人脸的微表情很多,本节 ...

  5. [深度应用]·Keras实现Self-Attention文本分类(机器如何读懂人心)

    [深度应用]·Keras实现Self-Attention文本分类(机器如何读懂人心) 配合阅读: [深度概念]·Attention机制概念学习笔记 [TensorFlow深度学习深入]实战三·分别使用 ...

  6. 【Python与机器学习】:利用Keras进行多类分类

    多类分类问题本质上可以分解为多个二分类问题,而解决二分类问题的方法有很多.这里我们利用Keras机器学习框架中的ANN(artificial neural network)来解决多分类问题.这里我们采 ...

  7. Keras人工神经网络多分类(SGD)

    import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import ...

  8. keras 的svm做分类

    SVC继承了父类BaseSVC SVC类主要方法: ★__init__() 主要参数: C: float参数 默认值为1.0 错误项的惩罚系数.C越大,即对分错样本的惩罚程度越大,因此在训练样本中准确 ...

  9. 【神经网络与深度学习】基于Windows+Caffe的Minst和CIFAR—10训练过程说明

    Minst训练 我的路径:G:\Caffe\Caffe For Windows\examples\mnist  对于新手来说,初步完成环境的配置后,一脸茫然.不知如何跑Demo,有么有!那么接下来的教 ...

  10. keras调用预训练模型分类

    在网上看到一篇博客,地址https://www.pyimagesearch.com/2017/03/20/imagenet-vggnet-resnet-inception-xception-keras ...

随机推荐

  1. (图解)Description Resource Path Location Type Java compiler level does not match the version of

    Description Resource Path Location Type Java compiler level does not match the version of project 编译 ...

  2. Flask中的模板语法jinjia2

    Flask中默认的模板语言是Jinja2 I. Jinja2模板语言中的 for {% for foo in g %} {% endfor %} II. Jinja2模板语言中的 if {% if g ...

  3. css浏览器兼容问题集锦

    表单按钮用input type=submit和a链接两者表现不一致的问题 表单的输入框.文本.验证码图片没有对齐 IE6/7中margin失效 IE6中margin双边距 1.问题: 表单按钮用inp ...

  4. ffmpeg 调试

    --enable-debug=3 --disable-optimizations --disable-yasm --disable-asm

  5. JAVA- JSP中解决无法在Cookie当中保存中文字符的问题

    因为cookie的值是ASCII字符,不能直接把自定义cookie的值直接赋值为中文,但是要实现这个功能,还是有方法的. 1.java中已经给我们提供了方法,此时只需要导入该包就行 <%@ pa ...

  6. (1)Java多线程编程核心——Java多线程技能

    1.为什么要使用多线程?多线程的优点? 提高CPU的利用率 2.什么是多线程? 3.Java实现多线程编程的两种方式? a.继承Thread类 public class MyThread01 exte ...

  7. swift的泛型貌似还差点意思

    protocol Container { typealias ItemType mutating func append(item: ItemType) mutating func removelas ...

  8. 《java编程思想》:设计模式(不定期更新)

    1.策略设计模式 创建一个能够根据所传递的参数对象的不同而具有不同的方法,被称为策略设计模式.这类方法包含索要执行的算法中固定不变的部分,而“策略”包含变化的部分.策略就是传递进去的参数对象.在下面的 ...

  9. C语言中的文件操作

    按照字符的方式读取文件 按照行的方式读取文件 按照数据块的方式读取文件 按照格式化的方式读取文件 文件分类 记录文件:具有一定的结构记录组成,分为定长和不定长两种方式 流式文件:按照一个字符一个字符( ...

  10. 'QObject& QObject::operator=(const QObject&)' is private——无法将自定义的QObject子类放入Qt容器(container)中

    先贴出问题的代码: #include<QCoreApplication> classMyObject:publicQObject { public: MyObject(QObject*pa ...