TensorFlow中Softmax函数的轴操作与概率意义解析
本文深入解析TensorFlow中Softmax函数的核心机制。重点讲解axis参数如何指定归一化维度,通过代码示例展示不同轴上的输出结果及求和为1的特性。同时详细阐述Softmax输出值作为条件概率P(label|value)的实际物理意义,并结合Batch和Timesteps维度说明其在序列模型中的应用。
具体实现如下所示:
def softmax(logits, axis=None, name=None, dim=None):
"""Computes softmax activations.
This function performs the equivalent of
softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)
Args:
logits: A non-empty `Tensor`. Must be one of the following types: `half`,
`float32`, `float64`.
axis: The dimension softmax would be performed on. The default is -1 which
indicates the last dimension.
name: A name for the operation (optional).
dim: Deprecated alias for `axis`.
Returns:
A `Tensor`. Has the same type and shape as `logits`.
Raises:
InvalidArgumentError: if `logits` is empty or `axis` is beyond the last
dimension of `logits`.
"""
axis = deprecation.deprecated_argument_lookup("axis", axis, "dim", dim)
if axis is None:
axis = -1
return _softmax(logits, gen_nn_ops.softmax, axis, name)
Softmax对张量的变换机制
Softmax函数的输出张量形状与输入张量完全一致,这意味着它并未改变张量的几何结构。那么,Softmax究竟对张量内部的数据进行了怎样的变换?
其核心机制是:Softmax会选取特定的轴索引作为基准,对该轴上其他维度的数值执行激活函数处理(指数运算)并进行归一化(除以总和)。
在常规应用场景中,这个被选中的轴通常对应于类别维度。例如,在tf.nn.softmax函数中,默认参数axis=-1,即默认对最后一个维度进行Softmax计算。
Softmax计算示例与轴特性
为了直观理解,我们来看一个具体的计算示例:
def softmax(X, theta = 1.0, axis = None):
"""
Compute the softmax of each element along an axis of X.
Parameters
----------
X: ND-Array. Probably should be floats.
theta (optional): float parameter, used as a multiplier
prior to exponentiation. Default = 1.0
axis (optional): axis to compute values along. Default is the
first non-singleton axis.
Returns an array the same size as X. The result will sum to 1
along the specified axis.
"""
# make X at least 2d
y = np.atleast_2d(X)
# find axis
if axis is None:
axis = next(j[0] for j in enumerate(y.shape) if j[1] > 1)
# multiply y against the theta parameter,
y = y * float(theta)
# subtract the max for numerical stability
y = y - np.expand_dims(np.max(y, axis = axis), axis)
# exponentiate y
y = np.exp(y)
# take the sum along the specified axis
ax_sum = np.expand_dims(np.sum(y, axis = axis), axis)
# finally: divide elementwise
p = y / ax_sum
# flatten if X was 1D
if len(X.shape) == 1: p = p.flatten()
return p
c = np.random.randn(2,3)
print(c)
# 假设第0维是类别,一共有里两种类别
cc = softmax(c,axis=0)
# 假设最后一维是类别,一共有3种类别
ccc = softmax(c,axis=-1)
print(cc)
print(ccc)
最终输出的数值结果如下:
c:
[[-1.30022268 0.59127472 1.21384177]
[ 0.1981082 -0.83686108 -1.54785864]]
cc:
[[0.1826746 0.80661068 0.94057075]
[0.8173254 0.19338932 0.05942925]]
ccc:
[[0.0500392 0.33172426 0.61823654]
[0.65371718 0.23222472 0.1140581 ]]
观察可知,当对axis=0执行Softmax时,输出结果在axis=0方向上的元素之和为1(例如:0.1826746 + 0.8173254 = 1)。同理,若在axis=1方向上执行,该轴上的输出元素之和同样为1(例如:0.0500392 + 0.33172426 + 0.61823654 = 1)。
这些具体的数值是如何计算得出的?
以cc为例(沿axis=0方向进行Softmax计算):

以ccc为例(沿axis=1方向进行Softmax计算):

Softmax输出值的概率意义
明确了计算逻辑后,我们进一步探讨这些输出值的实际物理含义:
cc[0,0]的值实际上代表了一种概率:P(label = 0 | value = [-1.30022268, 0.1981082] = c[*,0]) = 0.1826746。
cc[1,0]的值代表另一种概率:P(label = 1 | value = [-1.30022268, 0.1981082] = c[*,0]) = 0.8173254。
ccc[0,0]的值表示:P(label = 0 | value = [-1.30022268, 0.59127472, 1.21384177] = c[0]) = 0.0500392。
ccc[0,1]的值表示:P(label = 1 | value = [-1.30022268, 0.59127472, 1.21384177] = c[0]) = 0.33172426。
ccc[0,2]的值表示:P(label = 2 | value = [-1.30022268, 0.59127472, 1.21384177] = c[0]) = 0.61823654。
高维张量中的应用
将这一概念推广至更高维度的情况:假设c是一个形状为[batch_size, timesteps, categories]的三维张量。
output = tf.nn.softmax(c, axis=-1)
此时,output[1, 2, 3]表示的条件概率为:P(label = 3 | value = c[1, 2])。
以上关于TensorFlow Softmax函数用法及原理的解析内容,旨在为读者提供清晰的参考。希望本文能帮助大家深入理解Softmax机制,欢迎持续关注本站获取更多技术分享。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













