keras框架的CNN手写数字识别MNIST
参考:林大贵.TensorFlow+Keras深度学习人工智能实践应用[M].北京:清华大学出版社,2018.
首先在命令行中写入 activate tensorflow和jupyter notebook,运行如下代码。当然,事先准备好MNIST数据集。
# coding: utf-8 # In[4]: from keras.datasets import mnist
from keras.utils import np_utils
import numpy as np
np.random.seed(10) # In[5]: (x_train,y_train),(x_test,y_test)=mnist.load_data() # In[6]: x_train4d = x_train.reshape(x_train.shape[0],28,28,1).astype('float32')
x_test4d = x_test.reshape(x_test.shape[0],28,28,1).astype('float32') # In[7]: x_train4d_normalize = x_train4d/255
x_test4d_normalize = x_test4d/255 # In[8]: y_train_oneHot = np_utils.to_categorical(y_train)
y_test_oneHot = np_utils.to_categorical(y_test) # In[9]: from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten,Conv2D,MaxPooling2D # In[10]: model = Sequential() # In[11]: model.add(Conv2D(filters = 16,
kernel_size = (5,5),
padding = 'same',
input_shape = (28,28,1),
activation = ('relu')
)) # In[12]: model.add(MaxPooling2D(pool_size=(2,2))) # In[13]: model.add(Conv2D(filters = 36,
kernel_size = (5,5),
padding = 'same',
activation = 'relu')) # In[14]: model.add(MaxPooling2D(pool_size=(2,2))) # In[15]: model.add(Dropout(0,255)) # In[16]: model.add(Flatten()) # In[17]: model.add(Dense(128,activation = 'relu')) # In[18]: model.add(Dropout(0.5)) # In[19]: model.add(Dense(10,activation = 'sigmoid')) # In[20]: print(model.summary()) # In[21]: model.compile(loss='categorical_crossentropy',
optimizer = 'adam',
metrics = ['accuracy']) # In[22]: train_history = model.fit(x = x_train4d_normalize,
y = y_train_oneHot,
validation_split = 0.2,
epochs = 10,
batch_size = 300,
verbose = 2) # In[23]: import matplotlib.pyplot as plt
def show_train_history(train_history,train,validation):
plt.plot(train_history.history[train])
plt.plot(train_history.history[validation])
plt.title('Train_History')
plt.ylabel(train)
plt.xlabel('Epoch')
plt.legend(['train','validation'], loc = 'upper left')
plt.show() # In[24]: show_train_history(train_history,'acc','val_acc') # In[25]: show_train_history(train_history,'loss','val_loss') # In[26]: scores = model.evaluate(x_test4d_normalize,y_test_oneHot)
scores[1] # In[27]: def plot_image_labels_prediction(images,labels,prediction,idx,num=10):
fig = plt.gcf()
fig.set_size_inches(12,24)
if num>50 : num = 50
for i in range(0,num):
ax = plt.subplot(10,5,1+i)
ax.imshow(images[idx],cmap='binary')
title = "lable="+str(labels[idx])
if len(prediction)>0:
title+=",predict="+str(prediction[idx])
ax.set_title(title,fontsize=10)
ax.set_xticks([]);ax.set_yticks([])
idx+=1
plt.show() # In[28]: prediction = model.predict_classes(x_test4d_normalize) # In[29]: plot_image_labels_prediction(x_test,
y_test,
prediction,
0,
50) # In[30]: import pandas as pd # In[31]: pd.crosstab(y_test,
prediction,
rownames=['label'],
colnames=['predict']) # In[ ]:
卷积神经网络简介:https://www.cnblogs.com/bai2018/p/10413889.html
产生如下神经网络:

其中加入的dropout层用于避免过度拟合。在每次迭代时,随机舍弃一部分的训练样本。
训练效果较好。

林大贵.TensorFlow+Keras深度学习人工智能实践应用[M].北京:清华大学出版社,2018.
keras框架的CNN手写数字识别MNIST的更多相关文章
- keras框架的MLP手写数字识别MNIST,梳理?
keras框架的MLP手写数字识别MNIST 代码: # coding: utf-8 # In[1]: import numpy as np import pandas as pd from kera ...
- TensorFlow 之 手写数字识别MNIST
官方文档: MNIST For ML Beginners - https://www.tensorflow.org/get_started/mnist/beginners Deep MNIST for ...
- Keras cnn 手写数字识别示例
#基于mnist数据集的手写数字识别 #构造了cnn网络拟合识别函数,前两层为卷积层,第三层为池化层,第四层为Flatten层,最后两层为全连接层 #基于Keras 2.1.1 Tensorflow ...
- CNN 手写数字识别
1. 知识点准备 在了解 CNN 网络神经之前有两个概念要理解,第一是二维图像上卷积的概念,第二是 pooling 的概念. a. 卷积 关于卷积的概念和细节可以参考这里,卷积运算有两个非常重要特性, ...
- 卷积神经网络CNN 手写数字识别
1. 知识点准备 在了解 CNN 网络神经之前有两个概念要理解,第一是二维图像上卷积的概念,第二是 pooling 的概念. a. 卷积 关于卷积的概念和细节可以参考这里,卷积运算有两个非常重要特性, ...
- kaggle 实战 (2): CNN 手写数字识别
文章目录 Tensorflow 官方示例 CNN 提交结果 Tensorflow 官方示例 import tensorflow as tf mnist = tf.keras.datasets.mnis ...
- pytorch CNN 手写数字识别
一个被放弃的入门级的例子终于被我实现了,虽然还不太完美,但还是想记录下 1.预处理 相比较从库里下载数据集(关键是经常失败,格式也看不懂),更喜欢直接拿图片,从网上找了半天,最后从CSDN上下载了一个 ...
- keras基于卷积网络手写数字识别
import time import keras from keras.utils import np_utils start = time.time() (x_train, y_train), (x ...
- Tensorflow手写数字识别---MNIST
MNIST数据集:包含数字0-9的灰度图, 图片size为28x28.训练样本:55000,测试样本:10000,验证集:5000
随机推荐
- WAS 忘记密码
一.重置密码 1.首先关闭was,ps –ef|grep java 查看java进程号,然后kill -9 XXXX杀掉进程即可.或者使用命令./stopServer.sh server1 2.取消控 ...
- Trigger,Cursor
USE [Demo]GO /****** Object: StoredProcedure [dbo].[p_couser_Student] Script Date: 02/24/2014 20:43: ...
- 100-days: The one day
Title:In tech race with China, US universities may lose a vital edge in tech race with 与...的科技比赛中 e ...
- linux下Redis主从复制
Redis的主从配置比起MySQL主从配置简单多了,而且Redis主从复制中一个主服务可以有多个从服务,一个从服务又可以有多个从服务. MySQL主从配置http://www.cnblogs.com/ ...
- 37-Arrays.sort() 由大到小排序 和 对象数组排序
1. 由大到小排序: 2. 对象数组排序: 1. 由大到小排序: 注意:必需是Integer 类型的数组!!! 方法一: import java.util.Arrays; import java.ut ...
- golang 通过fsnotify监控文件,并通过文件变化重启程序
一.下载我们需要的包 > go get github.com/fsnotify/fsnotify 二.使用fsnotify监控文件 package main; import ( "gi ...
- 自定义 Mysql 类 与 自定义 异常类
import MySQLdb class MyExcept(Exception): ''' 常见做法定义异常基类,然后在派生不同类型的异常 ''' def __init__(self, *args): ...
- 继承 (js原型链)
原型链是实现继承的主要方法.基本思想:利用原型让一个引用类型继承另一个引用类型的属性和方法. 1.构造函数.原型.实例的关系: 每个构造函数都有原型属性(Prototype),指向一个原型对象(函数创 ...
- js对象(BOM部分/DOM部分)
JS总体包括ECMAScript,DOM,BOM三个部分,但是能够和浏览器进行交互的只有DOM和BOM,那么到底什么是DOM和BOM呢 概念 BOM(Browser Object Model)是指浏览 ...
- [转载]linux awk命令详解
简介 awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再 ...