以Numpy、Keras、TensorFlow和PyTorch为例解读神经网络的Softmax激活函数

535 阅读2分钟

简介

激活函数是神经网络的一个组成部分,决定了模型的行为方式。有许多激活函数可供选择,这往往导致初学者的困惑。在这篇文章中,我们将结合Numpy、Keras、TensorFlow和PyTorch中的例子,讨论并解释Softmax激活函数的特点。

我们将为初学者保持直观水平的解释。因此,让我们开始吧。

什么是神经网络中的激活函数?

Softmax Activation Function

在神经网络中,激活函数被用来转换人工神经元的传入信号,以产生输出信号。激活函数对于向网络添加非线性以产生能够理解现实世界数据的复杂非线性关系的模型至关重要。

Softmax激活函数

Softmax激活函数将人工神经元的输入信号转换为概率分布。

它通常用在多类分类器的神经网络的最后一层,在那里我们必须为类产生概率分布作为输出。

正如你在下面的插图中所看到的,来自前一个隐藏层的传入信号通过softmax激活函数,它产生了三个类别的概率分布。具有最高概率的类别被选为预测类别。

Softmax Function Multiclass Classification

软极限激活函数公式

在数学上,它是一个广义的sigmoid函数(另一个激活函数),其公式如下

Softmax Activation Function Formula

这里z是输入神经元的向量,k是多类分类问题中的类数。

Numpy中的Softmax函数

你可以使用Numpy库来创建计算Softmax函数,如下所示

例子

import numpy as np

input = [3,4,1]

output=np.exp(input - np.max(input))/np.exp(input - np.max(input)).sum()
output

输出。

array([0.25949646, 0.70538451, 0.03511903])

TensorFlow中的Softmax函数

在TensorFlow中,你可以通过使用_tf.nn.softmax()_函数应用Softmax函数。

例子

import tensorflow as tf

input = tf.constant([[3,4,1]], dtype = tf.float32)

output = tf.nn.softmax(a)
output.numpy()

输出。

array([[0.25949648, 0.7053845 , 0.03511902]], dtype=float32)

你也可以创建你自己的自定义公式来计算Softmax函数,如下例所示

例子

import tensorflow as tf
input = tf.constant([[3,4,1]], dtype = tf.float32)

output = tf.exp(inputs) / tf.reduce_sum(tf.exp(inputs), axis=1)
output.numpy()

输出。

array([[0.25949645, 0.7053845 , 0.03511903]], dtype=float32)

Keras中的Softmax函数

在 TF Keras 中,您可以通过使用_tf.keras.activations.softmax()_ 函数来应用 Softmax 功能。

例子

import tensorflow as tf

inputs = tf.constant([[3,4,1]], dtype = tf.float32)

outputs = tf.keras.activations.softmax(inputs)
outputs.numpy()

输出。

array([[0.25949648, 0.7053845 , 0.03511902]], dtype=float32)

在使用Keras密集层时,很容易添加softmax激活函数,如下图所示

layer = tf.keras.layers.Dense(32, activation=tf.keras.activations.softmax)

PyTorch中的Softmax函数

在PyTorch中,可以通过使用nn.Softmax()函数来实现Softmax功能,如下例所示。

from torch import nn

m = nn.Softmax(dim=1)
input = torch.tensor([[3.0, 4.0, 1.0]],dtype=torch.float)
#input = torch.randn(1, 3)
output = m(input)
output

输出。

tensor([[0.2595, 0.7054, 0.0351]])

总结

在这篇文章中,我们解释了什么是Softmax激活函数,以及它有哪些特点。我们还介绍了Numpy、Keras、TensorFlow和PyTorch的各种Softmax函数的实际例子。

参考文献-

The postDecoding Softmax Activation Function for Neural Network with Examples in Numpy, Keras, TensorFlow and PyTorchappeared first onMLK - Machine Learning Knowledge.