Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3596178
  • 博文数量: 365
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2522
  • 用 户 组: 普通用户
  • 注册时间: 2019-10-28 13:40
文章分类

全部博文(365)

文章存档

2023年(8)

2022年(130)

2021年(155)

2020年(50)

2019年(22)

我的朋友

分类: Python/Ruby

2021-08-26 17:14:25

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()自然常数ex次方

    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不会出现饱和,在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-ReLUP-ReLU

# 为了改进原本ReLU的硬饱和,和神经元坏死出现了Leaky-ReLUP-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可以作为一个可学习的参数,原文献建议初始化a0.25

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

# plt.subplot(122)

# Fun_show(x, y, "Leaky_ReLU")

# ELU

# 融合了sigmoidReLU,左侧具有软饱和性

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')

阅读(1133) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~