人工神经网络基础:激活函数、权重、偏置与损失函数详解
立即解锁
发布时间: 2025-08-30 00:57:22 阅读量: 3 订阅数: 20 AIGC 

# 人工神经网络基础:激活函数、权重、偏置与损失函数详解
## 1. 激活函数
### 1.1 ReLU函数
ReLU(Rectified Linear Unit)是2000年代后期开始使用的一种激活函数。它简单高效,通过计算最大值实现非线性变换。其线性和非饱和的特性,以及计算效率,使得收敛(即达到低错误率)速度更快。与sigmoid或tanh函数使用的指数运算不同,ReLU使用零矩阵,有时比tanh快达六倍。不过,ReLU存在“死亡神经元”问题,当学习率过大,大梯度与不规则的权重更新导致函数输出梯度为零时,ReLU非线性在训练中可能失效。在TensorFlow中,ReLU可以通过`tf.nn.relu`使用。
### 1.2 现代激活函数方法
- **Leaky ReLU**:为了解决“死亡神经元”问题,Leaky ReLU在ReLU函数中引入了一个小斜率,允许小梯度使单元保持活跃,从而使可能死亡的神经元存活。在TensorFlow中,其函数为`tf.nn.leaky_relu(features, alpha=0.2, name=None)`。
- **Parametric Rectified Linear Unit (PreLU)**:PreLU更进一步,将小梯度作为一个在训练过程中可调整的参数。以下是自定义的PreLU函数代码:
```python
## Parametric ReLu
def PreLu(x):
alpha = tf.get_variable('alpha', x.get_shape()[-1],
initializer=tf.constant_initializer(0.0), dtype=tf.float32)
p_bound = tf.nn.relu(x)
n_bound = alpha * (x - abs(x)) * 0.5
return p_bound + n_bound
```
- **Maxout层**:这不是一个激活函数,而是一个层。Maxout层是传统前馈神经网络的新迭代,使用maxout单元作为激活函数。ReLU和Leaky ReLU现在只是maxout的特殊情况。虽然maxout单元不会饱和并缓解了“死亡神经元”问题,但它使每个神经元的参数数量翻倍,导致参数集增大,计算难度增加。在TensorFlow中,Maxout层可以通过`tf.contrib.layers.maxout(inputs, num_units)`使用,其中`inputs`是输入到maxout层的数据,`num_units`是层的大小。
### 1.3 激活函数选择建议
- 不确定时,使用ReLU(注意控制学习率)。
- 网络中出现死亡神经元时,使用Leaky ReLU或MaxOut。
- Tanh是一个可选方案,但效果不如ReLU、Leaky ReLU或MaxOut。
- 不要使用sigmoid函数。
下面是激活函数选择的流程图:
```mermaid
graph TD
A[选择激活函数] --> B{是否不确定}
B -- 是 --> C[使用ReLU(注意学习率)]
B -- 否 --> D{是否有死亡神经元}
D -- 是 --> E[使用Leaky ReLU或MaxOut]
D -- 否 --> F{是否考虑Tanh}
F -- 是 --> G[谨慎使用,效果可能较差]
F -- 否 --> H[避免使用sigmoid]
```
## 2. 权重和偏置因子
### 2.1 权重和偏置的作用
权重和偏置是人工神经网络的两个关键部分。权重在神经网络的每次变换中应用,用于拉伸函数,本质上改变非线性的陡峭程度。偏置因子则允许我们将激活函数左右移动,以更好地逼近自然函数。
### 2.2 权重和偏置的实践示例
以下是一个简单的Python示例,展示了权重和偏置如何影响函数:
```python
import numpy as np
import matplotlib.pyplot as plt
# 仅使用权重
def single_output(x, w):
return np.tanh(np.dot(x, w))
x = np.arange(-5, 5, .1)
f1 = single_output(x, 0.5)
f2 = single_output(x, 1.0)
f3 = single_output(x, 2.0)
plt.plot(x, f1)
plt.plot(x, f2)
plt.plot(x, f3)
plt.show()
# 使用权重和偏置
def single_output(x, w, b):
return np.tanh(np.dot(x, w) + b)
x = np.arange(-5, 5, .1)
f1 = single_output(x, 1.0, 2.0)
f2 = single_output(x, 1.0, 1.0)
f3 = single_output(x, 1.0, -2.0)
f4 = single_output(x, 1.0, 0.0)
plt.plot(x, f1)
plt.plot(x, f2)
plt.plot(x, f3)
plt.plot(x, f4)
plt.show()
```
### 2.3 MNIST示例中的权重和偏置设置
在MNIST示例中,我们可以根据网络参数设置权重和偏置,代码如下:
```python
import tensorflow as tf
# 假设已定义输入层大小、隐藏层大小和类别数量
input_layer_size = ...
hidden_layer_one = ...
hidden_layeR_two = ...
number_classes = ...
weights = {
'w1': tf.Variable(tf.random_normal([input_layer_size, hidden_layer_one])),
'w2': tf.Variable(tf.random_normal([hidden_layer_one, hidden_layeR_two])),
'w_out': tf.Variable(tf.random_normal([hidden_layer_two, number_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([hidden_layer_one])),
'b2
```
0
0
复制全文
相关推荐










