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

第六章 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. Go 初体验 - 令人惊叹的语法 - defer.3 - defer 函数参数计算时机
  2. JS Math对象中一些小技巧
  3. 相机标定(三) —— 畸变校正
  4. linux之vim复制多行、光标跳转到指定行、插入当前光标上和下行
  5. mongodb atlas_如何使用MongoDB Atlas将MERN应用程序部署到Heroku
  6. JAVA springboot ssm b2b2c多用户商城系统源码(三):服务提供与调用
  7. 计算机病毒通常是指一段指令或什么,计算机病毒通常是()。 - 问答库
  8. eyoucms栏目类型介绍
  9. 如何用计算机求矩阵的逆矩阵,逆矩阵的求法
  10. 《数据清洗》 第六章 数据转换
  11. 丁磊:求快是创业者的思维误区,过于强调时间窗口也是一个伪命题
  12. 渗透火狐浏览器设置代理
  13. 基于eBPF的开源工具Kindling之page-fault事件可观测性实现机制
  14. Olly Script Editor V2.0
  15. 头歌 共享单车大数据项目数据分析
  16. DIY背景美化生成器微信小程序源码
  17. @程序员,对抗 996,你真的准备好了吗?
  18. Linux ALSA 之九:ALSA ASOC Codec Driver
  19. 南大计算机博士黄鑫,南京大学软件学院张贺教授团队在经验软件工程方法学研究中取得重要成果...
  20. VScode受难记 - 0

热门文章

  1. docker环境下安装rockermq以及rockermq-console
  2. 蘑菇游戏_让蘑菇动起来
  3. Adobe系列在安装时,出现安装程序检测到计算机重新启动的过程中可能暂停、安装失败
  4. 游戏开发:通过路径搜索优先级来进行补丁升级(从端游到手游)
  5. 大学职业生涯规划书_计算机专业,4000字,合肥大学
  6. 东软医疗打印设置java,关于单据打印的调试方法常见问题与使用技巧
  7. VGG16 - 咖啡豆识别
  8. 解决TexStudio编写LaTeX论文引用文献问题:正文引用处出现[?],参考文献也不显现
  9. 2018年优秀作译者TOP10揭晓,看看你喜欢的上榜了吗
  10. 如何用Pyqt5实现在程序中动态修改界面的语言(英语转中文或者中文转英语)