tf.keras入门系列(一)

文章目录


tf.keras的API是Tensorflow2.0的高级API,本小节简单介绍其用法。
按照官方文档分,tf.keras可以分为Modules、Classes、Functions三个部分。

Modules

  • activations 包含了当前主流激活函数,可以直接通过API进行激活函数的调用
  • applications 模块中是已经进行欲训练的神经模型,可直接用作预测或者迁移学习
  • backend 包含了keras后台的基础API接口,用于实现高级API或者自己构建神经网络
  • layers 包含众多的神经网络层接口,可以以直接调用API的方式构建神经网络结构。
  • losses 包含了常用的损失函数,可在需要时直接调用
  • optimizers 包含了主流的优化器
  • preprocessing 数据处理的一些方法,有图片数据处理,语言序列处理,文本处理等等
  • regularizes 正则化方法
  • wrappers 一个keras模型的包装器,当需要进行跨框架迁移时,可以使用该API接口提供与其他框架的兼容性

其中每个部分这里就不展开讲了,后面会详细讲解。

Classes

  • Model groups layers into an object with training and inference features.
  • Sequential: Linear stack of layers.

这是官方文档上的解释,不太好解释,直接贴出原文。
这里有两种方法实例化Model,其中一种是:使用“函数API”,从Input开始,连接各层、指定模型的前向传播,最后由输入和输出创建模型。

import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
model
#<tensorflow.python.keras.engine.training.Model at 0x1af47010c50>

对于Sequential,其经常被用来快速构建神经网络。

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
# Optionally, the first layer can receive an `input_shape` argument:
model = Sequential()
model.add(Dense(32, input_shape=(500,)))
# Afterwards, we do automatic shape inference:
model.add(Dense(32))
# This is identical to the following:
model = Sequential()
model.add(Dense(32, input_dim=500))

Input

Input用于将实例化一个Tensor张量
参数如下:

tf.keras.Input(
    shape=None,
    batch_size=None,
    name=None,
    dtype=None,
    sparse=False,
    tensor=None,
    ragged=False,
    **kwargs
)

调用如下:

import tensorflow as tf
x=tf.keras.Input(shape=(32,))
tf.square(x)
#<tf.Tensor 'input_7:0' shape=(None, 32) dtype=float32>

本小节就到这,未完待续。

发布了24 篇原创文章 · 获赞 2 · 访问量 1180

猜你喜欢

转载自blog.csdn.net/qq_40176087/article/details/100752065
今日推荐