LogoLogo
API ReferenceGitHubSlackService StatusLogin
v3.9.16
v3.9.16
  • šŸ Deep Lake Docs
  • List of ML Datasets
  • šŸ—ļøSETUP
    • Installation
    • User Authentication
      • Workload Identities (Azure Only)
    • Storage and Credentials
      • Storage Options
      • Setting up Deep Lake in Your Cloud
        • Microsoft Azure
          • Configure Azure SSO on Activeloop
          • Provisioning Federated Credentials
          • Enabling CORS
        • Google Cloud
          • Provisioning Federated Credentials
          • Enabling CORS
        • Amazon Web Services
          • Provisioning Role-Based Access
          • Enabling CORS
  • šŸ“šExamples
    • Deep Learning
      • Deep Learning Quickstart
      • Deep Learning Guide
        • Step 1: Hello World
        • Step 2: Creating Deep Lake Datasets
        • Step 3: Understanding Compression
        • Step 4: Accessing and Updating Data
        • Step 5: Visualizing Datasets
        • Step 6: Using Activeloop Storage
        • Step 7: Connecting Deep Lake Datasets to ML Frameworks
        • Step 8: Parallel Computing
        • Step 9: Dataset Version Control
        • Step 10: Dataset Filtering
      • Deep Learning Tutorials
        • Creating Datasets
          • Creating Complex Datasets
          • Creating Object Detection Datasets
          • Creating Time-Series Datasets
          • Creating Datasets with Sequences
          • Creating Video Datasets
        • Training Models
          • Splitting Datasets for Training
          • Training an Image Classification Model in PyTorch
          • Training Models Using MMDetection
          • Training Models Using PyTorch Lightning
          • Training on AWS SageMaker
          • Training an Object Detection and Segmentation Model in PyTorch
        • Updating Datasets
        • Data Processing Using Parallel Computing
      • Deep Learning Playbooks
        • Querying, Training and Editing Datasets with Data Lineage
        • Evaluating Model Performance
        • Training Reproducibility Using Deep Lake and Weights & Biases
        • Working with Videos
      • Deep Lake Dataloaders
      • API Summary
    • RAG
      • RAG Quickstart
      • RAG Tutorials
        • Vector Store Basics
        • Vector Search Options
          • LangChain API
          • Deep Lake Vector Store API
          • Managed Database REST API
        • Customizing Your Vector Store
        • Image Similarity Search
        • Improving Search Accuracy using Deep Memory
      • LangChain Integration
      • LlamaIndex Integration
      • Managed Tensor Database
        • REST API
        • Migrating Datasets to the Tensor Database
      • Deep Memory
        • How it Works
    • Tensor Query Language (TQL)
      • TQL Syntax
      • Index for ANN Search
        • Caching and Optimization
      • Sampling Datasets
  • šŸ”¬Technical Details
    • Best Practices
      • Creating Datasets at Scale
      • Training Models at Scale
      • Storage Synchronization and "with" Context
      • Restoring Corrupted Datasets
      • Concurrent Writes
        • Concurrency Using Zookeeper Locks
    • Deep Lake Data Format
      • Tensor Relationships
      • Version Control and Querying
    • Dataset Visualization
      • Visualizer Integration
    • Shuffling in Dataloaders
    • How to Contribute
Powered by GitBook
On this page
  • How to Split Datasets for Training in Deep Lake
  • Setting up the Environment
  • Fully random splitting by row number (index)
  • Pseudo-random Deep Lake splitting that is optimized for performance
  • Training a Model Using Views

Was this helpful?

Edit on GitHub
  1. Examples
  2. Deep Learning
  3. Deep Learning Tutorials
  4. Training Models

Splitting Datasets for Training

How to Split Datasets for Training in Deep Lake

PreviousTraining ModelsNextTraining an Image Classification Model in PyTorch

Was this helpful?

How to Split Datasets for Training in Deep Lake

This tutorial is also available as a

Deep Lake offers two approaches for splitting dataset for training and validation:

  • Fully random splitting by row number (index)

  • Pseudo-random splitting using Deep Lake's internal method that is optimized for fast streaming

Setting up the Environment

import deeplake
from PIL import Image
import numpy as np
import os, time
import random
import torch
from torchvision import transforms
import getpass

First, let's set up our environment and copy the into your organization. This dataset is an image classification dataset that categorizes images by clothing type (trouser, shirt, etc.). Copying the dataset into your organization enables you to make edits.

os.environ["ACTIVELOOP_TOKEN"]Ā =Ā getpass.getpass()
org_idĀ =Ā <your_org_id>Ā #Ā YouĀ alreadyĀ haveĀ anĀ org_idĀ thatĀ sharesĀ yourĀ username
dsĀ =Ā deeplake.deepcopy("hub://activeloop/fashion-mnist-train",Ā f"hub://{org_id}/fashion-mnist-train-2",Ā overwriteĀ =Ā True)Ā #Ā TheĀ secondĀ parameterĀ canĀ beĀ aĀ localĀ path

If you run this tutorial again, you may load the dataset instead of copying it.

#Ā dsĀ =Ā deeplake.load(f'hub://{os.environ['ORG_ID']}/fashion-mnist-train')

keyboard_arrow_down

Fully random splitting by row number (index)

Lets randomly split the dataset based on arbitrary row numbers:

len_ds = len(ds)

train_frac = 0.8

x = list(range(len_ds))
random.shuffle(x)
x_lim = round(train_frac*len(ds))
train_indices, val_indices = x[:x_lim], x[x_lim:]

print(f"Length of train_indices is {len(train_indices)}")
print(f"Length of val_indices is {len(val_indices)}")

Deep Lake refer to subsets of a dataset as views:

train_view = ds[train_indices]
val_view = ds[val_indices]

Saving the Views (Optional)

In order to achieve reproducibility, you may save the views and use them in the future. Each saved view is assigned a id for reference. Saved views are pointers to data, and they do not duplicate data in storage.

train_view.save_view()
val_view.save_view()
views_listĀ =Ā ds.get_views()print(views_list)

We can also load a view using:

train_view = ds.load_view(views_list[0].id)
val_view = ds.load_view(views_list[1].id)

print(f"Length of train_view is {len(train_view)}")
print(f"Length of val_view is {len(val_view)}")
train_view = ds.load_view(views_list[0].id, optimize = True, num_workers = 2)
val_view = ds.load_view(views_list[1].id, optimize = True, num_workers = 2)

print(f"Length of train_view is {len(train_view)}")
print(f"Length of val_view is {len(val_view)}")

Pseudo-random Deep Lake splitting that is optimized for performance

If high performance is required without duplicating data, we recommend using Deep Lake's internal random_split method, which splits the dataset pseudo-randomly in order to maintain fast streaming.

train_view, val_view = ds.random_split([0.8, 0.2])

print(f"Length of train_view is {len(train_view)}")
print(f"Length of val_view is {len(val_view)}")

Training a Model Using Views

tform = transforms.Compose([
    transforms.RandomRotation(20), # Image augmentation
    transforms.ToTensor(), # Must convert to pytorch tensor for subsequent operations to run
    transforms.Normalize([0.5], [0.5]),
])
batch_size = 32

# Since torchvision transforms expect PIL images, we use the 'pil' decode_method for the 'images' tensor. This is much faster than running ToPILImage inside the transform
train_loader = train_view.pytorch(num_workers = 0, shuffle = True, transform = {'images': tform, 'labels': None}, batch_size = batch_size, decode_method = {'images': 'pil'})
val_loader = val_view.pytorch(num_workers = 0, transform = {'images': tform, 'labels': None}, batch_size = batch_size, decode_method = {'images': 'pil'})
for train_batch in train_loader:
  ## Insert Train Code Here ##
  print(train_batch['images'].shape)
  break
for val_batch in val_loader:
  ## Insert Train Code Here ##
  print(val_batch['images'].shape)
  break

Congrats! You successfully created dataloaders from Deep Lake views! šŸŽ‰

When loading or saving a view, we can specify the flag optimize = True, which the data for optimal streaming performance. Note that this is a computationally intensive and it will duplicate the data from the view at the storage location.

Views and datasets can be used interchangeably for training models. In this tutorial, we show how to create and iterate over dataloaders for the training and validation views, and a .

šŸ“š
Colab Notebook
Fashion MNIST dataset
rechunks
full tutorial for training a classification model on Fashion MNIST is available here