Python绘制神经网络中常见激活函数的图形

前言

需要绘制的激活函数有sigmoidtanhReLUsoftplusswish共5个函数。

各个函数的公式

sigmoid:
在这里插入图片描述
tanh:
在这里插入图片描述
ReLU:
在这里插入图片描述

softplus:
在这里插入图片描述
swish:
在这里插入图片描述
其中 𝜎(⋅) 为 Logistic 函数, β为可学习的参数或一个固定超参数

上面5个激活函数对应的代码公式如下:

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def tanh(x):
    return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) 

def relu(x):
    return np.maximum(0, x)

def softplus(x):
    return np.log(1 + np.exp(x))

def swish(x, beta):
    return x * sigmoid(beta * x)

开始绘图

此处我们使用matplotlib来绘图,由于matplotlib默认的坐标系不是直角坐标系,需要写一个函数来获取直角坐标系,并在直角坐标系上绘图。

下面的代码可以获取直角坐标系的ax,此后便可以通过ax.plot等操作在ax上面绘图。

def get_central_ax():
    ax = plt.gca() # get current axis 获得坐标轴对象
	
	# 将右边 上边的两条边颜色设置为空 其实就相当于抹掉这两条边
    ax.spines['right'].set_color('none') 
    ax.spines['top'].set_color('none') 

	# 指定下边的边作为 x 轴 指定左边的边为 y 轴
    ax.xaxis.set_ticks_position('bottom') 
    ax.yaxis.set_ticks_position('left') 
    
    ax.spines['bottom'].set_position(('data', 0)) #指定 data 设置的bottom(也就是指定的x轴)绑定到y轴的0这个点上
    ax.spines['left'].set_position(('data', 0))
    
    return ax

下面是绘制sigmoidtanhReLUsoftplus的代码,swish的图像需要单独绘制:

x = np.arange(-6.0, 6.0, 0.1)
y1 = sigmoid(x)
y2 = tanh(x)
y3 = relu(x)
y4 = softplus(x)

ax = get_central_ax()

# ax = plt.subplot(111)
ax.plot(x, y1)
ax.plot(x, y2, linestyle='--')
ax.plot(x, y3, linestyle='--')
ax.plot(x, y4, linestyle='--')
ax.legend(['sigmoid', 'tanh', 'ReLU', 'softplus'])
plt.show()

绘制的图像如下:
在这里插入图片描述

下面是绘制swish函数图像的代码:

x = np.arange(-6.0, 6.0, 0.1)
ax = get_central_ax() 

legends = []
for beta in [0, 0.5, 1, 100]:
    y_s = swish(x, beta)
    ax.plot(x, y_s, linestyle='--')
    legends.append('β = '+str(beta))

ax.legend(legends)
plt.show()

图形如下:
在这里插入图片描述

完整代码

import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
    return 1 / (1 + np.exp(-x))
def tanh(x):
    return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x)) 

def relu(x):
    return np.maximum(0, x)
def softplus(x):
    return np.log(1 + np.exp(x))
def swish(x, beta):
    return x * sigmoid(beta * x)

def get_central_ax():
    ax = plt.gca() # get current axis 获得坐标轴对象

    ax.spines['right'].set_color('none') 
    ax.spines['top'].set_color('none')

    ax.xaxis.set_ticks_position('bottom') 
    ax.yaxis.set_ticks_position('left') 
    ax.spines['bottom'].set_position(('data', 0))
    ax.spines['left'].set_position(('data', 0))
    
    return ax

# 绘制`sigmoid`,`tanh`,`ReLU`,`softplus`
x = np.arange(-6.0, 6.0, 0.1)
y1 = sigmoid(x)
y2 = tanh(x)
y3 = relu(x)
y4 = softplus(x)

ax = get_central_ax()

# ax = plt.subplot(111)
ax.plot(x, y1)
ax.plot(x, y2, linestyle='--')
ax.plot(x, y3, linestyle='--')
ax.plot(x, y4, linestyle='--')
ax.legend(['sigmoid', 'tanh', 'ReLU', 'softplus'])
plt.show()

# 绘制`swish`函数
x = np.arange(-6.0, 6.0, 0.1)
ax = get_central_ax() 

legends = []
for beta in [0, 0.5, 1, 100]:
    y_s = swish(x, beta)
    ax.plot(x, y_s, linestyle='--')
    legends.append('β = '+str(beta))

ax.legend(legends)
plt.show()
  • 5
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用python实现前馈神经网络近似连续函数的示例代码: ```python import numpy as np import matplotlib.pyplot as plt # 定义输入数据 x = np.linspace(-10, 10, 1000) y = np.sin(x) # 定义神经网络 class NeuralNetwork: def __init__(self): # 随机生成权重和偏置 self.weights1 = np.random.randn(1, 10) self.bias1 = np.random.randn(1, 10) self.weights2 = np.random.randn(10, 1) self.bias2 = np.random.randn(1, 1) def forward(self, x): # 前向传播 self.layer1 = np.dot(x, self.weights1) + self.bias1 self.activation1 = np.tanh(self.layer1) self.layer2 = np.dot(self.activation1, self.weights2) + self.bias2 self.activation2 = self.layer2 return self.activation2 def backward(self, x, y, output, learning_rate): # 反向传播 error = output - y d_layer2 = error d_weights2 = np.dot(self.activation1.T, d_layer2) d_bias2 = np.sum(d_layer2, axis=0, keepdims=True) d_activation1 = np.dot(d_layer2, self.weights2.T) d_layer1 = d_activation1 * (1 - np.power(self.activation1, 2)) d_weights1 = np.dot(x.T, d_layer1) d_bias1 = np.sum(d_layer1, axis=0, keepdims=True) # 更新权重和偏置 self.weights1 -= learning_rate * d_weights1 self.bias1 -= learning_rate * d_bias1 self.weights2 -= learning_rate * d_weights2 self.bias2 -= learning_rate * d_bias2 def train(self, x, y, learning_rate=0.1, epochs=1000): # 训练神经网络 for i in range(epochs): output = self.forward(x) self.backward(x, y, output, learning_rate) if i % 100 == 0: loss = np.mean(np.square(output - y)) print("Epoch:", i, "Loss:", loss) # 创建神经网络实例 nn = NeuralNetwork() # 训练神经网络 nn.train(x.reshape(-1, 1), y.reshape(-1, 1)) # 绘制原始数据和神经网络预测结果的比较图 plt.plot(x, y, label="Ground Truth") plt.plot(x, nn.forward(x.reshape(-1, 1)).flatten(), label="Neural Network") plt.legend() plt.show() ``` 上述代码首先定义了输入数据 `x` 和 `y`,其 `y` 是 `x` 的正弦函数值。然后定义了一个名为 `NeuralNetwork` 的神经网络类,包含了前向传播、反向传播和训练方法。在训练方法,通过循环迭代来更新权重和偏置,最终得到神经网络模型。最后,将原始数据和神经网络预测结果的比较图绘制出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值