0
点赞
收藏
分享

微信扫一扫

从基本原理到梯度下降,小白都能看懂的神经网络教程

从基本原理到梯度下降,小白都能看懂的神经网络教程_神经网络

神经元:神经元是神经网络的基本单元,类似于生物体内的神经元。一个神经元接收一些输入,做一个简单的计算,然后产生一个输出。

层:神经网络由多个神经元组成的层组成。输入层接收数据,隐藏层执行一些计算,输出层产生最终的输出。

import numpy as np

def sigmoid(x):
  # Our activation function: f(x) = 1 / (1 + e^(-x))
  return 1 / (1 + np.exp(-x))

class Neuron:
  def __init__(self, weights, bias):
    self.weights = weights
    self.bias = bias

  def feedforward(self, inputs):
    # Weight inputs, add bias, then use the activation function
    total = np.dot(self.weights, inputs) + self.bias
    return sigmoid(total)

weights = np.array([0, 1]) # w1 = 0, w2 = 1
bias = 4                   # b = 4
n = Neuron(weights, bias)

x = np.array([2, 3])       # x1 = 2, x2 = 3
print(n.feedforward(x))    # 0.9990889488055994

import numpy as np

def sigmoid(x):
  # Our activation function: f(x) = 1 / (1 + e^(-x))
  return 1 / (1 + np.exp(-x))

class Neuron:
  def __init__(self, weights, bias):
    self.weights = weights
    self.bias = bias

  def feedforward(self, inputs):
    # Weight inputs, add bias, then use the activation function
    total = np.dot(self.weights, inputs) + self.bias
    return sigmoid(total)

weights = np.array([0, 1]) # w1 = 0, w2 = 1
bias = 4                   # b = 4
n = Neuron(weights, bias)

x = np.array([2, 3])       # x1 = 2, x2 = 3
print(n.feedforward(x))    # 0.9990889488055994

搭建神经网络

从基本原理到梯度下降,小白都能看懂的神经网络教程_损失函数_02

搭建神经网络的过程可以通过一个简单的分类任务来进行说明。假设我们想要构建一个神经网络来识别手写数字,这是一个经典的MNIST数据集任务。以下是搭建神经网络的步骤和案例:

  1. 确定问题类型 我们的问题是手写数字的分类,因此这是一个分类问题。
  2. 准备数据 下载MNIST数据集,它包含了60,000个训练样本和10,000个测试样本。这些样本是28x28像素的灰度图像。
  3. 选择模型架构 对于这个任务,我们可以选择一个简单的多层感知器(MLP)。它包括一个输入层(28x28=784神经元),一个或多个隐藏层,以及一个输出层(10个神经元,对应于10个数字类别)。
  4. 初始化网络 初始化权重和偏置。权重可以是随机的小数值,偏置可以初始化为0。
  5. 选择激活函数 对于隐藏层,我们可以使用ReLU激活函数,对于输出层,我们可以使用Softmax激活函数。
  6. 定义损失函数 对于分类问题,我们通常使用交叉熵损失函数。
  7. 选择优化器 我们可以选择Adam优化器。
  8. 训练网络 使用训练数据训练网络。在每次迭代中,我们向前传播输入数据,计算损失,然后使用反向传播更新权重。
  9. 验证和测试 在独立的验证集和测试集上评估网络的性能。
  10. 调整超参数 根据验证和测试结果,调整超参数,如学习率、批量大小、层数、神经元数量等。
  11. 模型部署 一旦模型在验证集上表现良好,您可以将其部署到生产环境中,用于实际的预测任务。 下面是一个使用Python和Keras库搭建简单神经网络的示例代码:


from keras.datasets import mnist

from keras.models import Sequential

from keras.layers import Dense, Flatten

from keras.optimizers import Adam


# 加载数据

(x_train, y_train), (x_test, y_test) = mnist.load_data()


# 预处理数据

x_train = x_train.reshape(-1, 28 * 28).astype('float32') / 255

x_test = x_test.reshape(-1, 28 * 28).astype('float32') / 255

y_train = keras.utils.to_categorical(y_train, 10)

y_test = keras.utils.to_categorical(y_test, 10)


# 构建模型

model = Sequential()

model.add(Flatten(input_shape=(28, 28)))

model.add(Dense(128, activation='relu'))

model.add(Dense(10, activation='softmax'))


# 编译模型

model.compile(loss='categorical_crossentropy', optimizer=Adam(), metrics=['accuracy'])


# 训练模型

model.fit(x_train, y_train, batch_size=32, epochs=10, validation_split=0.1)


# 评估模型

test_loss, test_acc = model.evaluate(x_test, y_test)

print(f'Test accuracy: {test_acc}')

训练神经网络

假设有一个数据集,包含4个人的身高、体重和性别:

现在我们的目标是训练一个网络,根据体重和身高来推测某人的性别。

为了简便起见,我们将每个人的身高、体重减去一个固定数值,把性别男定义为1、性别女定义为0。

在训练神经网络之前,我们需要有一个标准定义它到底好不好,以便我们进行改进,这就是损失(loss)。

比如用均方误差(MSE)来定义损失:

n是样本的数量,在上面的数据集中是4;
y代表人的性别,男性是1,女性是0;
ytrue是变量的真实值,ypred是变量的预测值。

顾名思义,均方误差就是所有数据方差的平均值,我们不妨就把它定义为损失函数。预测结果越好,损失就越低,训练神经网络就是将损失最小化。

如果上面网络的输出一直是0,也就是预测所有人都是男性,那么损失是:

MSE= 1/4 (1+0+0+1)= 0.5

计算损失函数的代码如下:

import numpy as np

def mse_loss(y_true, y_pred):
  # y_true and y_pred are numpy arrays of the same length.
  return ((y_true - y_pred) ** 2).mean()

y_true = np.array([1, 0, 0, 1])
y_pred = np.array([0, 0, 0, 0])

print(mse_loss(y_true, y_pred)) # 0.5

减少神经网络损失

训练过程:训练神经网络涉及多次前向传播和反向传播。每次迭代后,权重都会更新,使网络逐渐学习数据中的模式。

批量大小:批量大小是一个超参数,用于在每次迭代中指定要一起训练的数据样本数量。较大的批量大小可以提高计算效率,但可能导致梯度消失或爆炸。

预测值是由一系列网络权重和偏置计算出来的:

所以损失函数实际上是包含多个权重、偏置的多元函数:

(注意!前方高能!需要你有一些基本的多元函数微分知识,比如偏导数、链式求导法则。)

如果调整一下w1,损失函数是会变大还是变小?我们需要知道偏导数∂L/∂w1是正是负才能回答这个问题。

根据链式求导法则:

而L=(1-ypred)2,可以求得第一项偏导数:

接下来我们要想办法获得ypred和w1的关系,我们已经知道神经元h1、h2和o1的数学运算规则:

实际上只有神经元h1中包含权重w1,所以我们再次运用链式求导法则:

然后求∂h1/∂w1



我们在上面的计算中遇到了2次激活函数sigmoid的导数f′(x),sigmoid函数的导数很容易求得:

总的链式求导公式:

这种向后计算偏导数的系统称为反向传播(backpropagation)。

上面的数学符号太多,下面我们带入实际数值来计算一下。h1、h2和o1

h1=f(x1⋅w1+x2⋅w2+b1)=0.0474

h2=f(w3⋅x3+w4⋅x4+b2)=0.0474

o1=f(w5⋅h1+w6⋅h2+b3)=f(0.0474+0.0474+0)=f(0.0948)=0.524

神经网络的输出y=0.524,没有显示出强烈的是男(1)是女(0)的证据。现在的预测效果还很不好。

我们再计算一下当前网络的偏导数∂L/∂w1:

这个结果告诉我们:如果增大w1,损失函数L会有一个非常小的增长。

随机梯度下降

下面将使用一种称为随机梯度下降(SGD)的优化算法,来训练网络。

梯度:梯度是一个向量,指向函数增长最快的方向。在神经网络中,梯度指向预测误差增长最快的方向。

梯度下降:梯度下降是一种优化算法,用于根据梯度调整权重。在每次迭代中,权重沿着梯度的反方向更新,从而逐渐减小预测误差。

η是一个常数,称为学习率(learning rate),它决定了我们训练网络速率的快慢。将w1减去η·∂L/∂w1,就等到了新的权重w1。

当∂L/∂w1是正数时,w1会变小;当∂L/∂w1是负数 时,w1会变大。

如果我们用这种方法去逐步改变网络的权重w和偏置b,损失函数会缓慢地降低,从而改进我们的神经网络。

训练流程如下:

1、从数据集中选择一个样本;
2、计算损失函数对所有权重和偏置的偏导数;
3、使用更新公式更新每个权重和偏置;
4、回到第1步。

我们用Python代码实现这个过程:

import numpy as np

def sigmoid(x):
  # Sigmoid activation function: f(x) = 1 / (1 + e^(-x))
  return 1 / (1 + np.exp(-x))

def deriv_sigmoid(x):
  # Derivative of sigmoid: f'(x) = f(x) * (1 - f(x))
  fx = sigmoid(x)
  return fx * (1 - fx)

def mse_loss(y_true, y_pred):
  # y_true and y_pred are numpy arrays of the same length.
  return ((y_true - y_pred) ** 2).mean()

class OurNeuralNetwork:
  '''
  A neural network with:
    - 2 inputs
    - a hidden layer with 2 neurons (h1, h2)
    - an output layer with 1 neuron (o1)

  *** DISCLAIMER ***:
  The code below is intended to be simple and educational, NOT optimal.
  Real neural net code looks nothing like this. DO NOT use this code.
  Instead, read/run it to understand how this specific network works.
  '''
  def __init__(self):
    # Weights
    self.w1 = np.random.normal()
    self.w2 = np.random.normal()
    self.w3 = np.random.normal()
    self.w4 = np.random.normal()
    self.w5 = np.random.normal()
    self.w6 = np.random.normal()

    # Biases
    self.b1 = np.random.normal()
    self.b2 = np.random.normal()
    self.b3 = np.random.normal()

  def feedforward(self, x):
    # x is a numpy array with 2 elements.
    h1 = sigmoid(self.w1 * x[0] + self.w2 * x[1] + self.b1)
    h2 = sigmoid(self.w3 * x[0] + self.w4 * x[1] + self.b2)
    o1 = sigmoid(self.w5 * h1 + self.w6 * h2 + self.b3)
    return o1

  def train(self, data, all_y_trues):
    '''
    - data is a (n x 2) numpy array, n = # of samples in the dataset.
    - all_y_trues is a numpy array with n elements.
      Elements in all_y_trues correspond to those in data.
    '''
    learn_rate = 0.1
    epochs = 1000 # number of times to loop through the entire dataset

    for epoch in range(epochs):
      for x, y_true in zip(data, all_y_trues):
        # --- Do a feedforward (we'll need these values later)
        sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1
        h1 = sigmoid(sum_h1)

        sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2
        h2 = sigmoid(sum_h2)

        sum_o1 = self.w5 * h1 + self.w6 * h2 + self.b3
        o1 = sigmoid(sum_o1)
        y_pred = o1

        # --- Calculate partial derivatives.
        # --- Naming: d_L_d_w1 represents "partial L / partial w1"
        d_L_d_ypred = -2 * (y_true - y_pred)

        # Neuron o1
        d_ypred_d_w5 = h1 * deriv_sigmoid(sum_o1)
        d_ypred_d_w6 = h2 * deriv_sigmoid(sum_o1)
        d_ypred_d_b3 = deriv_sigmoid(sum_o1)

        d_ypred_d_h1 = self.w5 * deriv_sigmoid(sum_o1)
        d_ypred_d_h2 = self.w6 * deriv_sigmoid(sum_o1)

        # Neuron h1
        d_h1_d_w1 = x[0] * deriv_sigmoid(sum_h1)
        d_h1_d_w2 = x[1] * deriv_sigmoid(sum_h1)
        d_h1_d_b1 = deriv_sigmoid(sum_h1)

        # Neuron h2
        d_h2_d_w3 = x[0] * deriv_sigmoid(sum_h2)
        d_h2_d_w4 = x[1] * deriv_sigmoid(sum_h2)
        d_h2_d_b2 = deriv_sigmoid(sum_h2)

        # --- Update weights and biases
        # Neuron h1
        self.w1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1
        self.w2 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2
        self.b1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1

        # Neuron h2
        self.w3 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w3
        self.w4 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w4
        self.b2 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2

        # Neuron o1
        self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5
        self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6
        self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3

      # --- Calculate total loss at the end of each epoch
      if epoch % 10 == 0:
        y_preds = np.apply_along_axis(self.feedforward, 1, data)
        loss = mse_loss(all_y_trues, y_preds)
        print("Epoch %d loss: %.3f" % (epoch, loss))

# Define dataset
data = np.array([
  [-2, -1],  # Alice
  [25, 6],   # Bob
  [17, 4],   # Charlie
  [-15, -6], # Diana
])
all_y_trues = np.array([
  1, # Alice
  0, # Bob
  0, # Charlie
  1, # Diana
])

# Train our neural network!
network = OurNeuralNetwork()
network.train(data, all_y_trues)


举报

相关推荐

0 条评论