Complete Label Studio Tutorial: Data Labeling for Machine Learning
Label Studio is an open-source data labeling platform for machine learning. It supports labeling various data types including text, images, audio, video, and time series, making it essential for building high-quality ML training datasets.
Why Label Studio?
Label Studio Advantages:- Multi-modal: Label text, images, audio, video, HTML
- Flexible: Customizable labeling interfaces
- Collaborative: Team-based annotation workflows
- Integrations: ML backends, cloud storage, webhooks
- Open source: Self-hosted with enterprise options
- NLP annotation (NER, sentiment, classification)
- Computer vision labeling (bounding boxes, segmentation)
- Audio transcription and classification
- Multi-modal data annotation
- Active learning workflows
Installation
# Install with pip
pip install label-studio
Start Label Studio
label-studio start
Or with Docker
docker run -it -p 8080:8080 \
-v $(pwd)/mydata:/label-studio/data \
heartexlabs/label-studio:latest
Access at http://localhost:8080
Quick Start
1. Create Project
from labelstudiosdk import Client
Connect to Label Studio
ls = Client(url='http://localhost:8080', apikey='your-api-key')
Create project
project = ls.startproject(
title='Sentiment Analysis',
labelconfig='''
'''
)
print(f"Project created: {project.id}")
2. Import Data
# Import from list
tasks = [
{"text": "I love this product!"},
{"text": "This is terrible."},
{"text": "It's okay, nothing special."}
]
project.importtasks(tasks)
Import from file
project.importtasks('data.json')
Import from URL
project.importtasks([
{"image": "https://example.com/image1.jpg"},
{"image": "https://example.com/image2.jpg"}
])
3. Export Annotations
# Export all annotations
annotations = project.exporttasks()
Export in specific format
annotations = project.exporttasks(exporttype='JSON')
annotations = project.exporttasks(exporttype='CSV')
annotations = project.exporttasks(exporttype='COCO')
annotations = project.exporttasks(exporttype='YOLO')
Save to file
import json
with open('annotations.json', 'w') as f:
json.dump(annotations, f)
Label Configurations
1. Text Classification
2. Named Entity Recognition
3. Image Classification
4. Object Detection (Bounding Boxes)
5. Image Segmentation
6. Audio Transcription
7. Audio Classification with Regions
8. Video Annotation
SDK Operations
1. Project Management
from labelstudiosdk import Client
ls = Client(url='http://localhost:8080', api
key='your-api-key')
List all projects
projects = ls.getprojects()
for p in projects:
print(f"{p.id}: {p.title}")
Get specific project
project = ls.getproject(projectid=1)
Update project
project.setparams(
title="Updated Title",
description="New description"
)
Delete project
project.delete()
2. Task Management
# Get all tasks
tasks = project.gettasks()
Get specific task
task = project.gettask(taskid=1)
Update task
project.updatetask(
taskid=1,
data={"text": "Updated text"}
)
Delete task
project.deletetask(taskid=1)
Get tasks with filters
from labelstudiosdk.datamanager import Filters, Column, Operator, Type
filters = Filters.create(Filters.AND, [
Filters.item(
Column.completedat,
Operator.EMPTY,
Type.Datetime,
Filters.value(True)
)
])
unlabeledtasks = project.gettasks(filters=filters)
3. Annotation Management
# Create annotation
annotation = project.createannotation(
taskid=1,
result=[
{
"fromname": "sentiment",
"toname": "text",
"type": "choices",
"value": {"choices": ["Positive"]}
}
]
)
Get annotations for task
annotations = project.getannotations(taskid=1)
Delete annotation
project.deleteannotation(annotationid=1)
4. Prediction Upload
# Upload predictions for pre-labeling
predictions = [
{
"task": 1,
"result": [
{
"fromname": "sentiment",
"toname": "text",
"type": "choices",
"value": {"choices": ["Positive"]}
}
],
"score": 0.95
}
]
project.createpredictions(predictions)
Bulk prediction upload
modelpredictions = []
for task in project.gettasks():
pred = model.predict(task['data']['text'])
modelpredictions.append({
"task": task['id'],
"result": [{
"fromname": "sentiment",
"toname": "text",
"type": "choices",
"value": {"choices": [pred['label']]}
}],
"score": pred['confidence']
})
project.createpredictions(modelpredictions)
Cloud Storage Integration
1. Amazon S3
# Connect S3 storage
storage = project.connects3importstorage(
bucket='my-bucket',
prefix='images/',
awsaccesskeyid='AKIAXXXXXXXX',
awssecretaccesskey='xxxxxxxxxx',
regionname='us-east-1',
recursivescan=True
)
Sync storage
storage.sync()
Export to S3
exportstorage = project.connects3exportstorage(
bucket='my-bucket',
prefix='annotations/',
awsaccesskeyid='AKIAXXXXXXXX',
awssecretaccesskey='xxxxxxxxxx'
)
2. Google Cloud Storage
# Connect GCS storage
storage = project.connectgoogleimportstorage(
bucket='my-bucket',
prefix='data/',
googleapplicationcredentials='path/to/credentials.json'
)
storage.sync()
3. Azure Blob Storage
# Connect Azure storage
storage = project.connectazureimportstorage(
container='my-container',
prefix='images/',
accountname='myaccount',
accountkey='xxxxxxxxxx'
)
storage.sync()
ML Backend Integration
1. Create ML Backend
# mlbackend.py
from label
studioml import LabelStudioMLBase
class SentimentModel(LabelStudioMLBase):
def init(self, kwargs):
super(SentimentModel, self).init(kwargs)
# Load your model
from transformers import pipeline
self.model = pipeline("sentiment-analysis")
def predict(self, tasks, kwargs):
predictions = []
for task in tasks:
text = task['data']['text']
result = self.model(text)[0]
label = "Positive" if result['label'] == 'POSITIVE' else "Negative"
predictions.append({
'result': [{
'from
name': 'sentiment',
'toname': 'text',
'type': 'choices',
'value': {'choices': [label]}
}],
'score': result['score']
})
return predictions
def fit(self, annotations, kwargs):
# Train your model with new annotations
pass
2. Run ML Backend
# Install ML backend
pip install label-studio-ml
Initialize backend
label-studio-ml init mybackend --script mlbackend.py
Start backend
label-studio-ml start mybackend -p 9090
3. Connect to Label Studio
# Add ML backend to project
project.connectmlbackend(
url='http://localhost:9090',
title='Sentiment Model'
)
Trigger predictions
project.startpredictions()
Active Learning
1. Setup Active Learning
from labelstudioml import LabelStudioMLBase
import numpy as np
class ActiveLearningModel(LabelStudioMLBase):
def predict(self, tasks, kwargs):
predictions = []
for task in tasks:
# Get model prediction with uncertainty
pred, confidence = self.model.predict
withuncertainty(task['data'])
predictions.append({
'result': [{
'from
name': 'label',
'toname': 'text',
'type': 'choices',
'value': {'choices': [pred]}
}],
'score': confidence
})
return predictions
def gettaskstolabel(self, n=10):
# Get tasks sorted by uncertainty
tasks = self.project.gettasks()
predictions = self.predict(tasks)
# Sort by uncertainty (lowest confidence first)
sortedtasks = sorted(
zip(tasks, predictions),
key=lambda x: x[1]['score']
)
return [t[0] for t in sortedtasks[:n]]
2. Uncertainty Sampling
from labelstudiosdk import Client
ls = Client(url='http://localhost:8080', api
key='your-api-key')
project = ls.getproject(projectid=1)
Get tasks with prediction scores
tasks = project.gettasks()
Sort by prediction score (uncertainty)
uncertaintasks = sorted(
[t for t in tasks if t.get('predictions')],
key=lambda t: min(p['score'] for p in t['predictions'])
)
Prioritize uncertain tasks
for task in uncertaintasks[:10]:
print(f"Task {task['id']}: Score {task['predictions'][0]['score']}")
Webhooks
1. Setup Webhooks
# Create webhook
webhook = project.createwebhook(
url='https://my-server.com/webhook',
sendpayload=True,
sendforallactions=False,
actions=['ANNOTATIONCREATED', 'ANNOTATIONUPDATED']
)
Available actions:
- ANNOTATIONCREATED
- ANNOTATIONUPDATED
- ANNOTATIONDELETED
- TASKCREATED
- PROJECTUPDATED
2. Handle Webhook
from flask import Flask, request
app = Flask(name)
@app.route('/webhook', methods=['POST'])
def handlewebhook():
data = request.json
action = data['action']
annotation = data.get('annotation')
task = data.get('task')
if action == 'ANNOTATIONCREATED':
# Trigger model retraining
print(f"New annotation for task {task['id']}")
# retrainmodel(annotation)
return {'status': 'ok'}
if name == 'main':
app.run(port=5000)
Quality Control
1. Agreement Metrics
# Get agreement scores
agreements = project.getagreement()
for taskid, agreement in agreements.items():
print(f"Task {taskid}: {agreement['agreement']:.2%}")
2. Review Workflow
Best Practices
1. Efficient Data Import
import json
from labelstudiosdk import Client
ls = Client(url='http://localhost:8080', apikey='your-api-key')
project = ls.getproject(projectid=1)
Batch import for large datasets
def batchimport(data, batchsize=1000):
for i in range(0, len(data), batchsize):
batch = data[i:i+batchsize]
project.importtasks(batch)
print(f"Imported {min(i+batchsize, len(data))}/{len(data)}")
Load and import
with open('largedataset.json') as f:
data = json.load(f)
batchimport(data)
2. Export Processing
import pandas as pd
Export annotations
annotations = project.exporttasks()
Process for ML training
trainingdata = []
for task in annotations:
if task['annotations']:
annotation = task['annotations'][0]
for result in annotation['result']:
if result['type'] == 'choices':
trainingdata.append({
'text': task['data']['text'],
'label': result['value']['choices'][0]
})
df = pd.DataFrame(trainingdata)
df.tocsv('training_data.csv', index=False)
Conclusion
Label Studio is essential for ML data labeling with:
Key takeaways:
- Design clear labeling interfaces
- Use predictions for pre-labeling efficiency
- Implement quality control workflows
- Leverage webhooks for automation
- Batch operations for large datasets