深度学习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 仅处理标量。

相关推荐
HeteroCat7 小时前
2026.08杂记-AI 时代个体与组织如何应对变革
人工智能·aigc·创业
微小冷8 小时前
Python图论库NetworkX初步
开发语言·python·图论·graph·networkx·digraph
容器魔方8 小时前
云容器引擎 CCE 2026-Q2 优化升级:AI 推理负载、备份中心、Gateway API能力全新上线!
人工智能·云原生·容器·开源
Aloudata8 小时前
数据治理台账 vs 元数据知识图谱:数据资产如何从文档走向计算化
数据库·人工智能·知识图谱·数据治理·元数据·数据资产·数据血缘
tedcloud1238 小时前
Awesome DSH Plugin 怎么用?给 DeepSeek Harness 搭建自己的插件生态
大数据·linux·服务器·人工智能·音视频
hh9508 小时前
gent Plan × DeepSeek Harness Agent 单元测试与行为回归框架
人工智能·数据挖掘·回归·单元测试·agent plan·adg成都社区·adg社区
楷哥爱开发8 小时前
IPFoxy爬虫代理配置指南:从0搭建Crawl4AI网页爬虫教程
大数据·运维·人工智能·爬虫
JJJennie7778 小时前
【AI 网关】七类网关方案横向测评|MAI Gateway 会带来什么不同
人工智能·大模型·gateway·ai网关·魔芋ai
咖啡星人k8 小时前
2026 多模态大模型:AI 如何“看图+读字+听音“三合一,MonkeyCode 免费上手
人工智能·深度学习·神经网络·计算机视觉·自然语言处理
AI工具测评家8 小时前
AI检测器是怎么判断论文由AI生成的?从文本概率、语言规律到检测模型一次讲清
人工智能·aigc·降重·ai检测·查重·降ai·快降重