深度学习3.2 线性回归的从零开始实现

3.2.1 生成数据集

python 复制代码
%matplotlib inline
import random
import torch
from d2l import torch as d2l

def synthetic_data(w, b, num_examples):
    # 生成特征矩阵X,形状为(num_examples, len(w)),符合标准正态分布
    X = torch.normal(0, 1, (num_examples, len(w)))
    # 计算标签y = Xw + b
    y = torch.matmul(X, w) + b
    # 添加均值为0、标准差为0.01的噪声
    y += torch.normal(0, 0.01, y.shape)
    # 将y转换为列向量(形状:num_examples × 1)
    return X, y.reshape((-1, 1))
python 复制代码
true_w = torch.tensor([2, -3.4])  # 定义真实权重
true_b = 4.2                      # 定义真实偏置
features, labels = synthetic_data(true_w, true_b, 1000)  # 生成1000个样本

d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(), labels.detach().numpy(), 1)

features:, 1: 选取所有样本的第二个特征(索引为1的列)。

3.2.1 读取数据集

python 复制代码
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))

    random.shuffle(indices)
    for i in range(0, num_examples, batch_size):
        batch_indices = torch.tensor(
            indices[i: min(i + batch_size, num_examples)])
        yield features[batch_indices], labels[batch_indices]

batch_size = 10
for X, y in data_iter(batch_size, features, labels):
    print(X, '\n', y)
    break

tensor(\[ 1.6556, 0.1851,

-1.4880, 0.0684,

1.0536, 0.9818,

-0.7794, -1.9199,

-0.3383, 0.2244,

-0.2260, 3.1530,

-2.3626, 1.1877,

-0.3301, 0.1781,

-0.6136, -1.2974,

-0.3397, -0.2088])

tensor(\[ 6.8888,

0.9887,

2.9757,

9.1748,

2.7541,

-6.9671,

-4.5522,

2.9436,

7.3728,

4.2270])

相关推荐
RS迷途小书童几秒前
Python+FFmpeg提取大疆无人机MP4内嵌mov_text遥测SRT字幕并做完整性校验
python·ffmpeg·大疆·srt字幕·dji
workflower1 分钟前
AI 产业链带动效应加速,催生AI 原生企业
人工智能·机器学习·机器人·云计算·无人机
骑着蜗牛撵大象3272 分钟前
大模型工程化实战(十七):金融级 AI 落地——决策可追溯/可复现/可追责/不可抵赖这四件事怎么做
人工智能·金融·哈希·大模型工程化·决策可追溯·可复现
学编程就要猛2 分钟前
Spring AI Alibaba(上)
java·人工智能·spring·springaialibaba
Latchh6 分钟前
视频封面为什么会黑屏或截到旧帧
图像处理·人工智能·计算机视觉·音视频
小马哥crazymxm10 分钟前
Arxiv论文周选 (2026-W35)
论文阅读·人工智能·计算机视觉·目标跟踪
幻影123!11 分钟前
AlphaZero 五子棋实战(番外二):白棋专项训练的一种方案
python·机器学习·强化学习·五子棋·alpha zero
shaibdoio14 分钟前
瞬维AI落地经验:AI Agent工具调用准确率怎么提
数据库·人工智能·oracle
一缕82年的清风16 分钟前
当 AI 承包了 90% 的代码,架构师那致命的 10% 到底在控什么?
人工智能·vibecoding
头发够用的程序员16 分钟前
TensorRT 自定义算子插件实战(三):手搓 2×2 最大池化 customMaxpool
人工智能·pytorch·python·深度学习·神经网络·边缘计算·jetson