人工智能算法工程师(中级)课程8-PyTorch神经网络之神经网络基础与代码详解

大家好,我是微学AI,今天给大家介绍一下人工智能算法工程师(中级)课程8-PyTorch神经网络之神经网络基础与代码详解。神经网络是一种模仿人脑神经元连接方式的计算模型,广泛应用于图像识别、自然语言处理等领域。本文将介绍神经网络的概念、结构、样本、训练和评估,并配合完整的可运行代码。

神经网络基础与代码详解

1. 神经网络的概念

神经网络由大量的节点(或称为神经元)和连接这些节点的边组成。每个节点代表一个神经元,每个边代表神经元之间的连接。神经网络的主要作用是通过对输入数据进行加权求和和非线性变换,提取出数据中的有用信息。

2. 神经网络的结构

神经网络通常分为输入层、隐藏层和输出层。输入层接收外部数据,隐藏层对数据进行加工处理,输出层输出最终结果。每一层的节点都与下一层的节点相连,每个连接都有相应的权重。

2.1 神经网络计算公式

神经网络的输出可以通过以下公式计算:
a ( l ) = f ( z ( l ) ) a^{(l)} = f(z^{(l)}) a(l)=f(z(l))
z ( l ) = w ( l ) a ( l − 1 ) + b ( l ) z^{(l)} = w^{(l)}a^{(l-1)} + b^{(l)} z(l)=w(l)a(l1)+b(l)
其中, a ( l ) a^{(l)} a(l) 表示第 l l l 层的输出, z ( l ) z^{(l)} z(l) 表示第 l l l 层的加权求和结果, w ( l ) w^{(l)} w(l) b ( l ) b^{(l)} b(l) 分别表示第 l l l 层的权重和偏置, f ( ⋅ ) f(\cdot) f() 表示激活函数。
在这里插入图片描述

2.2 可运行代码

下面是一个简单的神经网络结构示例:

import numpy as np
def sigmoid(x):
    return 1 / (1 + np.exp(-x))
def feedforward(X, weights, biases):
    a = X
    for w, b in zip(weights, biases):
        z = np.dot(a, w) + b
        a = sigmoid(z)
    return a
# 定义输入数据
X = np.array([[1, 2], [3, 4]])
# 定义权重和偏置
weights = [np.array([[0.1, 0.2], [0.3, 0.4]]), np.array([[0.5], [0.6]])]
biases = [np.array([0.1, 0.2]), np.array([0.3])]
# 计算输出
output = feedforward(X, weights, biases)
print(output)

3. 神经网络的样本

神经网络的样本包括输入数据和相应的标签。在训练过程中,神经网络通过不断调整权重和偏置,使得输出尽可能接近标签。

3.1 损失函数

神经网络的训练目标是最小化损失函数,常用的损失函数有均方误差(MSE)和交叉熵损失。均方误差的公式如下:
J ( w , b ) = 1 2 m ∑ i = 1 m ( y ( i ) − a ( i ) ) 2 J(w, b) = \frac{1}{2m}\sum_{i=1}^{m}(y^{(i)} - a^{(i)})^2 J(w,b)=2m1i=1m(y(i)a(i))2
其中, m m m 表示样本数量, y ( i ) y^{(i)} y(i) a ( i ) a^{(i)} a(i) 分别表示第 i i i 个样本的标签和预测值。

3.2 可运行代码

下面是一个简单的样本生成和损失计算示例:

import numpy as np
def mse_loss(y_true, y_pred):
    return np.mean((y_true - y_pred) ** 2)
# 定义标签
y_true = np.array([[1], [0]])
# 计算损失
loss = mse_loss(y_true, output)
print(loss)

4. 神经网络的训练

神经网络的训练过程包括前向传播和反向传播。前向传播计算神经网络的输出,反向传播计算损失函数关于权重和偏置的梯度,并更新权重和偏置。

4.1 反向传播

反向传播算法通过链式法则计算梯度。对于第 l l l 层的权重 w ( l ) w^{(l)} w(l),其梯度可以表示为:
∂ J ∂ w ( l ) = a ( l − 1 ) ⋅ ( f ′ ( z ( l ) ) ⋅ δ ( l ) ) \frac{\partial J}{\partial w^{(l)}} = a^{(l-1)} \cdot (f'(z^{(l)}) \cdot \delta^{(l)}) w(l)J=a(l1)(f(z(l))δ(l))
其中, δ ( l ) \delta^{(l)} δ(l) 表示第 l l l 层的误差, f ′ ( ⋅ ) f'(\cdot) f() 表示激活函数的导数。

4.2 神经网络训练的代码

下面是一个简单的神经网络训练示例:

import numpy as np
def sigmoid_derivative(x):
    return sigmoid(x) * (1 - sigmoid(x))
def backpropagation(X, y_true, weights, biases):
    gradients_w = [np.zeros(w.shape) for w in weights]
    gradients_b = [np.zeros(b.shape) for b in biases]
    # 前向传播
    a = X
    activations = [a]
    zs = []
    for w, b in zip(weights, biases):
        z = np.dot(a, w) + b
        zs.append(z)
        a = sigmoid(z)
        activations.append(a)
    # 计算输出层误差
    delta = activations[-1] - y_true
    gradients_b[-1] = delta
    gradients_w[-1] = np.dot(activations[-2].T, delta)
    # 反向传播
    for l in range(2, len(weights) + 1):
        z = zs[-l]
        sp = sigmoid_derivative(z)
        delta = np.dot(delta, weights[-l + 1].T) * sp
        gradients_b[-l] = delta
        gradients_w[-l] = np.dot(activations[-l - 1].T, delta)
    return gradients_w, gradients_b
# 定义学习率
learning_rate = 0.1
# 进行一次梯度下降
gradients_w, gradients_b = backpropagation(X, y_true, weights, biases)
# 更新权重和偏置
for w, grad_w in zip(weights, gradients_w):
    w -= learning_rate * grad_w
for b, grad_b in zip(biases, gradients_b):
    b -= learning_rate * grad_b

5. 神经网络的评估

神经网络的评估通常通过计算测试集上的准确率或者损失函数值来完成。准确率是指模型正确预测的样本数与总样本数之比。

5.1 准确率

准确率的计算公式如下:
Accuracy = Number of correct predictions Total number of predictions \text{Accuracy} = \frac{\text{Number of correct predictions}}{\text{Total number of predictions}} Accuracy=Total number of predictionsNumber of correct predictions

5.2 代码实现

下面是一个简单的神经网络评估示例:

def predict(X, weights, biases):
    a = X
    for w, b in zip(weights, biases):
        z = np.dot(a, w) + b
        a = sigmoid(z)
    return np.round(a)
# 定义测试数据
X_test = np.array([[2, 3], [4, 5]])
# 进行预测
predictions = predict(X_test, weights, biases)
print(predictions)
# 计算准确率
y_test = np.array([[1], [0]])
accuracy = np.mean(predictions == y_test)
print("Accuracy:", accuracy)

总结

本文我们实现了一个简单的神经网络,包括前向传播、反向传播、梯度下降和评估过程。这个网络虽然简单,但是它展示了神经网络的基本原理和实现方法。在实际应用中,神经网络的结构会更加复杂,涉及更多的层和节点,以及更高级的优化算法和正则化技术。此外,现代深度学习框架(如TensorFlow和PyTorch)提供了更高效的实现和自动微分功能,使得神经网络的构建和训练更加便捷。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 12:36:01       53 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 12:36:01       55 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 12:36:01       46 阅读
  4. Python语言-面向对象

    2024-07-12 12:36:01       56 阅读

热门阅读

  1. linux,docker,k8s常见命令

    2024-07-12 12:36:01       19 阅读
  2. TensorFlow 和 PyTorch 显示模型参数方法详解

    2024-07-12 12:36:01       18 阅读
  3. 【go学习合集】进阶数据类型2 -------->切片

    2024-07-12 12:36:01       16 阅读
  4. 扩展欧几里得c++

    2024-07-12 12:36:01       22 阅读
  5. elementui的table的@selection-change阻止事件改变

    2024-07-12 12:36:01       19 阅读
  6. 介绍5款.NET开源、功能强大的Windows桌面工具箱

    2024-07-12 12:36:01       14 阅读
  7. tp计算距离,筛选0-10km距离内商家

    2024-07-12 12:36:01       22 阅读
  8. n3.平滑升级和回滚

    2024-07-12 12:36:01       15 阅读
  9. 有了HTTP,为什么还需要HTTPS?

    2024-07-12 12:36:01       26 阅读
  10. k8s中Service暴露的种类以及用法

    2024-07-12 12:36:01       20 阅读
  11. SchedulerLock分布式定时任务锁

    2024-07-12 12:36:01       20 阅读