手推反向传播+numpy实现

简介: 手推反向传播+numpy实现

      反向传播的重要性不必多说,手推也是必备基础,大厂面试要求用numpy实现一下BP也是经常的事。下面以一个简单的两层网络为例(简单到连bias都没有的那种),真·手推反向传播+numpy实现。


说明:


input:输入


net_h:隐层


S(x):sigmoid简写


SD(x):sigmoid导数的简写


out_h:隐层经过sigmoid激活的输出


net_o:输出层


out_o:经过经过sigmoid激活的输出层,也就是最后的输出


target(简写t1、t2):Ground Truth


L:损失函数,一个简单的MSE


gw:L在w的偏导数

2020080208425681.jpg


20200802092257515.jpg




下面是代码:


1.对以上手推图片的实现:

import numpy as np
 
def sigmoid(x):
    return 1 / (1 + np.exp(-x))
def sigmoid_derivationx(y):
    return y * (1 - y)
def back():
    input = np.array([0.9, 0.1], dtype='float')
    weight_1 = np.array([[0.15, 0.20], [0.25, 0.30]], dtype='float')
    weight_2 = np.array([[0.40, 0.45], [0.50, 0.55]], dtype='float')
    target_output = np.array([0.11, 0.89], dtype='float')
    learning_rate = 0.5
    steps = 1000
    while steps > 0:
        steps -= 1
        # 正向传播
        # layer-1
        net_h1, net_h2 = np.dot(input, weight_1)  # 第一层的计算结果
        out_h1, out_h2 = [1 / (1 + np.exp(-net_h1)), 1 / (1 + np.exp(-net_h2))]  # sigmoid激活后的输出
        # layer-2
        layer_2_input = np.array([out_h1, out_h2], dtype='float')
        net_o1, net_o2 = np.dot(layer_2_input, weight_2)  # 第二层的计算结果
        out_o1, out_o2 = [1 / (1 + np.exp(-net_o1)), 1 / (1 + np.exp(-net_o2))]  # sigmoid激活后的输出
        # 计算梯度,反向传播
        total_loss = sum([pow(target_output-real_output, 2)/2 for target_output, real_output in zip(target_output, [out_o1, out_o2])])
        print('网络的输出:step:%d loss=%f out_o1=%f out_o2=%f ' % (steps, total_loss, out_o1, out_o2))
        # gradient for layer-2
        gradient_w5 = -1 * (target_output[0] - out_o1) * out_o1 * (1 - out_o1) * out_h1
        gradient_w6 = -1 * (target_output[0] - out_o1) * out_o1 * (1 - out_o1) * out_h2
        gradient_w7 = -1 * (target_output[1] - out_o2) * out_o2 * (1 - out_o2) * out_h1
        gradient_w8 = -1 * (target_output[1] - out_o2) * out_o2 * (1 - out_o2) * out_h2
 
        # gradient for layer-1
        gradient_w1 = -1 * (target_output[0] - out_o1) * out_o1 * (1 - out_o1) * weight_2[0][0] * out_h1 * \
                      (1 - out_h1)*input[0] - (target_output[1] - out_o2) * out_o2 * (1 - out_o2) * weight_2[1][0] * \
                      out_h1 * (1 - out_h1)*input[0]
 
        gradient_w2 = -1 * (target_output[0] - out_o1) * out_o1 * (1 - out_o1) * weight_2[0][0] * out_h1 * \
                      (1 - out_h1) * input[1] - (target_output[1] - out_o2) * out_o2 * (1 - out_o2) * weight_2[1][0] * \
                      out_h1 * (1 - out_h1)*input[1]
 
        gradient_w3 = -1 * (target_output[0] - out_o1) * out_o1 * (1 - out_o1) * weight_2[0][1] * out_h2 * \
                      (1 - out_h2) * input[0] - (target_output[1] - out_o2) * out_o2 * (1 - out_o2) * weight_2[1][1] * \
                      out_h2 * (1 - out_h2)*input[0]
 
        gradient_w4 = -1 * (target_output[0] - out_o1) * out_o1 * (1 - out_o1) * weight_2[0][1] * out_h2 * \
                      (1 - out_h2) * input[1] - (target_output[1] - out_o2) * out_o2 * (1 - out_o2) * weight_2[1][1] * \
                      out_h2 * (1 - out_h2)*input[1]
 
        # update weight
        # layer -1
        weight_1[0][0] = weight_1[0][0] - learning_rate * gradient_w1
        weight_1[1][0] = weight_1[1][0] - learning_rate * gradient_w2
        weight_1[0][1] = weight_1[0][1] - learning_rate * gradient_w3
        weight_1[1][1] = weight_1[1][1] - learning_rate * gradient_w4
back()

2.用矩阵相乘实现:

import numpy as np
 
def sigmoid(x):
    return 1 / (1 + np.exp(-x))
def sigmoid_derivationx(y):
    return y * (1 - y)
def back_matrix():
    input = np.array([0.9, 0.1], dtype='float')
    weight_1 = np.array([[0.5, 0.5],
                         [0.5, 0.5]], dtype='float')
    weight_2 = np.array([[0.5, 0.5],
                         [0.5, 0.5]], dtype='float')
    target_output = np.array([0.11, 0.89], dtype='float')
    learning_rate = 0.5
    steps = 1000
    while steps > 0:
        steps -= 1
        # 正向传播
        # layer-1
        net_h = np.dot(input, weight_1)  # 第一层的计算结果
        out_h = sigmoid(net_h)  # sigmoid激活后的输出
        # layer-2
        layer_2_input = np.array(out_h, dtype='float')
        net_o = np.dot(layer_2_input, weight_2)  # 第二层的计算结果
        out_o = sigmoid(net_o)  # sigmoid激活后的输出
        # 计算梯度,反向传播
        total_loss = sum([pow(target_output-real_output, 2)/2 for target_output, real_output in zip(target_output, out_o)])
        print('网络的输出:step:%d loss=%f out_o1=%f out_o2=%f ' % (steps, total_loss, out_o[0], out_o[0]))
 
        gradient_weight_2 = np.zeros_like(weight_2)
        for i in range(gradient_weight_2.shape[1]):
            gradient_weight_2[:, i] = (out_o[i] - target_output[i]) * sigmoid_derivationx(out_o[i]) * out_h
 
        gradient_weight_1 = np.zeros_like(weight_1)
        for i in range(gradient_weight_1.shape[1]):
            dot1 = -1 * (target_output - out_o) * out_o * sigmoid_derivationx(out_h)
            dot2 = np.reshape(weight_2[:, i], (-1, 1))
            gradient_weight_1[:, i] = np.dot([dot1], dot2) * input
 
        # update weight
        # layer -1
        weight_1 = weight_1 - learning_rate * gradient_weight_1
 
        # layer-2
        weight_2 = weight_2 - learning_rate * gradient_weight_2
        if steps == 1:
            print('网络的输出:loss=%f out_o1=%f out_o2=%f ' % (total_loss, out_o[0], out_o[1]))
            break
back_matrix()

相关文章
|
2月前
|
人工智能 运维 IDE
Qoder CN是什么?全家桶QoderWork、Qoder CN CLI、QoderWake、Cloud Agents及Mobile介绍
阿里云Qoder CN是面向开发与办公的国产AI智能体全家桶,含Qoder CN(编程)、QoderWork CN(办公)、CLI、QoderWake(数字员工)、Cloud Agents(云端托管)及Mobile六款子产品,全栈支持多模型、高合规、一体化智能协作。(239字)
377 0
|
3月前
|
人工智能 自然语言处理 机器人
2026最新测算:企业建设智能客服系统要多少钱?
2026年智能客服成本逻辑已变:不再仅按坐席计费,而是由订阅、算力、集成、运营四大动态板块构成。大模型推理价降99%,但Agent任务Token消耗激增,导致实际支出不降反升。阿里云瓴羊Quick Service作为代表平台,提供模块化定价与AI Agent闭环能力,助力企业分阶段建设、控本增效。(239字)
|
6月前
|
运维 算法 前端开发
用办公Agent实现智能工单:从客服请求到指派工程师的端到端自动化
本文介绍如何用办公Agent实现智能工单端到端自动化:从用户提问→自动创建/分类→智能派单→通知工程师→闭环反馈,将平均响应时间从47分钟压缩至90秒。详解5步流程、规则+LLM双分类、实时负载+技能匹配派单等核心设计,并分享避坑指南与落地路径。(239字)
873 0
|
机器学习/深度学习 安全 数据安全/隐私保护
Jupyter Notebook本地部署并实现公网远程访问内网Jupyter服务器【内网穿透】
Jupyter Notebook本地部署并实现公网远程访问内网Jupyter服务器【内网穿透】
2557 0
|
Linux iOS开发 MacOS
【MCP教程系列】阿里云百炼MCP全面配置指南:涵盖NPX、UVX、SSE及Streamable HTTP
本文详细介绍如何在阿里云百炼平台及Windows、Linux、MacOS系统中正确配置MCP服务的JSON文件。内容涵盖三种MCP服务配置:npx(基于Stdio)、uvx(Python工具运行)和SSE(服务器发送事件)。同时解析Streamable HTTP作为新一代传输方案的优势与应用,帮助用户掌握每个参数的具体用途及使用方法,解决配置过程中可能遇到的问题,提供完整示例和扩展信息以优化设置体验。
8333 11
|
Ubuntu 开发工具 git
Ubuntu安装homebrew的完整教程
本文介绍了如何在没有公网的情况下安装 Homebrew。首先访问 Homebrew 官网,然后通过阿里云的镜像克隆安装脚本,并创建普通用户进行安装。接着修改 `install.sh` 文件指向国内镜像,执行安装命令。最后配置环境变量并更换 Homebrew 源为国内镜像,确保安装顺利。
6018 50
|
Ubuntu Python
全网最简约的Vscode配置Anaconda环境(百分百成功)
全网最简约的Vscode配置Anaconda环境(百分百成功)
40393 0
全网最简约的Vscode配置Anaconda环境(百分百成功)
|
前端开发
CSS-实现文字描边效果
一、介绍 文字描边分为两种:内外双描边和单外描边,也就是指在给文字加上描边效果后,描边的方向是向内外同时占用文字空间还是只向外扩充文字空间的区别。
|
存储 C语言
【学习笔记】verilog HDL之二:数据类型与表达式
本文介绍了Verilog语言中的常量、变量和表达式。Verilog有四种基本值:0、1、x(未知)和z(高阻)。整型常量有十进制和基数两种格式,实数型常量包括浮点数,字符串常量由双引号括起的字符序列构成。变量分为线网型和寄存器型,线网型包括wire、tri等11种类型,寄存器型有reg、integer、time等,其中reg可声明存储器。表达式中的操作数包括常数、参数、线网等8种类型,操作符包括算术、关系、逻辑等9种类型。
|
Ubuntu Linux Docker
弃用Docker Desktop:在WSL2中玩转Docker之Docker Engine 部署与WSL入门
弃用Docker Desktop:在WSL2中玩转Docker之Docker Engine 部署与WSL入门
28349 4