前言

久闻keras大名,最近正好实训,借着这个机会好好学一下。

首先推荐一个API,可能稍微有点旧,但是写的是真的好

https://keras-cn.readthedocs.io/en/latest/

还有一个tensorflow的API

https://www.w3cschool.cn/tensorflow_python/?

还有强烈推荐使用vscode+anaconda 配置环境

环境

安装anaconda和vscode,在conda中新建keras的环境。

conda create -n keras python=3.6
pip install tensorflow # 如果有GPU改为pip install tensorflow-gpu
pip install keras

正题

mnist是入门级别的数据集,是一个基本的分类数据集。这次尝试构造深度神经网络来构造一个图像分类器。


import keras
from keras.datasets import mnist
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense,Conv2D,MaxPooling2D,Flatten
import cv2
import matplotlib
matplotlib.use('TkAgg') batch_size=32
num_classes=10 (train_images,train_labels),(test_images,test_labels) = mnist.load_data() print(train_images.shape,train_labels.shape)
print(test_images.shape,test_labels.shape) """
将数据集中图片展示出来
""" def show_mnist(train_image,train_labels):
n = 3
m = 3
fig = plt.figure()
for i in range(n):
for j in range(m):
plt.subplot(n,m,i*n+j+1)
#plt.subplots_adjust(wspace=0.2, hspace=0.8)
index = i * n + j #当前图片的标号
img_array = train_image[index]
img = Image.fromarray(img_array)
plt.title(train_labels[index])
plt.imshow(img,cmap='Greys')
plt.show() img_row,img_col,channel = 28,28,1 mnist_input_shape = (img_row,img_col,1) #将数据维度进行处理
train_images = train_images.reshape(train_images.shape[0],img_row,img_col,channel)
test_images = test_images.reshape(test_images.shape[0],img_row,img_col,channel) train_images = train_images.astype("float32")
test_images = test_images.astype("float32") ## 进行归一化处理
train_images /= 255
test_images /= 255 # 将类向量,转化为类矩阵
# 从 5 转换为 0 0 0 0 1 0 0 0 0 0 矩阵
train_labels = keras.utils.to_categorical(train_labels,num_classes)
test_labels = keras.utils.to_categorical(test_labels,num_classes) """
构造网络结构
"""
model = Sequential()
model.add(Conv2D(32,kernel_size=(3,3),
activation="relu",
input_shape=mnist_input_shape))
# kernalsize = 3*3 并没有改变数据维度
model.add(Conv2D(16,kernel_size=(3,3),
activation="relu"
))
model.add(MaxPooling2D(pool_size=(2,2)))
# 进行数据降维操作
model.add(Flatten())#Flatten层用来将输入“压平”,即把多维的输入一维化,
#常用在从卷积层到全连接层的过渡。Flatten不影响batch的大小。
model.add(Dense(32,activation="relu"))
#全连接层
model.add(Dense(num_classes,activation='softmax')) """
编译网络模型,添加一些超参数
""" model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy']) model.fit(train_images,
train_labels,
batch_size=batch_size,
epochs=5,
verbose=1,
validation_data=(test_images,test_labels),
shuffle=True
) score = model.evaluate(test_images,test_labels,verbose=1) print('test loss:',score[0])
print('test accuracy:',score[1])

其中涉及到几个keras中的点,感觉看完以后很透彻,但是这只是初步应用,之后还会继续再写的。

jupyter notebook 版本的请访问:https://github.com/pprp/keras-example/tree/master/implement/mnist_keras/

欢迎访问我的Github:https://www.github.com/pprp/ star fork 感激不尽

基于Keras实现mnist-官方例子理解的更多相关文章

  1. 基于Keras 的VGG16神经网络模型的Mnist数据集识别并使用GPU加速

    这段话放在前面:之前一种用的Pytorch,用着还挺爽,感觉挺方便的,但是在最近文献的时候,很多实验都是基于Google 的Keras的,所以抽空学了下Keras,学了之后才发现Keras相比Pyto ...

  2. 基于tensorflow的MNIST手写数字识别(二)--入门篇

    http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...

  3. Caffe系列4——基于Caffe的MNIST数据集训练与测试(手把手教你使用Lenet识别手写字体)

    基于Caffe的MNIST数据集训练与测试 原创:转载请注明https://www.cnblogs.com/xiaoboge/p/10688926.html  摘要 在前面的博文中,我详细介绍了Caf ...

  4. [深度应用]·首届中国心电智能大赛初赛开源Baseline(基于Keras val_acc: 0.88)

    [深度应用]·首届中国心电智能大赛初赛开源Baseline(基于Keras val_acc: 0.88) 个人主页--> https://xiaosongshine.github.io/ 项目g ...

  5. 基于 Keras 用 LSTM 网络做时间序列预测

    目录 基于 Keras 用 LSTM 网络做时间序列预测 问题描述 长短记忆网络 LSTM 网络回归 LSTM 网络回归结合窗口法 基于时间步的 LSTM 网络回归 在批量训练之间保持 LSTM 的记 ...

  6. 基于 Keras 用深度学习预测时间序列

    目录 基于 Keras 用深度学习预测时间序列 问题描述 多层感知机回归 多层感知机回归结合"窗口法" 改进方向 扩展阅读 本文主要参考了 Jason Brownlee 的博文 T ...

  7. 基于TensorRT的BERT实时自然语言理解(下)

    基于TensorRT的BERT实时自然语言理解(下) BERT Inference with TensorRT 请参阅Python脚本bert_inference.py还有详细的Jupyter not ...

  8. 基于TensorRT的BERT实时自然语言理解(上)

    基于TensorRT的BERT实时自然语言理解(上) 大规模语言模型(LSLMs)如BERT.GPT-2和XL-Net为许多自然语言理解(NLU)任务带来了最先进的精准飞跃.自2018年10月发布以来 ...

  9. 最简单的基于FFmpeg的移动端例子:IOS 视频解码器-保存

    ===================================================== 最简单的基于FFmpeg的移动端例子系列文章列表: 最简单的基于FFmpeg的移动端例子:A ...

随机推荐

  1. 第八章 跨语言服务治理方案 Service Mesh

    8.1 Service Mesh 概述 新兴的下一代微服务架构,被称为下一代微服务,同时也是云原生技术栈的代表技术之一. 8.1.1 Service Mesh的由来 从2016年到2018年,serv ...

  2. [US Open 2004][luogu2342] 叠积木 [带权并查集]

    题面 洛谷传送门 思路 害 学了4年多OI,第一次知道还有带权并查集这个东西 wtcl 这个玩意儿的原理和详细实现,可以参考这个博客:带权并查集传送门 这道题,就是在带权并查集的基础上,加个维护每个集 ...

  3. Ehcache配置文件ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http:// ...

  4. 《ucore lab8》实验报告

    资源 ucore在线实验指导书 我的ucore实验代码 练习1: 完成读文件操作的实现(需要编码) 题目 首先了解打开文件的处理流程,然后参考本实验后续的文件读写操作的过程分析,编写在sfs_inod ...

  5. crontab每小时运行一次

    先给出crontab的语法格式 对于网上很多给出的每小时定时任务写法,可以说绝大多数都是错误的!比如对于下面的这种写法: 00 * * * * #每隔一小时执行一次 00 */1 * * * #与上面 ...

  6. Quartz.Net—IJob特性

    IJob默认情况下是无状态的,和其他系统没有关系  特别是job里面的jobdata每次都是新的.可以无限扩展. PersistJobDataAfterExecution JobData持久化 Job ...

  7. maven profiles多环境配置

    maven profiles多环境配置 转载. https://blog.csdn.net/runbat/article/details/81747874 今天做了一个小项目,需要配置开发.测试.预发 ...

  8. python基础学习(十)

    21.文件操作 # r只读 w只写(原来文件会消失!!!,也可以创建新文件) a追 # 加 r+ 读写 story_file = open("Story.txt", "r ...

  9. CMakeLists 添加 -pthread 编译选项 undefined reference to pthread_atfork

    在与 main() 函数同级的 CMakeLists 中添加如下内容(根据项目实际情况修改): cmake_minimum_required (VERSION 2.6) find_package (T ...

  10. 【exgcd】卡片

    卡片 题目描述 你有一叠标号为1到n的卡片.你有一种操作,可以重排列这些卡片,操作如下:1.将卡片分为前半部分和后半部分.2.依次从后半部分,前半部分中各取一张卡片,放到新的序列中.例如,对卡片序列( ...