当前位置: 首页 > ds >正文

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

3.2.1 生成数据集

%matplotlib inline
import random
import torch
from d2l import torch as d2ldef synthetic_data(w, b, num_examples):# 生成特征矩阵X,形状为(num_examples, len(w)),符合标准正态分布X = torch.normal(0, 1, (num_examples, len(w)))# 计算标签y = Xw + by = 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))

在这里插入图片描述

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 读取数据集

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]])

http://www.xdnf.cn/news/322.html

相关文章:

  • 深度学习中的卷积神经网络
  • git -- 对远程仓库的操作 -- 查看,添加(与clone对比),抓取和拉取,推送(注意点,抓取更新+合并的三种方法,解决冲突,对比),移除
  • 模块内聚:理解和优化模块设计的关键
  • C#如何动态生成实体类?5种方法详解与实战演示
  • 运营商二要素API接口有哪些应用场景?
  • 2025年03月中国电子学会青少年软件编程(Python)等级考试试卷(三级)真题
  • 练习(杨辉三角、字符串旋转)
  • 算法-链表
  • datasheet数据手册-阅读方法
  • 拆机装机,通电主板亮灯风扇不转无法开机解决办法
  • Three.js 教程导航页【目录总览】
  • SpringBoot集成oshi 查询系统数据
  • EVAL长度限制突破
  • 2000V高压储能趋势下,磁环如何实现高低温衰减≤12%
  • 性能测试面试题的详细解答
  • 习题3.4 最长连续递增子序列
  • 习题2.8 输出全排列
  • yarn常用的命令
  • Spring_MVC 快速入门指南
  • C++程序设计基础实验:C++对C的扩展特性与应用
  • Libtorch安装与使用
  • kubernetes-使用ceph-csi
  • Linux 进程
  • 浅析MySQL事务锁
  • 全球IP地址查询API:查询该IP所属的区域,提供即时服务
  • 【时时三省】(C语言基础)用do...while语句实现循环
  • 云端免费训练 AI 大模型推荐(适用于个人学习)
  • github 项目迁移到 gitee
  • 多肽 N 端乙酰化有什么作用?
  • 【机试】高精度