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

相关推荐
恋猫de小郭2 分钟前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
是一碗螺丝粉23 分钟前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain
两万五千个小时31 分钟前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
用户48159301959132 分钟前
揭秘GPT-4与LLaMA背后的加速黑科技:KV Cache、MQA、GQA、稀疏注意力与MoE全解析
人工智能
用户51914958484533 分钟前
Cisco SMA 暴露面检测工具 - 快速识别CVE-2025-20393风险
人工智能·aigc
碳基沙盒39 分钟前
AI工具的“超级外挂”:从零手把手教你搭建私人 MCP 服务器
人工智能
马腾化云东40 分钟前
Agent开发应知应会(langfuse):Langfuse Score概念详解和实战应用
人工智能·llm·ai编程
Baihai_IDP1 小时前
HackerNews 热榜第一名:AGI 的 A,原来代表的是 Ads(广告)
人工智能·程序员·llm
ma_king1 小时前
claude+tmux 团队模式使用
人工智能·claude
CoovallyAIHub1 小时前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉