书本上提供的代码下载地址失效了

第六章 kerasMNIST手写数字识别数据集和第七章Keras多层感知器识别手写数字的代码

单纯的按书上的顺序copy下来的,自己加了点注释

jupyter notebook上实现

import numpy as np
import pandas as pd
from keras.utils import np_utils
np.random.seed(10)
from keras.datasets import mnist
(X_train_image,y_train_label),\
(X_test_image,y_test_label)=mnist.load_data()
print('train data=',len(X_train_image))
print('test data=',len(X_test_image))
print('X_train_image:',X_train_image.shape)
print('y_train_label:',y_train_label.shape)
import matplotlib.pyplot as plt
def plot_image(image):fig=plt.gcf()fig.set_size_inches(2,2)plt.imshow(image,cmap='binary')plt.show()plot_image(X_train_image[0])
y_train_label[0]
import matplotlib.pyplot as plt
def plot_images_labels_prediction(image,labels,prediction,idx,num=10):
#num要显示的数据项数,默认为10,最大25fig=plt.gcf()fig.set_size_inches(12,14)if num>25:num=25for i in range(0,num):ax=plt.subplot(5,5,1+i)ax.imshow(image[idx],cmap='binary')title="label="+str(labels[idx])itle='label='+str(labels[idx])if(len(prediction)>0):title+=",prediction="+str(prediction[idx])ax.set_title(title,fontsize=10)ax.set_xticks([])ax.set_yticks([])idx+=1plt.show()plot_images_labels_prediction(X_train_image,y_train_label,[],0,10)
print('X_test_image:',X_test_image.shape)
print('y_test_label:',y_test_label.shape)
plot_images_labels_prediction(X_test_image,y_test_label,[],0,10)
X_Train=X_train_image.reshape(60000,784).astype('float32')
#将28*28的数字图像reshape转换为一维向量,astype转为float
X_Test=X_test_image.reshape(10000,784).astype('float32')
print('X_Train:',X_Train.shape)
print('X_Test:',X_Test.shape)
X_train_image[0]
X_Train_normalize=X_Train/255
X_Test_normalize=X_Test/255
X_Train_normalize[0]
y_train_label[:5]
y_Train_OneHot=np_utils.to_categorical(y_train_label) #np_utils.to_categorical进行热编码转换
y_Test_OneHot=np_utils.to_categorical(y_test_label)print(y_train_label[:5])#转换前
y_Train_OneHot[:5]#转换后,每个label用10个0,1来表示,对应10个神经元

用多层感知机来训练

#数据预处理
import numpy as np
from keras.utils import np_utils
from keras.datasets import mnist
np.random.seed(10)(x_train_image,y_train_label),(x_test_image,y_test_label)=mnist.load_data()
x_Train=x_train_image.reshape(60000,784).astype('float32')
x_Test=x_test_image.reshape(10000,784).astype('float32')
x_Train_normalize=x_Train/255
x_Test_normalize=x_Test/255
y_Train_OneHot=np_utils.to_categorical(y_train_label)
y_Test_OneHot=np_utils.to_categorical(y_test_label)#建立模型
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
model=Sequential()#Sequential模型
#units隐藏层神经元个数,输入层的神经元个数784,使用正态分布的随机数来初始化权重和偏差,激活函数为relu
model.add(Dense(units=1000,input_dim=784,kernel_initializer='normal',activation='relu'))
model.add(Dropout(0.5))#加入第二层隐藏层
model.add(Dense(units=1000,kernel_initializer='normal',activation='relu'))
model.add(Dropout(0.5))
#输出层的神经元个数10,使用正态分布的随机数来初始化权重和偏差,激活函数为sofmax
model.add(Dense(units=10,kernel_initializer='normal',activation='relu'))
#查看模型
print(model.summary())
#compile对训练模型进行设置
#loss为交叉熵,adam优化器,metrics模型评估的方式是准确率
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])#开始训练
#训练过程会储存在train_history中,x特征值,y真实的label,validation_split训练与验证数据集的比例
#epoch训练周期,batch_size每一批次的数据,
train_history=model.fit(x=x_Train_normalize,y=y_Train_OneHot,validation_split=0.2,epochs=10,batch_size=200,verbose=2)
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.xlabel('Epoch')plt.ylabel('train')plt.legend(['train','validation'],loc='upper left')plt.show()
show_train_history(train_history,'acc','val_acc')
show_train_history(train_history,'loss','val_loss')
#评估模型准确率
scores=model.evaluate(x_Test_normalize,y_Test_OneHot)
print('accuracy=',scores[1])
#进行预测
prediction=model.predict_classes(x_Test)
plot_images_labels_prediction(x_test_image,y_test_label,prediction,idx=340) 
#建立混淆矩阵
import pandas as pd
pd.crosstab(y_test_label,prediction,rownames=['label'], colnames=['predict'])

《TensorFlow+Keras深度学习人工智能实践应用》林大贵著第六章第七章代码相关推荐

  1. Windows+Anaconda+tensorflow+keras深度学习框架搭建--reproduced

    转载于网络,已备查用. 现在把windows下的Anaconda+tensorflow+keras深度学习框架搭建过程记录如下 1.下载安装Anaconda记住支持版本一定是python3以上的版本 ...

  2. TensorFlow深度学习应用实践

    http://product.dangdang.com/25207334.html 内 容 简 介 本书总的指导思想是在掌握深度学习的基本知识和特性的基础上,培养使用TensorFlow进行实际编程以 ...

  3. windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

    windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe.TensorFlow.Keras深度学习GPU环境 事情的由来 第一步,你得先有个windows7操作 ...

  4. 深度学习算法实践(基于Theano和TensorFlow)

    深度学习算法实践(基于Theano和TensorFlow) 闫涛 周琦 著 ISBN:9787121337932 包装:平装 开本:16开 用纸:胶版纸 正文语种:中文 出版社:电子工业出版社 出版时 ...

  5. [Python人工智能] 三十.Keras深度学习构建CNN识别阿拉伯手写文字图像

    从本专栏开始,作者正式研究Python深度学习.神经网络及人工智能相关知识.前一篇文章分享了生成对抗网络GAN的基础知识,包括什么是GAN.常用算法(CGAN.DCGAN.infoGAN.WGAN). ...

  6. 如何使用Keras和TensorFlow建立深度学习模型以预测员工留任率

    The author selected Girls Who Code to receive a donation as part of the Write for DOnations program. ...

  7. 人工神经网络理论、设计及应用_TensorFlow深度学习应用实践:教你如何掌握深度学习模型及应用...

    前言 通过TensorFlow图像处理,全面掌握深度学习模型及应用. 全面深入讲解反馈神经网络和卷积神经网络理论体系. 结合深度学习实际案例的实现,掌握TensorFlow程序设计方法和技巧. 着重深 ...

  8. DL框架之Tensorflow:深度学习框架Tensorflow的简介、安装、使用方法之详细攻略

    DL框架之Tensorflow:深度学习框架Tensorflow的简介.安装.使用方法之详细攻略 目录 Tensorflow的简介 1.描述 2.TensorFlow的六大特征 3.了解Tensorf ...

  9. 万字总结Keras深度学习中文文本分类

    摘要:文章将详细讲解Keras实现经典的深度学习文本分类算法,包括LSTM.BiLSTM.BiLSTM+Attention和CNN.TextCNN. 本文分享自华为云社区<Keras深度学习中文 ...

最新文章

  1. 聊聊前段插件之Datatables
  2. linux设置history历史记录
  3. FFMPEG中H.264的算法文档--整理自ffmpeg论坛等
  4. linux编译c 优化,Linux编译选项
  5. 【Deep Learning 五】课程二(mproving Deep Neural Networks),第一周(Setting up your Machine Learning Applicat)答案
  6. ProCAD.2D/3D.Designer.v2008.1 1CD(最大程度地提高管道设计效率)\
  7. sicilyOJ 09广东省赛重现H Westward Journey Online(线段树)
  8. matlab修改图片部分像素值
  9. redis查看集合中元素的数量,scard
  10. 从非诚勿扰看数据索引,优化代码小妙招
  11. 功放与喇叭的匹配原则
  12. Handheld Multi-Frame Super-Resolution论文理解
  13. 程序猿也爱学英语,有图有真相!
  14. 编程中的幂等性 —— HTTP幂等性
  15. Python语音合成探究(一、男声和女声的选择)
  16. 超详细快速入门JavaScript详解(一)
  17. 【AI测试】人工智能测试整体介绍——第六部分
  18. Verilog时序逻辑硬件建模设计(四)移位寄存器
  19. 谭浩强 《C程序设计》(第五版)第二章
  20. 2010 27寸 imac 升级固态_新iMac拆解证实 自行加装SSD难如登天

热门文章

  1. 【矩阵】蛇形 平方
  2. 区块链与分布式隐私计算行业报告 | TokenInsigh
  3. DRN 与 GAN相关知识
  4. ACM JAVA+C常用方法模板
  5. 2021 大促 AntMonitor 总结 - 云原生 Prometheus 监控实践
  6. tensorflow 中文字体训练集_深度学习与TensorFlow:自建手写字体数据集上的模型测试...
  7. Spring和Redis整合详解
  8. 江哥带你玩转C语言 | 13- 一级指针和多级指针
  9. java for windows 7_javaj基础之Window 系统下 Java 环境搭建(一)
  10. ArcGis 打开CAD文件的几种方法