SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2208.02567 · ECCV · 2022

Constructing Balance from Imbalance for Long-tailed Image Recognition

Yong-Lu Li, Cewu Lu, Jiefeng Li, Yue Xu

arXiv · PDF · Open in the Atlas

Code that ran

5 of 8 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (0 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 2 failures of our instrument; 3 no recorded run), measured 2026-11-22; repository links from the Papers with Code archive attributed under CC BY-SA, no affiliation; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2208.02567.json · badge: /api/ran/2208.02567.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
silicx/DLSA community
Papers with Code archive
5 ran · 3 no recorded run
FunctionStatusWhere it lives
BalancedSoftmaxLoss Ran
ran on a synthesized input
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("e4887aebe0516750")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np
import torch.nn as nn

class BalancedSoftmaxLoss(nn.CrossEntropyLoss):

    def __init__(self, all_train_label, num_classes, smoothing=0, sample_weight=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        assert smoothing == 0, str(smoothing)
        if isinstance(all_train_label, torch.Tensor):
            all_train_label = all_train_label.cpu().numpy()
        freq = []
        for i in range(num_classes):
            ids = all_train_label == i
            num = np.sum(ids)
            if num > 0:
                if sample_weight is None:
                    freq.append(num)
                else:
                    freq.append(np.sum(sample_weight[ids]))
            else:
                freq.append(0)
        self.register_buffer('class_freq', (torch.Tensor(freq) + 1e-06).log().unsqueeze(0))

    def forward(self, logit, target):
        logit = logit + self.class_freq
        return super().forward(logit, target)


# Create training labels with 3 classes
all_train_label = np.array([0, 0, 1, 1, 1, 2, 2, 2, 2])
num_classes = 3

INIT_ARGS = {
    'all_train_label': all_train_label,
    'num_classes': num_classes,
    'smoothing': 0,
    'sample_weight': None,
}

# Create logits (batch_size=2, num_classes=3) and targets (batch_size=2)
ARGS = {
    'logit': torch.randn(2, 3),
    'target': torch.tensor([0, 2]),
}

# Construct and call
loss_fn = BalancedSoftmaxLoss(**INIT_ARGS)
output = loss_fn(**ARGS)
print(f"Loss output: {output}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
BalancedSoftmaxLoss_v2 Ran
ran on a synthesized input
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("4fb85c99d3053a81")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F

class BalancedSoftmaxLoss_v2(nn.Module):

    def __init__(self, all_train_label, num_classes, smoothing=0, sample_weight=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.num_class = num_classes
        self.smoothing = smoothing
        if isinstance(all_train_label, torch.Tensor):
            all_train_label = all_train_label.cpu().numpy()
        freq = []
        for i in range(num_classes):
            ids = all_train_label == i
            num = np.sum(ids)
            if num > 0:
                if sample_weight is None:
                    freq.append(num)
                else:
                    freq.append(np.sum(sample_weight[ids]))
            else:
                freq.append(0)
        self.register_buffer('class_freq', (torch.Tensor(freq) + 1e-06).log().unsqueeze(0))

    def forward(self, logit, target):
        logit = logit + self.class_freq
        with torch.no_grad():
            target_vec = torch.zeros_like(logit)
            target_vec.fill_(self.smoothing / (self.num_class - 1))
            target_vec.scatter_(1, target.unsqueeze(1), 1.0 - self.smoothing)
        llh = F.log_softmax(logit, -1)
        loss = torch.mean(torch.sum(-target_vec * llh, dim=-1))
        return loss


all_train_label = np.array([0, 0, 1, 1, 2, 2, 0, 1])
num_classes = 3
smoothing = 0.1

INIT_ARGS = {
    'all_train_label': all_train_label,
    'num_classes': num_classes,
    'smoothing': smoothing,
    'sample_weight': None,
}

logit = torch.randn(2, 3)
target = torch.tensor([0, 2])

ARGS = {
    'logit': logit,
    'target': target,
}

if __name__ == '__main__':
    loss_fn = BalancedSoftmaxLoss_v2(**INIT_ARGS)
    loss = loss_fn(**ARGS)
    print(f"Loss: {loss}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
CrossEntropyLossWrapper Ran
ran on a synthesized input
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("dc2e4e06b6763296")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 0, dtype family float, shape () as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn

class CrossEntropyLossWrapper(nn.CrossEntropyLoss):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

INIT_ARGS = {
    'weight': None,
    'size_average': None,
    'ignore_index': -100,
    'reduce': None,
    'reduction': 'mean',
    'label_smoothing': 0.0
}

ARGS = {
    'input': torch.randn(2, 4),
    'target': torch.tensor([0, 2])
}

if __name__ == '__main__':
    loss_fn = CrossEntropyLossWrapper(**INIT_ARGS)
    output = loss_fn(**ARGS)
    print(f"Loss output: {output}")
    print(f"Output shape: {output.shape}")
Setup block drafted by
a language model, class construct-then-call prompt, model not recorded
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type Tensor, ndim 0, dtype family float, shape () — shape () as a later run recorded it
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
eval_cluster_aided_classifier Ran
ran; our contract draft was wrong, not the code
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("b4b28f623377a685")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import torch.utils.data as tdata

torch.manual_seed(0)

# Define a minimal classifier model that accepts X, Z, P and returns logits
class ClusterAidedClassifier(nn.Module):
    def __init__(self, input_dim=4, cluster_dim=4, proto_dim=4, num_classes=3):
        super().__init__()
        self.fc = nn.Linear(input_dim + cluster_dim + proto_dim, num_classes)
    
    def forward(self, X, Z, P):
        # Concatenate inputs and pass through linear layer
        combined = torch.cat([X, Z, P], dim=1)
        logits = self.fc(combined)
        return logits

# Create a minimal args object with device attribute
class Args:
    def __init__(self):
        self.device = 'cpu'

args = Args()

# Build a minimal test_loader
# Each batch item is (X, Z, P, Y)
# X: batch_size=2, feature_dim=4
# Z: batch_size=2, cluster_dim=4
# P: batch_size=2, proto_dim=4
# Y: batch_size=2 (labels)
batch_size = 2
X1 = torch.randn(batch_size, 4)
Z1 = torch.randn(batch_size, 4)
P1 = torch.randn(batch_size, 4)
Y1 = torch.randint(0, 3, (batch_size,))

X2 = torch.randn(batch_size, 4)
Z2 = torch.randn(batch_size, 4)
P2 = torch.randn(batch_size, 4)
Y2 = torch.randint(0, 3, (batch_size,))

dataset = [
    (X1, Z1, P1, Y1),
    (X2, Z2, P2, Y2)
]

test_loader = tdata.DataLoader(
    dataset,
    batch_size=batch_size,
    shuffle=False,
    collate_fn=lambda batch: (
        torch.cat([item[0] for item in batch], dim=0),
        torch.cat([item[1] for item in batch], dim=0),
        torch.cat([item[2] for item in batch], dim=0),
        torch.cat([item[3].unsqueeze(0) if item[3].dim() == 0 else item[3] for item in batch], dim=0)
    )
)

# Create the model
cls_model = ClusterAidedClassifier(input_dim=4, cluster_dim=4, proto_dim=4, num_classes=3)

ARGS = {
    'cls_model': cls_model,
    'args': args,
    'test_loader': test_loader
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple — a tuple output has no array shape of its own; none is stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
get_classification_loss Ran
ran; our contract draft was wrong, not the code
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("757b8fc1441702d9")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1) and returned type. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np
import torch.nn as nn

torch.manual_seed(0)

# Setup for get_classification_loss function
# The function takes a single parameter 'name' which is a string

ARGS = {
    'name': 'CE'
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1
Imports
numpy, torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type type — a type output has no array shape of its own; none is stated — the instrument coerces any output to an array; for a type output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
adjust_learning_rate Not yet run
unverified (harvested, no recorded run)
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("58558daeef4e2285")
How it ran

no invocation recorded.

shot_acc Not yet run
unverified (harvested, no recorded run)
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("2d1bf3bf736db923")
How it ran

no invocation recorded.

train_cluster_aided_classifier Not yet run
unverified (harvested, no recorded run)
silicx/DLSA/solvers/cluster_aided_classifier.py
code served (permissive licence) · get_code("fe028e773391bd55")
How it ran

no invocation recorded.

Also present in other papers' code

Of 8 samples lifted from this paper's linked repositories, 8 carry a function identity and 0 do not. Of the 8 distinct functions with an identity, 1 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 1 later) and 7 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

FunctionAlso present inEarliest-datedOthers named
shot_acc
brick of this paper's assembly: helper
2 other papers
2 later
2403.06726 (2024-03)
Probabilistic Contrastive Learning for Long-Tailed Visual Recognition
2605.10047 (2026-05)
Rethinking Loss Reweighting for Imbalance Learning as an Inverse Problem: A Neural Collapse Point of View

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-22.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Long-tailed image recognition presents massive challenges to deep learning systems since the imbalance between majority (head) classes and minority (tail) classes severely skews the data-driven deep neural networks. Previous methods tackle with data imbalance from the viewpoints of data distribution, feature space, and model design, etc. In this work, instead of directly learning a recognition model, we suggest confronting the bottleneck of head-to-tail bias before classifier learning, from the previously omitted perspective of balancing label space. To alleviate the head-to-tail bias, we propose a concise paradigm by progressively adjusting label space and dividing the head classes and tail classes, dynamically constructing balance from imbalance to facilitate the classification. With flexible data filtering and label space mapping, we can easily embed our approach to most classification models, especially the decoupled training methods. Besides, we find the separability of headtail classes varies among different features with different inductive biases. Hence, our proposed model also provides a feature evaluation method and paves the way for long-tailed feature learning. Extensive experiments show that our method can boost the performance of state-of-the-arts of different types on widely-used benchmarks. Code is available at https://github.com/silicx/DLSA.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2208.02567")
get_code_for_paper("2208.02567")
have("2208.02567")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2208.02567.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2208.02567.svg)](https://syntology.ai/paper/2208.02567)

Connect an agent — have() is free.