深度学习3.1 线性回归

3.1.1 线性回归的基本概念

损失函数

梯度下降

3.1.2 向量化加速

python 复制代码
%matplotlib inline
import math
import time
import numpy as np
import torch
from d2l import torch as d2l

n = 1000000 #本机为了差距明显,选择数据较大,运行时间较长,可选择10000
a = torch.ones(n)
b = torch.ones(n)


class Timer:
    def __init__(self):
        self.times = []  # 存储每次测量的时间
        self.start()      # 初始化时自动开始计时

    def start(self):
        self.tik = time.time()  # 记录当前时间戳(开始时间)

    def stop(self):
        self.times.append(time.time() - self.tik)  # 计算并保存时间差
        return self.times[-1]  # 返回本次测量的时间

    def avg(self):
        return sum(self.times) / len(self.times)  # 平均耗时

    def sum(self):
        return sum(self.times)  # 总耗时

    def cumsum(self):
        return np.array(self.times).cumsum().tolist()  # 累计耗时(用于绘图)
python 复制代码
c = torch.zeros(n)      # 初始化全0张量 c(存储结果)
timer = Timer()         # 创建计时器实例
for i in range(n):
    c[i] = a[i] + b[i]  # 逐个元素相加(慢!)
print(f'{timer.stop():.5f} sec')

'19.59485 sec'

python 复制代码
timer.start()
d = a + b
f'{timer.stop():.5f} sec'

'0.00470 sec'

3.1.3 正态分布与平方损失

python 复制代码
import math
import numpy as np
from d2l import torch as d2l

def normal(x, mu, sigma):
    p = 1 / math.sqrt(2 * math.pi * sigma ** 2)  # 归一化系数
    return p * np.exp(-0.5 / sigma ** 2 * (x - mu) ** 2)  # 概率密度计算

x = np.arange(-7, 7, 0.01)  # 生成 [-7, 7) 区间内步长0.01的数组
params = [(0, 1), (0, 2), (3, 1)]  # (mu, sigma) 的组合 (均值, 标准差)

d2l.plot(
    x,  # x 轴数据
    [normal(x, mu, sigma) for mu, sigma in params],  # y 轴数据列表(三条曲线)
    xlabel='x',  # x 轴标签
    ylabel='p(x)',  # y 轴标签
    figsize=(4.5, 2.5),  # 图像尺寸(宽,高)
    legend=[f'mean {mu}, std {sigma}' for mu, sigma in params]  # 图例说明
)


x 是 NumPy 数组,np.exp 支持数组运算,而 math.exp 仅处理标量。

相关推荐
大刚测试开发实战9 小时前
TestHub V0.2.2版本发布,附更新指南
人工智能
冬奇Lab10 小时前
Agent 系列(21):Harness 测试工程——45 个测试怎么设计,以及它发现了什么 bug
人工智能·llm·agent
冬奇Lab10 小时前
每日一个开源项目(第133篇):EchoBird - 把 AI 工具的安装和部署做成傻瓜操作
人工智能·开源·资讯
程序员龙叔11 小时前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
IT_陈寒12 小时前
Redis的SETNX并发问题让我加了三天班
前端·人工智能·后端
用户51914958484513 小时前
Windows 渗透测试载荷加载器 POC 工具集
人工智能·aigc
大树8813 小时前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
用户83562907805113 小时前
使用 Python 操作 Word 内容控件
后端·python
通信小呆呆13 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
施小赞13 小时前
普通 RAG vs GraphRAG 核心对比
人工智能·ai