Python 深度学习中的激活函数实现及其公式推导

sigmoid函数

公式:       

                      S\left ( x \right )=\frac{1}{1+e^{-x}}

梯度:        

                   \left ( \frac{1}{1+e^{-x}} \right ){}'=S\left ( x \right )\left ( 1-S\left ( x \right ) \right )

tanh函数

公式:

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

梯度:

                  \left (\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}} \right ){}'= 1-Tanh^{2}\left ( x \right )=\frac{2}{1+e^{-2x}}-1 

relu函数

公式:

                   Relu\left ( x \right ) = max\left ( x,0 \right )

梯度:

                  Relu{}'\left ( x \right ) = \left \{ 1 , x>0 ; 0,x<0 \right \}

 

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import setChinese as setCh
setCh.set_ch()

"""sigmoid函数也叫logistics函数 取值范围(0,1)
    它能够将任何实数映射到(0,1)区间上。用来做二分类
    公式:1/(1+exp(-x))"""
class SigmoidActivator(object):
    def sigmoid(self,x):
        return 1.0/(1.0+np.exp(-x))

    def sigmoid_derivative(self,x):
        return self.sigmoid(x)*(1-self.sigmoid(x))

    def sigmoid_graph(self):
        x = np.arange(-8,8,1)
        y = self.sigmoid(x)
        y_derivative = self.sigmoid_derivative(x)
        plt.plot(x,y,'g:')
        plt.plot(x,y_derivative,'r-')
        plt.legend(['sigmoid', 'sigmoid_derivative'])
        plt.show()

class TanhActivator(object):
    def tanh(self,x):
        return 2.0/(1+np.exp(-2*x))-1.0

    def tanh_derivative(self,x):
        return 1-self.tanh(x)*self.tanh(x)

    def tanh_graph(self):
        x = np.arange(-8,8,1)
        y = self.tanh(x)
        y_derivative = self.tanh_derivative(x)
        plt.plot(x,y,'g:')
        plt.plot(x,y_derivative,'r-')
        plt.title("tanh函数及其导数(正反向)")
        plt.legend(['tanh','tanh_dervative'])
        plt.show()


class ReluActivator(object):
    def Relu(self,x):
        return np.maximum(x,0.0)

    def Relu_derivative(self,x):
        return np.where(x>0,1,0)

    def Relu_gragh(self):
        x = np.arange(-8,8,0.1)
        y = self.Relu(x)
        y_derivative = self.Relu_derivative(x)
        plt.plot(x,y,'g:')
        plt.plot(x,y_derivative,'r-')
        plt.title("Relu函数及其导数(正反向)")
        plt.legend(['Relu','Relu_derivative'])
        plt.show()



if __name__ == '__main__':
    x = 3
    sig = SigmoidActivator()
    sig.sigmoid(x)
    sig.sigmoid_derivative(x)
    sig.sigmoid_graph()

    tanh = TanhActivator()
    tanh.tanh(x)
    tanh.tanh_derivative(x)
    tanh.tanh_graph()

    relu = ReluActivator()
    relu.Relu(x)
    relu.Relu_derivative(x)
    relu.Relu_gragh()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值