仅仅为了学习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. Java for LeetCode 114 Flatten Binary Tree to Linked List

    Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 ...

  2. 使用viewholder优化listview,减少findViewById的次数

  3. mvn 创建的项目 导入到eclipse

    首先,我的工具版本如下: jdk: java version "1.6.0_10-rc2"; maven: apache-maven-3.1.0; eclipse: MyEclip ...

  4. 请求时token过期自动刷新token

    1.在开发过程中,我们都会接触到token,token的作用是什么呢?主要的作用就是为了安全,用户登陆时,服务器会随机生成一个有时效性的token,用户的每一次请求都需要携带上token,证明其请求的 ...

  5. 修改ubuntu14.04命令行启动

    方法1: 原来要想默认不进入xwindows,只需编辑文件”/etc/default/grub”, 把 GRUB_CMDLINE_LINUX_DEFAULT=”quiet splash” 改成GRUB ...

  6. 分享知识-快乐自己:2017IDEA破解教程

    首先 修改host文件: 文件路径:C:\Windows\System32\drivers\etc\hosts 修改:将“0.0.0.0 account.jetbrains.com”追加到hosts文 ...

  7. MyBatis映射文件中用#和$传递参数的特点

    在MyBatis映射文件中用#和$传递参数的特点, #是以占位符的形式来传递对应变量的参数值的,框架会对传入的参数做预编译的动作, 用$时会将传入的变量的参数值原样的传递过去,并且用$传递传递参数的时 ...

  8. 3D Flip

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. bootstrap框架日期时间 开始日期和结束日期选择

    页面表单查询时,常要求要查询一个日期时间段内的数据,若采用bootstrap框架的datetimepicker插件来控制,需要了解怎么个用法:

  10. lsnrctl启动报错,Linux Error: 29: Illegal seek

    [oracle@phydb admin]$ lsnrctl startLSNRCTL for Linux: Version 11.2.0.1.0 - Production on 15-SEP-2014 ...