文章目录
- 前言
- 一、Keras流程
- 二、Keras中的模型定义
- 1.基于Sequential 类
- 2.基于函数式API
前言
目前打算看tensorflow.probability模块,但是发现整个都是适配Keras的,很多的例程也都是基于Keras的。所以借此机会学一下这个框架。
一、Keras流程
目前keras已经集成在了tf之中,默认的import方式如下所示,一般用到最多的就是layers
层。
tfk = tf.keras
tfkl = tf.keras.layers
network = tfk.Sequential()
vae = tfk.Model(inputs=encoder.inputs, outputs=decoder(encoder.outputs[0]))
network.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
network.fit(train_images, train_labels, epochs=5, batch_size=128)
二、Keras中的模型定义
定义模型有两种方法:
- 一种是使用
Sequential 类
(仅用于层的线性堆叠,这是目前最常见的网络架构) - 另一种是
函数式 API
( functional API,用于层组成的有向无环图,可以构建任意形式的架构)。
1.基于Sequential 类
这种方式只能用于直通传播,并不适用于ResNet这样有跳跃层、单层具有多输入多输出的情况。使用方法有列表直接添加
和增量式add()
添加:
model = keras.Sequential(
[
layers.Dense(2, activation="relu", name="layer1"),
layers.Dense(3, activation="relu", name="layer2"),
layers.Dense(4, name="layer3"),
]
)
x = tf.ones((3, 3))
y = model(x)
model = keras.Sequential()
model.add(layers.Dense(2, activation="relu"))
model.add(layers.Dense(3, activation="relu"))
model.add(layers.Dense(4))
完成模型的搭建之后可以使用model.summary()
输出模型的层信息:
Model: "sequential_4"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_10 (Dense) (None, 2) 10
=================================================================
Total params: 10
Trainable params: 10
Non-trainable params: 0
_________________________________________________________________
2.基于函数式API
这种搭建方法更加地自由,可以以函数的形式进行任意连接(类似Pytorch):
input_tensor = tfkl.Input(shape=(784,))
x = tfkl.Dense(32, activation='relu')(input_tensor)
output_tensor = tfkl.Dense(10, activation='softmax')(x)
model = models.Model(inputs=input_tensor, outputs=output_tensor)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)