LogoLogo
API ReferenceGitHubSlackService StatusLogin
v3.8.16
v3.8.16
  • Deep Lake Docs
  • Vector Store Quickstart
  • Deep Learning Quickstart
  • Storage & Credentials
    • Storage Options
    • User Authentication
    • Storing Deep Lake Data in Your Own Cloud
      • Microsoft Azure
        • Provisioning Federated Credentials
        • Enabling CORS
      • Amazon Web Services
        • Provisioning Role-Based Access
        • Enabling CORS
  • List of ML Datasets
  • šŸ¢High-Performance Features
    • Introduction
    • Performant Dataloader
    • Tensor Query Language (TQL)
      • TQL Syntax
      • Sampling Datasets
    • Deep Memory
      • How it Works
    • Index for ANN Search
      • Caching and Optimization
    • Managed Tensor Database
      • REST API
      • Migrating Datasets to the Tensor Database
  • šŸ“šEXAMPLE CODE
    • Getting Started
      • Vector Store
        • Step 1: Hello World
        • Step 2: Creating Deep Lake Vector Stores
        • Step 3: Performing Search in Vector Stores
        • Step 4: Customizing Vector Stores
      • Deep Learning
        • 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
    • Tutorials (w Colab)
      • Vector Store Tutorials
        • Vector Search Options
          • Deep Lake Vector Store API
          • REST API
          • LangChain API
        • Image Similarity Search
        • Deep Lake Vector Store in LangChain
        • Deep Lake Vector Store in LlamaIndex
        • Improving Search Accuracy using Deep Memory
      • 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
      • Concurrent Writes
        • Concurrency Using Zookeeper Locks
    • Playbooks
      • Querying, Training and Editing Datasets with Data Lineage
      • Evaluating Model Performance
      • Training Reproducibility Using Deep Lake and Weights & Biases
      • Working with Videos
    • Low-Level API Summary
  • šŸ”¬Technical Details
    • Best Practices
      • Creating Datasets at Scale
      • Training Models at Scale
      • Storage Synchronization and "with" Context
      • Restoring Corrupted Datasets
      • Concurrent Writes
    • Data Layout
    • Version Control and Querying
    • Dataset Visualization
    • Tensor Relationships
    • Visualizer Integration
    • Shuffling in dataloaders
    • How to Contribute
Powered by GitBook
On this page
  • Splitting Datasets for Training and Validation
  • 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?

  1. EXAMPLE CODE
  2. Tutorials (w Colab)
  3. Deep Learning Tutorials
  4. Training Models

Splitting Datasets for Training

PreviousTraining ModelsNextTraining an Image Classification Model in PyTorch

Last updated 1 year ago

Was this helpful?

Splitting Datasets for Training and Validation


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:
  print(train_batch['images'].shape)
  break
for val_batch in val_loader:
  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 .

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