码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • pytorch回炉再造笔记--python类中getitem的用法


    目录

    1-- 类中__getitem__的作用

    2-- 实例

    3-- 结合pytorch封装并读取batch数据

    4-- 参考


    1-- 类中__getitem__的作用

    当一个python类中定义了__getitem__函数,则其实例对象能够通过下标来进行索引数据。

    2-- 实例

    代码:

    1. import numpy as np
    2. # 创建类
    3. class Example():
    4. def __getitem__(self, index):
    5. data = np.array([[1,2,3], [4,5,6], [7,8,9]])
    6. return data[index]
    7. # 使用Example类实例对象example1
    8. example1 = Example()
    9. # 索引访问数据
    10. print('example1[0][0]:', example1[0][0])
    11. print('example1[0]:', example1[0])
    12. # 切片访问数据
    13. print('example1[0:2]:\n', example1[0:2])

    输出:

    1. example1[0][0]: 1
    2. example1[0]: [1 2 3]
    3. example1[0:2]:
    4. [[1 2 3]
    5. [4 5 6]]

    3-- 结合pytorch封装并读取batch数据

    代码:

    1. import torch
    2. import numpy as np
    3. from torch.utils.data import Dataset
    4. # 创建MyDataset类
    5. class MyDataset(Dataset):
    6. def __init__(self, x, y):
    7. self.data = torch.from_numpy(x).float()
    8. self.label = torch.LongTensor(y)
    9. def __getitem__(self, idx):
    10. return self.data[idx], self.label[idx], idx
    11. def __len__(self):
    12. return len(self.data)
    13. Train_data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
    14. Train_label = np.array([10, 11, 12, 13])
    15. TrainDataset = MyDataset(Train_data, Train_label) # 创建实例对象
    16. print('len:', len(TrainDataset))
    17. # 创建DataLoader
    18. loader = torch.utils.data.DataLoader(
    19. dataset=TrainDataset,
    20. batch_size=2,
    21. shuffle=False,
    22. num_workers=0,
    23. drop_last=False)
    24. # 按batchsize打印数据
    25. for batch_idx, (data, label, index) in enumerate(loader):
    26. print('batch_idx:',batch_idx, '\ndata:',data, '\nlabel:',label, '\nindex:',index)
    27. print('---------')

    输出:

    1. len: 4
    2. batch_idx: 0
    3. data: tensor([[1., 2., 3.],
    4. [4., 5., 6.]])
    5. label: tensor([10, 11])
    6. index: tensor([0, 1])
    7. ---------
    8. batch_idx: 1
    9. data: tensor([[ 7., 8., 9.],
    10. [10., 11., 12.]])
    11. label: tensor([12, 13])
    12. index: tensor([2, 3])
    13. ---------

    4-- 参考

    参考链接1

  • 相关阅读:
    教你几分钟学会DNAC查看设备健康度
    DN-DETR(CVPR 2022)
    Selenium 三种等待方式详解 (强制等待、隐式等待、显示等待)
    CSS初阶语法
    RK3588平台开发系列讲解(SARADC篇)SARADC的工作流程
    RK3588修改eth0和eth1,对调这两个网卡设备的名称
    Linux CentOS7 vim多文件与多窗口操作
    给页面写一个炫酷的时钟特效【web前端】
    ARM底层汇编基础指令
    RabbitMQ管控台使用
  • 原文地址:https://blog.csdn.net/weixin_43863869/article/details/125602643
  • 最新文章
  • 沪漂五周年了:我越来越迷茫了
    Agentic Skill Routing 实战:别再把所有 Skill 塞进 AI Agent 上下文
    MySQL-Seconds_behind_master的精度误差
    [MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱省时间
    AI的至暗历史:从万众期待到被政府撤资,AI的两次死亡徘徊
    Agent OS :五种驯服不确定性的范式
    PortSwigger SQL注入LAB11
    数据库即时编译JIT
    [Begin]AI Learn Data Day 0
    深度学习进阶(二十七)现代 LLM 的核心架构设计其二:SwiGLU
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
小工具 小游戏
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1

京公网安备 11010502049817号