AI-Powered Return Analysis & Classification


Returns are one of the biggest cost drivers in e-commerce. A single unprocessed return can cost up to €15–25 in logistics, quality control, and reprocessing — and this doesn’t include the lost revenue from resale. Most companies know the volume of returns, but not the reasons behind them with sufficient granularity.

This project presents an AI-driven pipeline that automatically reads and classifies free-text return reasons at scale. The system delivers actionable insights for product management, quality assurance, and customer service — all while being fully GDPR-compliant through its local execution.

The Challenge: Unstructured Return Data

Customer comments like “The blue was lighter than expected, and the wool is scratchy” are a goldmine of information — but they cannot be analyzed with conventional methods. Traditional keyword search misses context, and manual classification is not scalable.

The goal: automatically classify each return comment into a standardized category to enable structured analyses.

The Technical Approach: Local LLM via LM Studio

The decisive business advantage of this project is the use of a locally hosted language model. Instead of sending customer data to an external API (OpenAI, Anthropic), the model runs entirely on our own hardware via LM Studio and its OpenAI-compatible API.

from openai import OpenAI
import pandas as pd
from tqdm import tqdm

# Connection to the local LM Studio server
# Advantage: No costs, full data sovereignty & privacy
client = OpenAI(
    base_url="http://localhost:1234/v1",
    api_key="lm-studio"
)

# Optimized system prompt for precise classification in JSON format
SYSTEM_PROMPT = """You are an expert return analyst for an e-commerce company.
Your task is to classify customer return reasons into exactly ONE of these categories:

- WRONG_SIZE: Size/fit problem (too big, too small)
- WRONG_COLOR: Color deviates from expectation
- QUALITY_DEFECT: Material or processing defect
- NOT_AS_DESCRIBED: Product differs from description/photo
- CHANGED_MIND: Customer changed their mind, no longer wants it
- DUPLICATE_ORDER: Accidentally ordered twice
- DELIVERY_DAMAGE: Damaged during shipping

Answer ONLY in this exact JSON format:
{"category": "CATEGORY_NAME", "confidence": 0.95, "reason": "short explanation"}"""

def classify_return(comment: str) -> dict:
    response = client.chat.completions.create(
        model="lmstudio-community/Qwen2.5-7B-Instruct-GGUF",  # Uses the currently loaded model (e.g. Qwen 2.5)
        temperature=0,  # Temperature 0 for maximum determinism
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": f"Return reason: {comment}"}
        ]
    )
    return response.choices[0].message.content

# Load data
df = pd.read_csv("returns.csv")

# Analyze a sample comment
sample = "Dachte das blau wäre heller, außerdem kratzt die Wolle."
result = classify_return(sample)
# Output: QUALITY_DEFECT (Defects prioritized over visual discrepancies)

# Iterate over DataFrame with progress bar
results = []
for _, row in tqdm(df.iterrows(), total=len(df), desc="Classifying"):
    classification = classify_return(row['return_reason'])
    results.append(classification)

df['ai_category'] = results

# Aggregate results
category_distribution = df['ai_category'].value_counts(normalize=True) * 100

Key Insights from the Analysis

A pilot analysis with 500 sample returns revealed a clear pattern:

Category Share Cost Impact
WRONG_SIZE 38% ~€5.70 per return
QUALITY_DEFECT 22% ~€18.90 per return
NOT_AS_DESCRIBED 19% ~€12.40 per return
CHANGED_MIND 12% ~€8.20 per return
WRONG_COLOR 9% ~€6.50 per return

The high share of WRONG_SIZE (38%) directly points to an optimization need in the product detail page: better size guides, customer reviews that mention fit, and possibly a size recommendation tool.

The Business Impact: From Data to Decision

The real value lies not in the categorization itself, but in the resulting decisions:

For product management: Which products have unusually high “NOT_AS_DESCRIBED” rates? These products need better photo material or more accurate descriptions.

For quality assurance: A sudden increase in “QUALITY_DEFECT” returns for a specific supplier in a specific week signals a production batch problem — before it spreads.

For customer service: Classifying returns enables automated, personalized response emails: instead of a generic “we’re sorry,” the customer receives a specific solution offer for their problem.

GDPR Compliance as a Competitive Advantage

The local model execution ensures 100% GDPR compliance:

  • No customer data leaves the corporate network.
  • No data processing agreements with external AI providers necessary.
  • Full control over data retention and deletion.
  • No dependency on third-party API availability or pricing.

Technologies Used

  • Language: Python 3
  • LLM Runtime: LM Studio with OpenAI-compatible API
  • Model: Qwen 2.5 7B Instruct (GGUF quantized)
  • Data Processing: Pandas, tqdm
  • Output Format: Structured JSON for reliable parsing