0Pricing
Deep Learning Academy · Lección

Escriba una clase Dataset personalizada

Implemente __len__ y __getitem__

Escriba una clase Dataset personalizada es una lección gratuita de Deep Learning Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Deep Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Deep Learning Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Your Data Needs a Front Door

Before a model can learn, PyTorch needs a clean way to reach your samples one at a time. That front door is a Dataset class. 🚪

Start by Subclassing

You build a custom dataset by subclassing torch.utils.data.Dataset. PyTorch then knows exactly how to ask your object for data.

from torch.utils.data import Dataset

class MyData(Dataset):
    pass

Stash Your Data in __init__

The __init__ method runs once when you create the dataset. Use it to load file paths, arrays, or labels into the object's fields.

def __init__(self, X, y):
    self.X = X
    self.y = y

Two Methods Make It Work

A working dataset only needs two methods: __len__ to report its size and __getitem__ to fetch one sample. That is the whole contract.

__len__ Counts Your Samples

The __len__ method returns how many samples you have. PyTorch reads this to know when an epoch ends and how far an index can go.

def __len__(self):
    return len(self.X)

__getitem__ Returns One Sample

Given an index, __getitem__ returns a single sample, usually a feature and its label. This is where one row of data is handed over.

def __getitem__(self, idx):
    return self.X[idx], self.y[idx]

Return Tensors, Not Lists

__getitem__ should hand back tensors so the model can use them directly. Convert NumPy arrays or Python lists right here if needed.

import torch
x = torch.tensor(self.X[idx], dtype=torch.float32)

Lazy Loading for Big Data

For huge datasets, do not load everything in __init__. Instead read each file inside __getitem__ so only one sample sits in memory at a time.

Apply Transforms Per Sample

__getitem__ is the natural place to apply a transform, like resizing an image. Store the transform in __init__, then call it before returning.

if self.transform:
    x = self.transform(x)

Index It Like a List

Once built, your dataset behaves like a list. Calling len(ds) or ds[0] just triggers the two methods you defined. Test it before training.

ds = MyData(X, y)
print(len(ds), ds[0])

Now It Plugs Into Everything

This tidy interface is why a custom Dataset drops straight into a DataLoader. You write two methods and the rest of PyTorch just works.

Quick Check

Which method does PyTorch call to fetch a single sample by index?

Recap

A custom dataset subclasses Dataset and defines two methods: __len__ for its size and __getitem__ to return one sample. Two methods, full power. 🎉

Preguntas frecuentes

¿La lección «Escriba una clase Dataset personalizada» es gratis?

Sí — el texto completo de «Escriba una clase Dataset personalizada» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Deep Learning Academy, actualiza a CoddyKit PRO. El curso de Deep Learning Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Escriba una clase Dataset personalizada»?

Implemente __len__ y __getitem__ Practicas Deep Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Deep Learning Academy?

No se requiere experiencia previa. Deep Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Escriba una clase Dataset personalizada»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Deep Learning Academy?

Sí. Cada lección de Deep Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Escriba una clase Dataset personalizada
  2. Agrupación en lotes, barajado y num_workers
  3. collate_fn para entradas de longitud variable
  4. Normalice y estandarice las entradas
← Volver a Deep Learning Academy