Tensorflow2.0 Keras高层接口之Softmax网络层类

Tensorflow2.0Keras高层接口之Softmax网络层类

tensorflow2.0 keras中的网络层接口简介

对于常见的神经网络层,可以使用张量方式的底层接口函数来实现,这些接口函数一般在tf.nn 模块中。更常用地,对于常见的网络层,我们一般直接使用层方式来完成模型的搭建,在tf.keras.layers 命名空间(下文使用layers 指代tf.keras.layers)中提供了大量常见网络层的类,如全连接层、激活函数层、池化层、卷积层、循环神经网络层等。对于这些网络层类,只需要在创建时指定网络层的相关参数,并调用__call__方法即可完成前向计算。在调用__call__方法时,Keras 会自动调用每个层的前向传播逻辑,这些逻辑一般实现在类的call 函数中。

Softmax层

Softmax层: Softmax层经常多为输出层的设计,通多Softmax层的维度上的值相加会等于1

以 Softmax 层为例,它既可以使用tf.nn.softmax 函数在前向传播逻辑中完成Softmax运算,也可以通过layers.Softmax(axis)类搭建Softmax 网络层,其中axis 参数指定进行softmax 运算的维度。首先导入相关的子模块,实现如下:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# 创建Softmax层,,并调用__call__方法完成前向计算
x = tf.constant([2., 1., 0.1])
layer = layers.Softmax(axis=-1)
out = layer(x)
print(out)
Out[1]:
<tf.Tensor: id=2, shape=(3,), dtype=float32, numpy=array([0.6590012,
0.242433 , 0.0985659], dtype=float32)>
发布了62 篇原创文章 · 获赞 33 · 访问量 3477

猜你喜欢

转载自blog.csdn.net/python_LC_nohtyp/article/details/104272797