TensorFlow笔记高级封装Ker

前言

之前在《Tensorflow笔记:高级封装——tf.Estimator》中介绍了Tensorflow的一种高级封装,本文介绍另一种高级封装Keras。Keras的特点就是两个字——简单,不用花时间和脑子去研究各种细节问题。

1.贯序结构

最简单的情况就是贯序模型,就是将网络层一层一层堆叠起来,比如DNN、LeNet等,与之相对的非贯序模型的层和层之间可能存在分叉、合并等复杂结构。下面通过一个LeNet的例子来展示Keras如何实现贯序模型,我们依然采用MNIST数据集举例:

LeNet-5模型结构

首先假设我们已经读到了数据,对于MNIST数据可以通过官方API直接获取,如果是其他数据可以自行进行数据预处理,由于数据读取内容不是本篇介绍重点,所以不做介绍。

(train_images,train_labels),(valid_images,valid_labels)=tf.keras.datasets.mnist.load_data()train_images=train_images.reshape(-1,8,8,1)valid_images=valid_images.reshape(-1,8,8,1)train_images,valid_images=train_images/55.0,valid_images/55.0

最后数据的格式为(n,height,width,channel),数据和标签的dtype分别为float和int,Keras相比与原生和tf.Estimator相比对于数据type的要求比较友好。

print(train_images.shape)#(,8,8)print(train_labels.shape)#(,)print(train_images.dtype)#float64/float3都可以print(train_labels.dtype)#uint8/int16/int3/int64等都可以

接下来开始构建模型

importtensorflowastffromtensorflow.keras.optimizersimportSGD#构建模型结构model=tf.keras.models.Sequential([tf.keras.layers.ConvD(6,(5,5),activation=tanh,input_shape=(8,8,1)),tf.keras.layers.MaxPoolingD(,),tf.keras.layers.ConvD(16,(5,5),activation=tanh),tf.keras.layers.MaxPoolingD(,),tf.keras.layers.Flatten(),tf.keras.layers.Dense(10,activation=tanh),tf.keras.layers.Dense(84,activation=tanh),tf.keras.layers.Dense(10,activation=softmax)])#模型编译(告诉模型怎么优化)model.


转载请注明:http://www.zpwkh.com/bzbk/13920.html

  • 上一篇文章:
  •   
  • 下一篇文章:

  • 当前时间: