every blog every motto: You can do more than you think.
0. 前言
我们知道对于分类问题,最后一层会经过softmax,关于最后结果我们用数据进行验证。
1. 正文
softmax公式:
import numpy as np
import os, sys
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from tensorflow.keras.layers import *
import tensorflow as tf
1.1 一维
# 一维情况
tensor1 = tf.constant(np.array([1, 0, 0]), dtype=tf.float32)
print('tensor1: ', tensor1)
print('tensor1 shape: ', tensor1.shape)
tensor1_soft = Softmax()(tensor1)
print(tensor1_soft)
print('-' * 50)
结果:
由上面结果可知,我们对一维内的数据按照上述公式进行求解,我们可以numpy加以验证:
np_soft = np.exp(tensor1) / np.sum(np.exp(tensor1))
print(np_soft)
print('-*'*20)
结果:
得到的结果和前面进行softmax的结果一致。
1.2 二维
# 二维情况
tensor2 = tf.constant(np.array([[1, 1], [2, 0]]), dtype=tf.float32)
print('tensor2: ', tensor2)
print('tensor2.shape: ', tensor2.shape)
tensor2_soft = Softmax()(tensor2)
print(tensor2_soft)
print('-' * 50)
结果:
上面的结果,我们可以发现,只对[1,1] ;[2,0] 各自做了softmax,这里暂时不过多解释。
具体过程:
以其中两个数为例:
1.3 三维
1.3.1 第一种情况
# 三维情况
tensor3 = tf.constant(np.array([[[1, 1], [1, 0], [0, 0]]]), dtype=tf.float32)
print('tensor3: ', tensor3)
print('tensor3.shape', tensor3.shape)
print('-'*29)
tensor3_soft = Softmax()(tensor3)
print(tensor3_soft)
结果:
1.3.2 第二种情况
# 三维情况
tensor3 = tf.constant(np.array([[[1], [0]], [[2], [1]], [[0], [0]]]), dtype=tf.float32)
print('tensor3: ', tensor3)
print('tensor3.shape', tensor3.shape)
print('-' * 29)
tensor3_soft = Softmax()(tensor3)
print(tensor3_soft)
结果:
由上面结果,我们发现所有的值都为1,我们再联系所有tensor的shape,可以发现,这样一个规律:
Softmax对最后一维内的数据进行求解。
1.4 ReLu(附)
这里我们仅列举一列,以三维为例:
结果(结论)与Softmax相同
# 三维情况
tensor3 = tf.constant(np.array([[[1], [-1]], [[2], [1]], [[0], [0]]]), dtype=tf.float32)
print('tensor3: ', tensor3)
print('tensor3.shape', tensor3.shape)
print('-' * 29)
tensor3_soft = ReLU()(tensor3)
print(tensor3_soft)
结果:
1.5 小结
-
至此,我们由上面可以发现,得到如下结论:
激活函数对特征图的最后一维,进行求解。 -
这也是为什么有关分类问题,模型最后输出的特征图的shape中的最后一维的维数等于分类数 (这句话可能有点绕)
-
我们可以联想之前再语义分割讲解中,模型最后输入shape为(208*208,2),即(43264,2),他的最后一维维数为2,对这两个数进行softmax求取概率。
参考文献
[1] https://blog.csdn.net/weixin_39190382/article/details/106301781
[2] https://zhuanlan.zhihu.com/p/105722023
[3] https://blog.csdn.net/weixin_39190382/article/details/106516370
[4] https://blog.csdn.net/siyue0211/article/details/81017728