参考:林大贵.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的更多相关文章

  1. keras框架的MLP手写数字识别MNIST,梳理?

    keras框架的MLP手写数字识别MNIST 代码: # coding: utf-8 # In[1]: import numpy as np import pandas as pd from kera ...

  2. TensorFlow 之 手写数字识别MNIST

    官方文档: MNIST For ML Beginners - https://www.tensorflow.org/get_started/mnist/beginners Deep MNIST for ...

  3. Keras cnn 手写数字识别示例

    #基于mnist数据集的手写数字识别 #构造了cnn网络拟合识别函数,前两层为卷积层,第三层为池化层,第四层为Flatten层,最后两层为全连接层 #基于Keras 2.1.1 Tensorflow ...

  4. CNN 手写数字识别

    1. 知识点准备 在了解 CNN 网络神经之前有两个概念要理解,第一是二维图像上卷积的概念,第二是 pooling 的概念. a. 卷积 关于卷积的概念和细节可以参考这里,卷积运算有两个非常重要特性, ...

  5. 卷积神经网络CNN 手写数字识别

    1. 知识点准备 在了解 CNN 网络神经之前有两个概念要理解,第一是二维图像上卷积的概念,第二是 pooling 的概念. a. 卷积 关于卷积的概念和细节可以参考这里,卷积运算有两个非常重要特性, ...

  6. kaggle 实战 (2): CNN 手写数字识别

    文章目录 Tensorflow 官方示例 CNN 提交结果 Tensorflow 官方示例 import tensorflow as tf mnist = tf.keras.datasets.mnis ...

  7. pytorch CNN 手写数字识别

    一个被放弃的入门级的例子终于被我实现了,虽然还不太完美,但还是想记录下 1.预处理 相比较从库里下载数据集(关键是经常失败,格式也看不懂),更喜欢直接拿图片,从网上找了半天,最后从CSDN上下载了一个 ...

  8. keras基于卷积网络手写数字识别

    import time import keras from keras.utils import np_utils start = time.time() (x_train, y_train), (x ...

  9. Tensorflow手写数字识别---MNIST

    MNIST数据集:包含数字0-9的灰度图, 图片size为28x28.训练样本:55000,测试样本:10000,验证集:5000

随机推荐

  1. 最长公共子序列hdu1503

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1503 题意:给你两个字符串,把这两个字符串合并,使合并之后的字符串最短,并且合并之后的字符之间的相对位 ...

  2. c++面向行的输入getline()和get()

    来源:c++ primer plus 在c++里当我们输入一个字符串时习惯用cin,但是cin只能读取一段不含空格的字符串,如果我们需要读取一段包含空格的字符串时,就需要用到getline()或get ...

  3. [剑指Offer]42-连续子数组的最大和(DP)

    题目链接 https://www.nowcoder.com/practice/459bd355da1549fa8a49e350bf3df484?tpId=13&tqId=11183&t ...

  4. 【Linux 线程】同一个进程中的线程共享哪些资源

    进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动,进程是系统进行资源分配和调度的一个独立单位. 线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位.线 ...

  5. Django的model操作中一些常用的小点

    一.django的orm的13种基本的查询方法 1.all方法,查询某张表中的所有的数据 user_obj_list = models.Person.objects.all() 返回的结果是query ...

  6. rsync同步工具的配置与使用

    一.什么是rsync?rsync是一款开源的,快速的,多功能的,可实现全量及增量的本地或远程数据同步备份的优秀工具. rsync官网 http://rsync.samba.org/ 二.rsync的工 ...

  7. avalon子孙元素属性监听

    HTML正文: <body ms-controller="ex"> <div class="ms-hover" ms-click=" ...

  8. css背景图充满屏幕

    代码: body { /* 加载背景图 */ background: url(resource/inv_bg.png); /* 背景图不平铺 */background-repeat: no-repea ...

  9. JavaScript 字符串用于存储和处理文本

    JavaScript 字符串用于存储和处理文本 var string_value='dasfsdfsd'; 注意:字符串利用索引精确定位取值 var character=string_value[7] ...

  10. 8M - 三角形

    用N个三角形最多可以把平面分成几个区域?  Input 输入数据的第一行是一个正整数T(1<=T<=10000),表示测试数据的数量.然后是T组测试数据,每组测试数据只包含一个正整数N(1 ...