Easy Deep Learning——激活函数

激活函数在神经网络中起到关键作用,通过引入非线性,帮助网络识别复杂模式。常见的激活函数包括ReLU、Sigmoid和Tanh,各有优缺点。本文介绍了这些函数的概念,并提供了PyTorch中的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

激活函数是什么?什么神经网络需要激活函数?它的作用是什么?

假设你是一位魔术师,你手里有一个魔法盒子,盒子里面有很多彩色的球。你想要从盒子里面找到所有红色的球,然后将它们放到一个特殊的盒子里。

你开始一个个地从魔法盒子中取出球,然后仔细地检查它们的颜色。如果是红色的球,你就放到特殊的盒子里;如果不是,你就把它放回原来的魔法盒子里,继续找下一个球。

但是你很快发现,这种方法效率非常低。你需要一个更快、更有效的方法来找到所有的红色球。于是你开始思考:有没有一种方法,可以在一次性地查看所有的球之后,直接找到所有的红色球呢?


你想了很久,最终想到了一个办法。你把所有的球都放到一个大盒子里,然后用一个特殊的滤网过滤掉所有不是红色的球,只留下红色的球。这样一来,你就能够一次性地找到所有的红色球了。

激活函数就像是魔法盒子中的滤网一样,可以帮助神经网络找到特定的模式。激活函数通过引入非线性,让神经网络能够识别更为复杂的模式,从而找到特定的目标。激活函数的作用就像是滤网一样,可以帮助神经网络快速、准确地找到我们需要的模式,提高神经网络的性能。 

激活函数(Activation Function)是神经网络中一种非线性的函数,用于将输入信号映射到输出信号。激活函数的作用是增加神经网络的表达能力,使神经网络能够处理非线性的数据。

激活函数对应神经网络有以下作用:

  1. 引入非线性:激活函数通过引入非线性,使得神经网络能够拟合更为复杂的模型。如果没有激活函数,神经网络将退化为线性模型,无法处理非线性数据。

  2. 改善模型输出:激活函数可以将神经网络的输出值映射到一个特定的范围内,例如0到1或-1到1。这种映射可以使神经网络的输出更容易理解和解释。

  3. 防止梯度消失:在反向传播过程中,如果激活函数的导数很小,梯度就会消失,导致神经网络无法更新权重。一些特殊的激活函数,如ReLU(Rectified Linear Unit)和其变种,具有较大的导数,可以避免梯度消失的问题。

常见的激活函数包括Sigmoid函数、Tanh函数、ReLU函数、LeakyReLU函数等。不同的激活函数在不同的场景下表现不同,选择合适的激活函数可以提高神经网络的性能。

Pytorch中常见的激活函数介绍

  1. ReLU(Rectified Linear Unit):是目前使用最广泛的激活函数之一,它将小于零的值设为零,大于零的值不变。可以通过 torch.nn.ReLU() 来使用。

  2. Sigmoid:将实数映射到区间 (0,1) 内,对于二分类问题非常有用。可以通过 torch.nn.Sigmoid() 来使用。

  3. Tanh:将实数映射到区间 (-1,1) 内,比 Sigmoid 函数的输出范围更广。可以通过 torch.nn.Tanh() 来使用。

  4. Softmax:主要用于多分类问题,将实数映射到 (0,1) 区间内的概率值,且所有输出的概率和为1。可以通过 torch.nn.Softmax() 来使用。

 以下使用pytorch的API 来实现这四种函数,代码如下

import  torch
import  torch.nn as nn
import matplotlib.pyplot as plt
import numpy
x = torch.linspace(-6,6,100)
sigmod = nn.Sigmoid()  ##Sigmod激活函数
ysigmod = sigmod(x)

tanh = nn.Tanh() ##Tanh激活函数
ytanh = tanh(x)

relu = nn.ReLU() ##ReLU激活函数
yrelu = relu(x)

softmax = nn.Softmax() ##Softmax函数
ysoftmax = softmax(x)

plt.figure(figsize=(14,3))

plt.subplot(1,4,1)
plt.plot(x.data.numpy(),ysigmod.data.numpy(),"r-")
plt.title('sigmod')
plt.grid()

plt.subplot(1,4,2)
plt.plot(x.data.numpy(),yrelu.data.numpy(),"r-")
plt.title('relu')
plt.grid()



plt.subplot(1,4,3)
plt.plot(x.data.numpy(), ysoftmax.data.numpy(), "r-")
plt.title('softplus')
plt.grid()

plt.subplot(1,4,4)
plt.plot(x.data.numpy(),ytanh.data.numpy(),"r-")
plt.title('tanh')
plt.grid()
plt.show()

  

### Triplet Loss Function in Deep Learning In the context of deep learning, **Triplet Loss** is a specific type of loss function designed to capture relationships between data points by comparing an anchor point with both positive and negative examples. This approach aims at ensuring that similar items are closer together while dissimilar ones remain further apart within the feature space. The formal definition involves three elements: an _anchor_, a _positive_ example (similar to the anchor), and a _negative_ example (dissimilar from the anchor). The goal is to minimize the distance between the anchor and its corresponding positive sample while maximizing the separation from any given negative instance[^2]. Mathematically, this can be expressed as follows: For each triplet $(a_i, p_i, n_i)$p_i$, and $ represent the anchor, positive, and negative samples respectively, the objective becomes minimizing the following expression: \[ L_{i}=\left[\|f(a_i)-f(p_i)\|^2-\|f(a_i)-f(n_i)\|^2+\alpha \right]^{+} \] Here $\|\cdot\|$ denotes Euclidean norm or L2-distance; $\alpha>0$ represents margin parameter which controls how far apart we want our pairs to stay even after optimization converges[^3]. When implementing such functionality using Python alongside TensorFlow/Keras libraries one might write code like so: ```python import tensorflow as tf def triplet_loss(y_true, y_pred, alpha=0.2): """ Implementation of the triplet loss function Arguments: y_true -- true labels, required when you define a loss in Keras, not used here. y_pred -- python list containing three objects: anchor -- the encodings for the anchor images, shape (None, embedding_size) positive -- the encodings for the positive images, shape (None, embedding_size) negative -- the encodings for the negative images, shape (None, embedding_size) Returns: loss -- real number, value of the loss """ total_lenght = y_pred.shape.as_list()[-1] anchor = y_pred[:,0:int(total_lenght*1/3)] positive = y_pred[:,int(total_lenght*1/3):int(total_lenght*2/3)] negative = y_pred[:,int(total_lenght*2/3):int(total_lenght)+1] # Compute distances between embeddings pos_dist = tf.reduce_sum(tf.square(anchor - positive), axis=-1) neg_dist = tf.reduce_sum(tf.square(anchor - negative), axis=-1) basic_loss = pos_dist - neg_dist + alpha loss = tf.maximum(basic_loss, 0.0) return tf.reduce_mean(loss) ``` This implementation ensures easy integration into neural network architectures built on top of popular frameworks without requiring significant modifications elsewhere in your pipeline[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员陈子青

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值