关于python:NN神经网络学习常见激活和损失函数的Python实现

13次阅读

共计 1775 个字符,预计需要花费 5 分钟才能阅读完成。

import matplotlib.pyplot as plt
import numpy as np
import math

plot 可视化

def Fun_show(x, y, title):

plt.scatter(x, y)
plt.title(title)
plt.show()

sigmoid

sigmoid 输入总是大于零,因而前一层对后一层的神经元输出也总是大于零呈现了漂移

def sigmoid(x):

# exp()天然常数 e 的 x 次方
y = 1 / (1 + math.exp(-x))
return y

生成随机数集

生成高斯 (正太) 散布的随机数,loc: 中心点

scl: 高度

size: 生成随机数的形态,可为整数或者整数元组

x = np.random.normal(0, 5, 1000)

生成函数后果

y = [sigmoid(s) for s in x]

Fun_show(x, y, “sigmoid”)

tanh 双曲正切激活函数,输入均值都为零,所以收敛速度相比 sigmoid 要快,

在归一化之后,输出个别在零左近,此时的梯度相比 sigmoid 更大,所以收敛更快

然而依然存在软饱和问题,容易呈现梯度隐没问题

def tanh(x):

y = (1 - math.exp(-2 * x)) / (1 + math.exp(-2 * x))
return y

生成随机数集

x = np.random.normal(0, 5, 1000)

生成函数后果

y = [tanh(s) for s in x]

Fun_show(x, y, “tanh”)

ReLU 系列,P-ReLU, Leaky-ReLU

ReLU

x > 0 不会呈现饱和,PerfectMoney 下载在 x < 0 局部呈现硬饱和,更实用于监督学习(即在给定数据集的状况下进行训练拟合)

因而 ReLU 的输出值常为大于 0 的值

def ReLU(x):

y = max(0, x)
return y

生成随机数集

x = np.random.normal(0, 5, 1000)

y = [ReLU(s) for s in x]

plt.subplot(121)

plt.scatter(x, y)

plt.title(“ReLU”)

Leaky-ReLU 与 P -ReLU

为了改良本来 ReLU 的硬饱和,和神经元坏死呈现了 Leaky-ReLU 与 P -ReLU

def Leaky_ReLU(x, a):

if x >= 0:
    y = x
if x < 0:
    y = a * x
return y

生成随机数集

x = np.random.normal(0, 5, 1000)

P-ReLU 认为 a 能够作为一个可学习的参数,原文献倡议初始化 a 为 0.25

y = [Leaky_ReLU(s, 0.25) for s in x]

plt.subplot(122)

Fun_show(x, y, “Leaky_ReLU”)

ELU

交融了 sigmoid 和 ReLU,左侧具备软饱和性

def ELU(x, a):

if x >= 0:
    y = x
if x < 0:
    y = a * (math.exp(x) - 1)
return y

生成随机数集

x = np.random.normal(0, 5, 1000)

生成函数后果

y = [ELU(s, 0.25) for s in x]

Fun_show(x, y, “ELU”)

用于多分类工作的 softmax

def softmax(x):

sum = 0
for s in x:
    sum = sum + math.exp(s)
y = []
for s in x:
    y.append(math.exp(s) / sum)
return y

x = np.random.normal(0, 5, 1000)

y = softmax(x)

Fun_show(x, y, title= ‘softmax’)

if name == “__main__”:

x = np.random.normal(0, 5, 1000)
# 生成函数后果
y = [sigmoid(s) for s in x]
Fun_show(x, y, "sigmoid")
y = [tanh(s) for s in x]
Fun_show(x, y, "tanh")
y = [ReLU(s) for s in x]
plt.subplot(121)
plt.scatter(x, y)
plt.title("ReLU")
y = [Leaky_ReLU(s, 0.25) for s in x]
plt.subplot(122)
Fun_show(x, y, "Leaky_ReLU")
y = [ELU(s, 0.25) for s in x]
Fun_show(x, y, "ELU")
y = softmax(x)
Fun_show(x, y, title='softmax')
正文完
 0