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

相关推荐
会周易的程序员4 分钟前
唯识学架构的AI:Agent个体意识与佛陀出现可能性的推演
人工智能
卡梅德生物科技小能手4 分钟前
卡梅德生物科普 TNFSF4(肿瘤坏死因子超家族成员 4)
经验分享·深度学习·生活
weixin_7275356221 分钟前
Loop 已死,Graph 新生:AI 工作流的范式革命
android·人工智能·rxjava
tqs_1234529 分钟前
Agent智能体+Skill插件引擎+Milvus混合检索 技术沉淀
java·python·milvus
abcefg_h33 分钟前
Agent Skill 体系全解:从渐进式披露到生产级管控
人工智能·microsoft
KaneLogger34 分钟前
一套系统,让 AI 写代码的速度变成生产力
人工智能·程序员·代码规范
眼泪划过的星空42 分钟前
LangChain 两大基础提示词模板:PromptTemplate 与 ChatPromptTemplate 详解
人工智能·python·langchain
狗都不学爬虫_43 分钟前
AI逆向 - 99aq中心滑块验证+登录(wasm纯算)
爬虫·python·网络爬虫
小码哥哥1 小时前
如何评价“构建企业级 AI 知识库“这一趋势?从技术架构到落地实践的完整分析
人工智能·架构
小罗水1 小时前
第18章 接口回归、异常演练与轻量压测
人工智能·数据挖掘·回归