深度学习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])

相关推荐
100个铜锣烧11 小时前
高级提示技术:Chain-of-Thought与ReAct——让大模型学会“思考”和“行动”
人工智能·大模型·提示词工程
JackHCC12 小时前
快手OneRetrieval:可编辑生成式电商召回
人工智能·机器学习
hhzz12 小时前
基于监控视频的水位尺自动识别技术方案与实现
python·opencv·yolo·图像识别·cv
yongche_shi12 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
前端之虎陈随易12 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·vue.js·人工智能·typescript·node.js
QiLinkOS12 小时前
第三视觉理解徐玉生与他的商业活动(30)
大数据·c++·人工智能·算法·开源协议
武汉唯众智创12 小时前
当汉字成为心理CT:AI汉字联想投射分析的技术实现与心理评估价值
人工智能·ai心理健康·ai心理评估·本土化心理测评·校园心理健康解决方案·ai心理监测·多模态情绪模型
Longvox12 小时前
Agent为什么会死循环?
人工智能·ai编程
陈天伟教授13 小时前
FreeCAD 启动后小窗口闪现即退的解决思路
人工智能·机器人·工业设计
weixin_4080996713 小时前
OCR批量识别图片方案:从手动处理到自动化API系统(Python/Java/PHP实战)
图像处理·python·ocr·文字识别·api调用·批量识别·石榴智能