[chapter 25][PyTorch][激活函数与GPU加速]

前言:

        这里面主要介绍一下常用的激活函数与GPU 加速

目录

  1.      tanH 函数
  2.       sigmoid函数
  3.       relu 函数
  4.       leaky Relu 函数
  5.       tf.nn.selu 扩展型指数线性单元
  6.       GPU 加速
  7.       softplus 激活函数
  8.       numpy 傅里叶变换

一: tanH 函数

   

   定义:

           tanhx =\frac{e^x-e^{-x}}{e^x+e^{-x}}

   应用:

             该激活函数在RNN 模型中应用比较广泛 

     导数:

              

    导数区间:

              [0,1]

# -*- coding: utf-8 -*-
"""
Created on Tue Apr  4 16:45:50 2023

@author: chengxf2
"""

import numpy as np
import torch as t
import matplotlib.pyplot as plt


def activate():
    
    
    x = t.linspace(-5.0, 5.0, 20)

    y = t.tanh(x)
    
    plt.xlabel('x')
    plt.ylabel('tanH')
    plt.plot(x,  y, 'r--',label="tanH")
  
    
    plt.grid(True)
    plt.legend()
  
    print(x)


activate()

二  sigmoid函数

      定义:

              f(x)=\frac{1}{1+e^{-x}}

      应用:

              机器学习classifcation ,多层神经网络应用较少,存在梯度弥散问题

      导数

                f^{'}(x)=f(x)(1-f(x))

      导数区间 

              [0,0.25]

     

# -*- coding: utf-8 -*-
"""
Created on Tue Apr  4 16:45:50 2023

@author: chengxf2
"""

import numpy as np
import torch as t
import matplotlib.pyplot as plt


def activate():
    
    
    x = t.linspace(-5.0, 5.0, 20)

    y = t.sigmoid(x)
    
    plt.xlabel('x')
    plt.ylabel('sigmoid')
    plt.plot(x,  y, 'r--',label="sigmoid")
  
    
    plt.grid(True)
    plt.legend()
  
    print(x)


activate()

三 relu 函数

      relu(x) =max(0,x)

      定义:

        

      应用:

          比较广泛,参考知乎

           第一,采用sigmoid等函数,算激活函数时(指数运算),计算量大,反向传播求误差梯度           时,求导涉及除法,计算量相对大,而采用Relu激活函数,整个过程的计算量节省很多。

          第二,对于深层网络,sigmoid函数反向传播时,很容易就会出现 梯度消失 的情况(在sigmoid接近饱和区时,变换太缓慢,导数趋于0,这种情况会造成信息丢失),从而无法完成深层网络的训练。

           第三,ReLu会使一部分神经元的输出为0,这样就造成了 网络的稀疏性,并且减少了参数的相互依存关系,缓解了过拟合问题的发生。

            第四,relu函数的导数计算更快,程序实现就是一个if-else语句,而sigmoid函数要进行浮点四则运算。

  

  导数:

         f^{'}(x)=\left\{\begin{matrix} 0,x \leq 0\\ 1,x \geq 0 \end{matrix}\right.

   导数区间:

       0 or  1

     

  x = t.linspace(-5.0, 5.0, 20)

    y = t.relu(x)

四 leaky Relu 函数

   修正线性单元(Rectified linear unit,ReLU)是神经网络中最常用的激活函数

    Leaky ReLU 激活函数首次在该论文关于声学模型应用中被提出,

    

  梯度:    

  ReLu 在x<0时候,梯度为0,存在梯度弥散现象。

      leaky ReLu  x<0, 梯度为\alpha

  代码

    torch.nn.LeakyReLU(negative_slope=0.01, inplace=False)

  • negative_slope:x为负数时的需要的一个系数,控制负斜率的角度。默认值:1e-2
  • inplace:可以选择就地执行操作。默认值:False

五: tf.nn.selu 扩展型指数线性单元

        在权重用tf.keras.initializers.lecun_normal初始化前提下能够对神经网络进行自归一化.
不可能出现梯度爆炸或者梯度消失问题。需要和Dropout的变种AlphaDropout一起使用

在这里插入图片描述

 


六  softplus 激活函数

     

 


七  GPU 加速

   首先通过任务管理器查看一下当前的GPU,CPU情况

我的Lenovo T14 有两个GPU0, GPU1(独立显卡)

 

 

 我们开始初始花了一个GPU device,使用了GPU 0

后面把 model, loss, data 陆续放到对应的GPU上进行训练


八 numpy 傅里叶变换

def fft_data(input_data):
    ffts = []
    for block in range(input_data.shape[0]):
        for channel in range(input_data.shape[-1]):
            input_data[block, :, channel] -= input_data[block,:, channel].mean()
            # print data.shape
            ffts.append(np.abs(np.fft.rfft(input_data[block,:,channel])))
    mean_fft = np.stack(ffts).mean(axis=0)
    return mean_fft

def plot_fft(x_axis, data_fft):
    
    plt.plot(x_axis, data_fft, 'tab:red')

    plt.xlabel('Frequency', fontsize=17)
    plt.ylabel('Amplitude', fontsize=17)
    plt.axis(xmin = 5, xmax = 70)
    plt.axis(ymin = 0, ymax = 20)
    plt.tight_layout()
    filename = "fft_plot_class%i.pdf" 
    plt.savefig(filename % (nf), format='PDF', bbox_inches='tight')

 

 

 

 

参考:

六、【TF2】Activation 激活函数_tf activation_feifeiyechuan的博客-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值