Medium Scraper: Articles, Authors, Publications & Comments avatar

Medium Scraper: Articles, Authors, Publications & Comments

Pricing

from $1.00 / 1,000 results

Go to Apify Store
Medium Scraper: Articles, Authors, Publications & Comments

Medium Scraper: Articles, Authors, Publications & Comments

Search Medium articles, authors and publications, collect author posts and available article text, and export reader responses or clapper profiles. Get titles, dates, biographies and engagement for content research and writer discovery.

Pricing

from $1.00 / 1,000 results

Rating

0.0

(0)

Developer

ScrapingMonkey

ScrapingMonkey

Maintained by Community

Actor stats

0

Bookmarked

2

Total users

2

Monthly active users

2 months ago

Last modified

Categories

Features

Limited permissions

Share

Medium Scraper helps you discover Medium articles, writers and publications, then review reader engagement. Search a topic, collect an author’s posts or inspect an article with its visible text, responses and clapper profiles for editorial research, thought-leadership analysis and creator discovery.

Find writers and publications covering your niche, compare their articles and examine reader responses. Organize titles, previews, dates and author context into a useful content research workflow.

At a glanceDetails
📥 InputSearch fields or links to the selected items; see the examples below
📤 OutputOne row per article, response, profile or publication, depending on the mode
📄 PaginationAutomatic up to maxResults for each input, when more results are available
🔐 Login requiredNo
⚡ ProcessingMultiple inputs per run with automatic retries for temporary errors
💾 DeliveryOne complete Apify dataset table; CSV, JSON and Excel export

What the Medium scraper collects 📱

Search articles, writers and publications; collect author posts, available article text, reader responses and clapper profiles.

CollectionWhat you receive
Medium article search scraperSearch Medium articles by keyword. Export titles, public previews, authors, publication details, dates and available engagement counts.
Medium article clappers scraperCollect profiles of readers who clapped for a Medium article. Export visible names, biographies, profile links and article associations.
Medium article responses scraperCollect root reader responses to a Medium article. Export each comment as one row with public text, author details, dates and engagement metadata.
Medium article text scraperExtract Medium article metadata and the article text available to visitors. Export paragraphs, author details, dates and engagement counts.
Medium author posts scraperCollect posts from a Medium author profile. Export article titles, public previews, publication dates, authors and engagement metadata.
Medium author profiles scraperExtract Medium author profiles with biographies, avatar links and public follower, following and publication-following counts.
Medium author search scraperFind Medium writers by keyword. Export public author identities, names, biographies, profile links and avatar URLs.
Medium publication search scraperFind Medium publications by keyword. Export publication names, descriptions, slugs, domains and profile images into one dataset.

Data can include:

  • Articles: Titles, previews, available article text and original links.
  • Authors: Names, biographies, avatars and profile links.
  • Publications: Names, descriptions, slugs, domains and images.
  • Publishing activity: Publication dates and author post lists.
  • Engagement: Available clap and response figures and clapper profiles.
  • Responses: Root response text, authors, dates and visible engagement.

How to scrape Medium 🚀

  1. Choose Post Search in What to collect, or select another collection mode.
  2. Fill in the search fields, or paste links to the items you want to collect.
  3. Set the maximum results and any optional filters.
  4. Start the Actor and review the collected rows.
  5. Export the dataset or connect it to your application.

Medium article search scraper — input example

{
"mode": "post-search",
"searchQueries": [
"python"
],
"maxResults": 10
}

maxResults: 10 means up to 10 results for each input. It does not guarantee that the website has that many matches. You can set the limit as low as 1.

Medium article clappers scraper — input example

{
"mode": "post-clappers",
"postUrls": [
"https://medium.com/@tomaspueyo/coronavirus-the-hammer-and-the-dance-be9337092b56"
],
"maxResults": 10
}

Medium article responses scraper — input example

{
"mode": "post-comments",
"postUrls": [
"https://medium.com/@tomaspueyo/coronavirus-the-hammer-and-the-dance-be9337092b56"
],
"maxResults": 10
}

Medium article text scraper — input example

{
"mode": "post",
"postUrls": [
"https://medium.com/@rolandolbouloyfascitelli/how-playing-volleyball-with-ai-agents-helped-me-predict-restaurant-turnover-and-win-a-hackathon-a3c696d6e900"
],
"maxResults": 10
}

Medium author posts scraper — input example

{
"mode": "profile-posts",
"profileUrls": [
"https://medium.com/@andymcdonaldgeo"
],
"maxResults": 10
}

Medium author profiles scraper — input example

{
"mode": "profile",
"profileUrls": [
"https://medium.com/@getpy"
],
"maxResults": 10
}

Medium author search scraper — input example

{
"mode": "profile-search",
"searchQueries": [
"python"
],
"maxResults": 10
}

Medium publication search scraper — input example

{
"mode": "publication-search",
"searchQueries": [
"python"
],
"maxResults": 10
}

Medium data fields and complete output 📦

Field groupIncluded data
ArticlesTitles, previews, available article text and original links.
AuthorsNames, biographies, avatars and profile links.
PublicationsNames, descriptions, slugs, domains and images.
Publishing activityPublication dates and author post lists.
EngagementAvailable clap and response figures and clapper profiles.
ResponsesRoot response text, authors, dates and visible engagement.

Each collected item is a separate row. input identifies the submitted value and result_type identifies the selected mode. All returned fields appear in one table; columns that do not apply to a mode can be empty.

A complete JSON result is shown for every collection mode below, in the same order as the input examples. Each example includes every field for its mode; text and lists are not shortened. Values are representative and can change.

Medium article search scraper — complete JSON result

{
"result_type": "post-search",
"input": "python",
"status": "success",
"id": "87d710633673",
"url": "https://blog.stackademic.com/10-python-tools-i-wish-someone-had-shown-me-as-a-beginner-87d710633673",
"title": "10 Python Tools I Wish Someone Had Shown Me as a Beginner",
"text": "",
"text_is_preview": true,
"is_locked": true,
"visibility": "LOCKED",
"creator.id": "e577a0e69846",
"creator.username": "abdur.rahman12",
"creator.name": "Abdur Rahman",
"creator.url": "https://medium.com/@abdur.rahman12",
"publication.id": "d1baaa8417a4",
"publication.slug": "stackademic",
"publication.name": "Stackademic",
"publication.url": "https://blog.stackademic.com/",
"published_at": "2026-09-08T22:51:46.612000Z",
"updated_at": "2026-09-08T22:51:46.612000Z",
"clap_count": 357,
"response_count": 3,
"voter_count": null,
"reading_time_minutes": 9.441509433962263,
"word_count": null,
"language": null,
"tags": [
"python",
"programming",
"data-science",
"artificial-intelligence",
"technology"
],
"preview_image_url": "https://miro.medium.com/1*10zvqtzqi0QSltxDloIS5Q.png",
"paragraphs.type": [],
"paragraphs.name": [],
"paragraphs.text": [],
"paragraphs.image_id": [],
"paragraphs.media_url": []
}

Medium article clappers scraper — complete JSON result

{
"result_type": "post-clappers",
"input": "be9337092b56",
"status": "success",
"id": "fdc19516129c",
"url": "https://medium.com/@david_deroussel.stu",
"username": "david_deroussel.stu",
"name": "Dave Russel",
"bio": "I am a pirate expert, musician, filmmaker, and video game fan.",
"domain": null,
"avatar_url": "https://miro.medium.com/0*3XiJkgb8VcT9xsBx",
"followers_count": null,
"following_count": null,
"publications_following_count": null,
"is_suspended": null,
"post_id": "be9337092b56",
"clap_count_by_user": null
}

Medium article responses scraper — complete JSON result

{
"result_type": "post-comments",
"input": "be9337092b56",
"status": "success",
"id": "c471f4c80b4",
"url": "https://medium.com/@drjuneau/i-have-a-phd-in-public-health-with-a-specialisation-in-epidemiology-c471f4c80b4",
"title": "I have a PhD in public health with a specialisation in epidemiology.",
"text": "I have a PhD in public health with a specialisation in epidemiology. Just wanted to say that overall, I agree with your argument. Would need to review virus mutations, but even if we allow for error, I think your conclusion stands.\nSaw people doubt your previous piece because of “lack of proper credentials.” So thought I’d share my 2 cents.\nYour team must have been working around the clock. Thanks for putting in the work. This has the potential to influence decision-makers in many countries, and hopefully save lives. I’ll start working on a French translation now.",
"text_is_preview": false,
"is_locked": null,
"visibility": "PUBLIC",
"creator.id": "53a0e1cdfdd4",
"creator.username": "drjuneau",
"creator.name": "Dr. Carl Juneau, PhD",
"creator.url": "https://medium.com/@drjuneau",
"publication.id": null,
"publication.slug": null,
"publication.name": null,
"publication.url": null,
"published_at": "2020-03-19T21:59:32.416000Z",
"updated_at": "2020-03-20T00:02:07.034000Z",
"clap_count": 2766,
"response_count": 9,
"voter_count": 593,
"reading_time_minutes": null,
"word_count": null,
"language": null,
"tags": null,
"preview_image_url": null,
"paragraphs.type": [
"P",
"P",
"P"
],
"paragraphs.name": [
"edeb",
"c2c5",
"cdba"
],
"paragraphs.text": [
"I have a PhD in public health with a specialisation in epidemiology. Just wanted to say that overall, I agree with your argument. Would need to review virus mutations, but even if we allow for error, I think your conclusion stands.",
"Saw people doubt your previous piece because of “lack of proper credentials.” So thought I’d share my 2 cents.",
"Your team must have been working around the clock. Thanks for putting in the work. This has the potential to influence decision-makers in many countries, and hopefully save lives. I’ll start working on a French translation now."
],
"paragraphs.image_id": [
null,
null,
null
],
"paragraphs.media_url": [
null,
null,
null
]
}

Medium article text scraper — complete JSON result

{
"result_type": "post",
"input": "a3c696d6e900",
"status": "success",
"id": "a3c696d6e900",
"url": "https://medium.com/@rolandolbouloyfascitelli/how-playing-volleyball-with-ai-agents-helped-me-predict-restaurant-turnover-and-win-a-hackathon-a3c696d6e900",
"title": "How ‘Playing Volleyball’ with AI Agents Helped Me Predict Restaurant Turnover — and Win a Hackathon",
"text": "How ‘Playing Volleyball’ with AI Agents Helped Me Predict Restaurant Turnover — and Win a Hackathon\nAI generated image\nIn this article, I’ll share the approach I took during the Restaurant Turnover Prediction Hackathon, organized by Great Learning in collaboration with the University of Texas at Austin and the McCombs School of Business.\nA practical case study in agentic-AI orchestration, human-in-the-loop decision gates, lean ML development, rigorous validation, and the development of a hackathon-winning ensemble.\nThe model was only half the problem. The other half was coordinating multiple AI agents quickly enough to explore competing ideas, while maintaining enough control that every consequential decision remained with a human.\nThat is the role of DontPanic, the agentic orchestration framework I implemented. I designed its workflows around the logic of a volleyball rally: agents could receive a task, set up the next action, volley the work across specialized roles, and dispatch results — but the rally always came back to me at the decision line. The agents accelerated execution; they did not own the judgment.\n1. The Problem\nThe task was to predict Annual Turnover for restaurants across India using 3,493 labeled training records and 500 unlabeled test records, with roughly 32 raw predictors spanning location, cuisine, restaurant format, amenities, social-media popularity, and customer-experience ratings. In this article, ‘turnover’ means annual sales/revenue, not employee attrition. The evaluation metric was RMSE (Root Mean Squared Error), so a few very large misses could dominate the score because errors are squared before aggregation.\nThe objective was not simply to fit the most complex model. It was to build a defensible forecasting system: audit the data, understand the economic structure of the target, engineer business-relevant signals, validate candidates under stable cross-validation, reject improvements that did not replicate, and finally distinguish the model’s generalization performance from competition-specific optimization.\n2. Technology Stack\nThe project was built in VS Code as a modular Python package (src/) rather than a collection of disconnected notebook experiments. That architecture mattered: cleaning, feature construction, validation, and inference used the same reusable code paths, reducing the risk that a feature behaved one way during training and another way at submission time.\nBreakdown of the tech-stack architecture used in the project.\n3. Agentic AI Orchestration\nDontPanic was the agentic-AI harness I implemented around the project. Its purpose was not to make the workflow fully autonomous. It was to let multiple agents work quickly while making the decision architecture explicit: who explores, who implements, who challenges, what artifact is authoritative, and when the work must return to me for a human go/no-go decision.\nThat distinction mattered. ML experimentation is a highly iterative process because it creates many locally plausible next steps. An unconstrained agent can keep optimizing the most recent signal, while a human can lose track of whether the underlying hypothesis, validation protocol, or promotion criterion has changed. DontPanic acted as the operating system for the experiment: agents could move the ball, but they could not silently redefine the game.\n{\n \"schema_version\": \"1.0.0\",\n \"id\": \"agent-claude-cli\",\n \"title\": \"Claude CLI agent runtime\",\n \"kind\": \"agent_cli\",\n \"category\": \"agent-cli\",\n \"summary\": \"External agent CLI used by DontPanic as an implementer, auditor, or goal-auditor runtime.\",\n \"setup_required\": true,\n \"setup_doc\": \"docs/GETTING_STARTED.md#setup-tracks--pick-yours\",\n \"default_in_profiles\": [\"core\"],\n \"use_cases\": [\"U1\", \"U3\", \"U4\", \"U5\", \"U6\", \"U7\"],\n \"requires\": {\n \"commands\": [\"claude\"],\n \"env\": [],\n \"files\": [\"~/.dontpanic/config.json\"],\n \"services\": [\"Claude account / Claude Code or CLI runtime\"],\n \"auth\": [\"Claude CLI authenticated by operator\"],\n \"config\": [\n \"roles.implementer\",\n \"roles.auditor\",\n \"roles.goal_auditor\"\n ]\n },\n \"verify\": {\n \"doctor_profiles\": [\"core\"],\n \"probes\": [\"cli:claude\", \"agent_role_config\"],\n \"readiness\": \"Ready when the claude command is present and the selected DontPanic role points at claude.\"\n },\n \"owner_boundary\": {\n \"dontpanic_core\": [\n \"agent registry entry\",\n \"dispatch envelope\",\n \"audit/signoff capture\",\n \"quota and breaker handling\",\n \"role configuration\"\n ],\n \"adapter\": [\n \"subprocess executor for claude\",\n \"stream/output parsing\",\n \"timeout and envelope normalization\"\n ],\n \"operator\": [\n \"Claude CLI installation\",\n \"account authentication\",\n \"model/quota management\",\n \"local CLI updates\"\n ]\n },\n \"mutation_boundary\": {\n \"writes_dontpanic_state\": true,\n \"external_mutation\": \"agent_subprocess_execution\",\n \"allowed_path\": \"DontPanic supervisor invokes claude through the governed executor and captures artifacts through audit/signoff writers.\",\n \"forbidden\": [\n \"Bypassing supervisor gates\",\n \"Untracked agent writes outside declared plan scope\",\n \"Treating Claude account configuration as DontPanic-owned state\"\n ]\n },\n \"notes\": [\n \"Claude is an external runtime, not bundled by DontPanic.\",\n \"Core profile may also support other agent CLIs; this manifest records the Claude-specific path.\"\n ],\n \"setup_steps\": [\n {\n \"id\": \"install_claude_cli\",\n \"what\": \"Install the Claude CLI so DontPanic can spawn agent runs through the governed executor.\",\n \"automatable\": true,\n \"command_template\": \"npm install -g @anthropic-ai/claude-cli\",\n \"verify_probe\": \"cli:claude\",\n \"human_required_reason\": null\n },\n {\n \"id\": \"authenticate_claude\",\n \"what\": \"Authenticate the Claude CLI against the operator's Claude account or API key.\",\n \"automatable\": false,\n \"command_template\": \"claude auth login --token <YOUR_CLAUDE_API_TOKEN>\",\n \"verify_probe\": \"agent_role_config\",\n \"human_required_reason\": \"Operator must approve scopes for their Claude account and treat the API token as a secret; DontPanic does not provision Claude credentials on the operator's behalf.\"\n }\n ]\n}\n3.1 The volleyball rally\n• Serve — I framed the business question, constraints, metric, acceptance criteria, and current champion before an experiment started.\n• Receive — a discovery/research agent inspected the evidence, surfaced anomalies, and proposed testable hypotheses rather than immediately rewriting the model.\n• Set — an implementation agent converted an approved hypothesis into modular code, deterministic artifacts, and a reproducible experiment definition.\n• Volley— a validation/reviewer agent challenged leakage, cross-validation design, seed stability, data provenance, and whether the apparent gain survived comparison with the frozen champion.\n• Dispatch to human — promotion, rejection, expansion, or a change in strategy came back to me. The agents could recommend the shot; they did not own the scoreboard.\nThe practical benefit was not simply faster coding. It was controlled parallelism. Different agents could focus on different failure modes, while the human loop preserved product intent, business plausibility, and accountability. That made the workflow closer to a small product team than to a single chatbot session.\n3.2 Lean ML product delivery\nI also mapped the agent workflow to a lean product-development lifecycle. The objective was to make experimentation cheap in DEV, make evidence hard to fake in UAT, and make production states difficult to mutate accidentally.\nThis DEV/UAT/PROD separation became especially valuable as the experiment count grew. A new agent could enter the workflow without relying on conversational memory alone because the system of record lived in files, manifests, out-of-fold (OOF) predictions, champion registries, and explicit promotion decisions. For practitioners, that is the main pattern I would carry forward: use agents for speed, but use artifacts and gates for truth.\n4. Data Audit: Trust Nothing Until Verified\nBefore modeling, the train and test files were fingerprinted with SHA-256 and audited column-by-column. This was not administrative overhead: several issues could have silently changed the feature space at inference time and degraded predictions without producing an obvious error.\n• Train had 3,493 rows / 34 columns; test had 500 rows / 33 columns (no target).\n• Data-type mismatches between train and test for ‘Ambience’ and ‘Restaurant Tier’ required explicit coercion so that identical features reached the models in both datasets.\n• A schema typo differed between train (‘Endorsed By’) and test (‘Endoresed By’). Without an explicit mapping, the pipeline could have created an all-missing test feature.\n• Zero duplicate rows and zero duplicate predictor vectors — the dataset was clean at the row level.\n• ‘Registration Number’ behaved like an identifier rather than a business predictor (Pearson r approximately -0.017; Spearman approximately -0.022), so it was excluded from modeling and retained only for final row mapping.\n5. Exploratory Data Analysis\n5.1 Univariate: the target is heavily right-skewed\nAnnual Turnover was extremely right-skewed: p90 was about ₹48M, p95 about ₹57M, p99 about ₹100M, and the maximum reached ₹400M. Raw-target skewness was approximately 6.65. A log1p transform made the distribution close to symmetric, so raw, log1p, Yeo-Johnson, and later a square-foot target variant was evaluated. The business implication was important: most restaurants occupied a relatively narrow revenue band, while a tiny group of very large establishments created disproportionate financial error when missed.\nModeling consequence: the tail was not just visually unusual; it dominated the loss function. Error analysis showed that a small set of worst-predicted restaurants contributed a large share of total squared error, so tail diagnostics became a first-class part of model evaluation.\nFigure 1 — Annual Turnover: raw vs log1p transform\n5.2 Missing data: why one-size-fits-all imputation was wrong\nMissing values were not treated as one phenomenon. Some represented ordinary data-quality gaps; others encoded business structure, such as an entertainment rating being absent because the restaurant did not offer that amenity. Treating both cases with the same imputation rule would erase useful information.\nFigure 2 — Missing value percentage by column\n‘Ordinary’ missingness (for example social-media popularity, overall rating, ambience, and tier) was handled with train-fitted imputation plus explicit missingness indicators. This allowed the model to separate the estimated value from the fact that the observation had been unavailable.\n‘Structural’ missingness (Live Music, Comedy Gigs, Value Deals, and Live Sports) was translated into availability flags such as has_live_music and has_comedy. The absence of a rating can mean the service itself does not exist, which is a different business state from ‘unknown rating’.\nORDINARY_MISSINGNESS_FLAGS = {\n \"facebook_popularity_quotient\": \"facebook_missing\",\n \"instagram_popularity_quotient\": \"instagram_missing\",\n \"overall_restaurant_rating\": \"overall_rating_missing\",\n \"ambience\": \"ambience_missing\",\n \"restaurant_tier\": \"tier_missing\",\n}\n\nSTRUCTURAL_AVAILABILITY_FLAGS = {\n \"live_music_rating\": \"has_live_music\",\n \"comedy_gigs_rating\": \"has_comedy\",\n \"value_deals_rating\": \"has_value_deals\",\n \"live_sports_rating\": \"has_live_sports\",\n}\n\n\ndef add_missingness_features(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add ordinary-null and structural-availability indicators before imputation.\"\"\"\n required_columns = set(ORDINARY_MISSINGNESS_FLAGS) | set(\n STRUCTURAL_AVAILABILITY_FLAGS\n )\n missing_columns = sorted(required_columns - set(df.columns))\n if missing_columns:\n raise KeyError(f\"Missing required columns for missingness features: {missing_columns}\")\n\n df = df.copy()\n for column, flag in ORDINARY_MISSINGNESS_FLAGS.items():\n df[flag] = df[column].isna().astype(\"int8\")\n for column, flag in STRUCTURAL_AVAILABILITY_FLAGS.items():\n df[flag] = df[column].notna().astype(\"int8\")\n return df\n5.3 Categorical mess: 297 raw city spellings\nThe City field contained 297 raw spellings for a much smaller set of economic markets: differences in case and whitespace, typographical errors, aliases, and compound multi-city strings all appeared. A reproducible normalization process combined an algorithmically rapidfuzz-match review, a curated alias dictionary, and explicit parsing for compound entries. Rare-city flags and city-frequency features were kept because market size and data support can both influence turnover estimates.\nFigure 3 — Restaurant count by (cleaned) city, top 15\ndef generate_city_candidate_matches(\n city: pd.Series,\n minimum_similarity: float = 80.0,\n) -> pd.DataFrame:\n \"\"\"Return nearest fuzzy matches for review; this never changes city values.\"\"\"\n normalized = normalize_city_values(city, aliases={})\n counts = normalized.value_counts()\n names = [name for name in counts.index if name != \"unknown\"]\n rows = []\n for raw_city in names:\n candidates = [candidate for candidate in names if candidate != raw_city]\n match = process.extractOne(raw_city, candidates, scorer=fuzz.ratio)\n if match is not None and match[1] >= minimum_similarity:\n rows.append(\n {\n \"Raw City\": raw_city,\n \"Candidate\": match[0],\n \"Similarity\": float(match[1]),\n \"Count\": int(counts[raw_city]),\n }\n )\n return pd.DataFrame(\n rows,\n columns=[\"Raw City\", \"Candidate\", \"Similarity\", \"Count\"],\n ).sort_values([\"Similarity\", \"Count\", \"Raw City\"], ascending=[False, False, True])\n5.4 Bivariate relationships\nRestaurant Type and City Tier showed meaningful turnover separation. From a business perspective, those variables capture different revenue environments: restaurant format influences average ticket, throughput, and operating model, while city tier acts as a coarse proxy for demand density, purchasing power, and market scale.\nFigure 4 — Annual Turnover distribution by Restaurant Type\nFigure 5 — Annual Turnover distribution by City Tier\nIndividual rating variables were useful but noisy. Food, hygiene, value-for-money, service, and ambience are not independent business levers; they interact with restaurant format, age, market, social visibility, and positioning. That motivated both non-linear learners and carefully controlled interaction features.\nFigure 6 — Food Rating vs Annual Turnover, colored by Restaurant Tier\n5.5 Multivariate view & correlation matrix\nFigure 7 — Correlation matrix across numeric ratings and the target\nPearson and Spearman views told different stories. Several predictors had materially stronger monotonic than linear association with turnover, suggesting that useful signal existed even when a straight-line relationship was weak. Pairwise-support checks were also added so apparently extreme correlations based on very few overlapping observations were not mistaken for robust structure.\nFigure 8 — Multivariate pairplot of core ratings vs Annual Turnover\n5.6 Engineered temporal features tell a story\nRestaurant opening date was decomposed into calendar components and age features. Older restaurants tended to show higher turnover, but this was treated as an association rather than a causal claim: age may proxy brand recognition, location survivorship, repeat demand, or accumulated operating scale. A fixed reference date was used so the feature remained reproducible.\nFigure 9 — Annual Turnover by opening era\nFigure 10 — Restaurant age (years) vs Annual Turnover\n6. Handling Imbalance in a Regression Problem\nRegression does not have class imbalance in the classification sense, but this target had an analogous problem: the upper tail was rare and expensive. With RMSE, a small number of very large residuals can dominate total squared error. In our diagnostics, the worst observations contributed a disproportionate share of SSE, which meant that a model could look reasonable on most restaurants and still score poorly if it missed a few high-turnover cases.\nValidation therefore used target-stratified 5-fold CV. The continuous target was bucketed into 10 quantile bins only for fold assignment, while the model still trained and scored on raw turnover. Final promotion checks were repeated across independent seeds (17, 42, and 101). This reduced the chance that a candidate became ‘champion’ simply because one favorable split placed the extreme tail in easier folds.\n7. Feature Engineering\nFeature construction was separated into stateless transformations and fitted statistics. Stateless logic was reused identically for train and test; fitted values such as medians, frequency maps, and encodings were learned on training data only, versioned, and reused at inference. This made the pipeline auditable and protected against subtle train/test drift introduced by preprocessing.\n• Missingness & availability flags (see Section 5.2).\n• Calendar features from opening date: year, month, quarter, day-of-week, plus restaurant age in months/years and a 4-bucket ‘opening era’ categorical.\n• Cuisine count: parsed the comma-separated cuisine list into an integer count of cuisines offered.\n• City hierarchy: raw city → cleaned city → primary city → state, plus compound-city flags, region flags, alias flags, frequency, and rare-city indicators at 3 thresholds.\n• Categorical interactions captured business combinations that can have different economics from their components alone: theme × restaurant type, theme × location, liquor × type, and selected entertainment/format combinations.\n• Numeric interactions supported the regularized linear family: restaurant tier × city tier, social visibility × tier, customer-experience × social visibility, and restaurant age × popularity. These converted some non-linear business relationships into a form Ridge could exploit.\n• Frequency and ordinal encodings for every categorical column, learned on train and reused on test.\nThe main frozen modeling pipeline used 71 predictors. Additional engineered families were evaluated by ablation rather than automatically retained; the value of a feature was judged by incremental validation lift, not by how intuitively appealing it sounded.\n8. External Data as an Enrichment Layer\nA separate research branch enriched cleaned city/state keys with public geographic and economic reference data. The goal was to test whether local market capacity, urbanization, tourism intensity, and population scale added information beyond the restaurant’s own attributes.\n• City-level: population, households, household size, log-population, geographic coordinates, and flags for metro status, national-capital-region membership, coastal location, state-capital status, and ‘million-plus city’ status.\n• State-level: population, urban population & urban share, population density, per-capita NSDP, GSDP/NSDP, and domestic/foreign tourism visit volumes (with a derived tourism-per-capita metric).\nThe result was deliberately conservative: several external features showed signal in isolated component tests, but the family did not improve the final ensemble when tested under the full substitution/promotion protocol. It was therefore not promoted into the clean champion. This is a useful business-modeling lesson: a variable can be economically plausible and predictive in isolation yet add little incremental value after stronger correlated signals are already present.\n9. Models: What Was Tried and Why\nThe dataset mixed continuous ratings, sparse/structural missingness, and high-cardinality categoricals, so multiple model families were used as competing hypotheses rather than assuming one algorithm would dominate.\nFigure 11 — Breakdown of ML models implemented\nRidge and ElasticNet were unexpectedly competitive with CatBoost. That was not a failure of boosting; it reflected the amount of structure moved into engineered features and the value of regularization when many related predictors coexist. Tree models remained important because they captured non-linear interactions that the linear family could not express directly.\n10. Hyperparameter Tuning\nDuring model development, each family was tuned independently with Optuna using repeated, target-stratified out-of-fold RMSE as the objective. Candidate discovery and model promotion were based on internal validation rather than the leaderboard. This distinction matters because the later competition-optimization phase should not be confused with generalization performance.\nFigure 12 — Breakdown of key tuned hyperparameters used\nThe strongest clean blend combined CatBoost, Ridge, ElasticNet, and a variance-stabilized square-root Ridge variant (WR01) at approximately 30% / 10% / 6% / 54%. Its repeated out-of-fold RMSE was approximately ₹20.10M. The large WR01 weight was informative: the transformed linear model was not the best standalone learner, but its different error geometry made it highly valuable in the ensemble.\nFigure 13 — Top 15 predictors by CatBoost feature importance\n12. What Improved — and What Did Not\nEvery experiment was logged with the feature family, model configuration, validation design, OOF predictions, and promotion decision. The project improved because weak ideas were rejected as aggressively as strong ideas were promoted.\n• Baseline first: mean/median predictors established an RMSE floor around ₹21.6–21.7M, making it easy to detect models that were merely complex rather than useful.\n• Regularization mattered: Ridge and ElasticNet improved substantially over OLS because the engineered feature space contained correlated business signals and interactions.\n• CatBoost added non-linear and categorical strength, but the project did not assume that tuning always helped. One apparently strong CatBoost tuning result improved the optimization split by roughly ₹258K, then failed independent-seed confirmation and was rejected as selection overfit.\n• Feature engineering was model-dependent. Target encodings, interactions, category-frequency features, and restaurant-tenure features were among the more useful families, while several intuitive aggregate features added little incremental information once stronger predictors were present.\n• External city/state enrichment was a useful negative result: some component tests improved, but ensemble substitution worsened performance, so the external branch was excluded from the clean champion.\n• Ensembling delivered the most reliable final model gain because CatBoost and the regularized linear variants made different mistakes. The objective was not maximum algorithmic complexity; it was minimum validated squared error from complementary models.\n• Tail classifiers and residual-correction models showed promising diagnostic lift, but they did not translate into enough regression-RMSE improvement to justify promotion. Diagnostic usefulness and forecast usefulness were treated as separate questions.\n13. Performance Across Champions\nThe project produced two different kinds of ‘champion’: a clean model champion selected by repeated cross-validation, and a competition champion optimized for the specific evaluation environment. A third intermediate checkpoint, S08, is useful because it shows the effect of a deliberately narrow tail adjustment before the later competition-specific optimization stages. These scores answer different questions and should not be interpreted as interchangeable measures of model generalization.\nCompetition result: LB05 reduced public RMSE by ₹9,195,461.72 versus S08 (approximately 76.1%). That improvement is a competition result, not evidence that the deployable model suddenly generalized at ₹2.89M RMSE.\nfrom __future__ import annotations\n\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nimport time\nimport json\n\nimport joblib\nimport numpy as np\nimport pandas as pd\n\nfrom src import config, data, models, submission\nfrom src.pipeline import FeaturePipeline\nfrom main import _prepare_catboost_matrices, _prepare_model_matrices\n\n\nS01_ID = \"S01\"\nS01_WEIGHTS = {\"catboost\": 0.50, \"ridge\": 0.45, \"elasticnet\": 0.05}\n\n\ndef run(output_dir: Path | None = None) -> tuple[Path, Path]:\n output_dir = output_dir or config.SUBMISSIONS_DIR\n output_dir.mkdir(parents=True, exist_ok=True)\n manifest_path = config.EXPERIMENTS_DIR / \"frozen_v1_manifest.json\"\n if not manifest_path.exists():\n raise FileNotFoundError(f\"Frozen V1 manifest is required: {manifest_path}\")\n manifest = json.loads(manifest_path.read_text(encoding=\"utf-8\"))\n if manifest.get(\"feature_pipeline\") != \"processed_v1\" or manifest.get(\"predictor_count\") != 71:\n raise ValueError(\"Frozen V1 manifest does not describe the processed_v1 71-predictor contract\")\n\n train_raw = data.load_train()\n test_raw = data.load_test()\n pipeline = FeaturePipeline().fit(train_raw)\n train = pipeline.transform(train_raw)\n test = pipeline.transform(test_raw)\n target = config.INTERNAL_TARGET\n\n X_train = train.drop(columns=[target, config.INTERNAL_ID_COL], errors=\"ignore\")\n X_test = test.drop(columns=[config.INTERNAL_ID_COL], errors=\"ignore\")\n y = train[target].astype(float).to_numpy()\n X_numeric, X_test_numeric = _prepare_model_matrices(X_train, X_test)\n X_cat, X_test_cat = _prepare_catboost_matrices(X_train, X_test)\n\n predictions = {}\n timings = {}\n\n start = time.perf_counter()\n catboost = models.get_catboost(**{\n key: value for key, value in manifest[\"catboost_config\"].items()\n if key != \"native_categorical\"\n })\n cat_features = [\n index for index, dtype in enumerate(X_cat.dtypes)\n if str(dtype) in {\"object\", \"string\", \"category\"}\n ]\n catboost.fit(X_cat, y, cat_features=cat_features, verbose=False)\n predictions[\"catboost\"] = catboost.predict(X_test_cat)\n timings[\"catboost_seconds\"] = time.perf_counter() - start\n\n start = time.perf_counter()\n ridge = models.get_ridge(**manifest[\"ridge_config\"])\n ridge.fit(X_numeric, y)\n predictions[\"ridge\"] = ridge.predict(X_test_numeric)\n timings[\"ridge_seconds\"] = time.perf_counter() - start\n\n start = time.perf_counter()\n elasticnet = models.get_elasticnet(**manifest[\"elasticnet_config\"])\n elasticnet.fit(X_numeric, y)\n predictions[\"elasticnet\"] = elasticnet.predict(X_test_numeric)\n timings[\"elasticnet_seconds\"] = time.perf_counter() - start\n\n weights = manifest[\"ensemble_weights\"]\n blend_prediction = sum(weights[name] * predictions[name] for name in weights)\n submission_df = submission.build_submission(test_raw, blend_prediction)\n submission_path = output_dir / \"S01_frozen_v1_blend.csv\"\n submission.write_submission(submission_df, submission_path, expected_rows=len(test_raw))\n\n component_paths = {}\n for name, prediction in predictions.items():\n component_paths[name] = output_dir / f\"S01_{name}_predictions.csv\"\n pd.DataFrame({config.ID_COL: test_raw[config.ID_COL].to_numpy(), config.TARGET: prediction}).to_csv(\n component_paths[name], index=False\n )\n\n metadata = {\n \"submission_id\": S01_ID,\n \"model\": \"Frozen V1 Blend\",\n \"feature_version\": \"frozen production\",\n \"oof_rmse\": 20097389.205713525,\n \"catboost_weight\": S01_WEIGHTS[\"catboost\"],\n \"ridge_weight\": S01_WEIGHTS[\"ridge\"],\n \"elasticnet_weight\": S01_WEIGHTS[\"elasticnet\"],\n \"public_leaderboard_rmse\": None,\n \"leaderboard_rank\": None,\n \"timestamp_utc\": datetime.now(timezone.utc).isoformat(timespec=\"seconds\"),\n \"submission_file\": str(submission_path),\n \"component_files\": {name: str(path) for name, path in component_paths.items()},\n \"fit_method\": \"fit_each_frozen_component_on_all_3493_processed_v1_training_rows\",\n \"catboost_production_iterations_rule\": \"fixed_manifest_value_no_early_stopping\",\n \"manifest_path\": str(manifest_path),\n **timings,\n }\n metadata_path = output_dir / \"S01_metadata.json\"\n metadata_path.write_text(json.dumps(metadata, indent=2), encoding=\"utf-8\")\n return submission_path, metadata_path\n\n\nif __name__ == \"__main__\":\n for path in run():\n print(path)\n14. Competition Performance vs. Generalization\nAfter the clean model and its validation protocol were frozen, a separate competition-optimization stage was used to improve predictions for the specific held-out evaluation set. The exact mechanics are intentionally outside the scope of this article; the important methodological point is that this stage used information available from the competition environment rather than new independently labeled training data.\nFor that reason, the final leaderboard RMSE of approximately ₹2.893M should be treated as competition-specific and potentially overfit to that evaluation set. The appropriate estimate of how the underlying forecasting model would generalize to new restaurants remains the repeated-CV result of roughly ₹20.10M. Keeping those two numbers separate is essential for scientific and business interpretation.\nIn a real forecasting deployment, the competition-optimized layer would not be carried forward unless an equivalent calibration signal were available prospectively. The deployable system would instead use the frozen feature pipeline and ensemble, monitor residuals and distribution drift, and retrain when new actual turnover becomes available.\n15. Main Assumptions\nTrain and test were assumed to arise from sufficiently similar business processes for cross-validation to be meaningful. No formal covariate-shift correction was applied beyond schema and distribution checks.\n• Registration Number was treated strictly as an identifier and excluded from the clean model because it showed no defensible predictive relationship with turnover.\n• Missing amenity ratings were assumed to be structurally informative when the corresponding service was absent; this drove the availability-flag design.\n• All fitted preprocessing statistics had to be learned on training data and reused unchanged at inference; this was enforced in the pipeline rather than left to analyst discipline.\n• External market data was considered admissible only if it improved repeated validation and ensemble-level performance. Economic plausibility alone was not enough for promotion.\n16. Business and Modeling Recommendations\nTreat data quality as model performance. Schema mismatches, city-name fragmentation, and inconsistent categoricals can destroy signal before an algorithm ever sees it.\n• Distinguish ‘missing because unknown’ from ‘missing because the business capability does not exist’. The second case is often a feature, not a nuisance.\n• For highly skewed revenue targets, monitor tail RMSE and squared-error concentration in addition to aggregate RMSE. A few large accounts can determine the financial usefulness of the forecast.\n• Use explicit promotion gates: candidate discovery, independent-seed confirmation, and ensemble substitution. This prevents a one-split improvement from becoming a false champion.\n• Treat agentic AI as an operating model, not as permission for autonomous promotion. Let agents propose, implement, and challenge; keep high-impact model and product decisions at explicit human gates.\n• Keep the system of record outside the chat. Persist datasets, manifests, OOF predictions, experiment ledgers, frozen champions, and promotion decisions so a new agent can resume from evidence rather than reconstructing state from conversation history.\n• Use DEV/UAT/PROD boundaries for ML experimentation. Creativity belongs in DEV; replication and adversarial review belong in UAT; PROD should be deterministic, frozen, and reversible.\n17. Conclusions and Lessons Learned\n1. The strongest lesson from this project was not that one algorithm won. It was that disciplined problem framing, data auditing, tail-aware validation, feature engineering, residual diversity, and a controlled agentic workflow created a better forecasting system than model complexity alone. DontPanic made the AI agents useful as a team: they accelerated discovery and implementation, while explicit human-in-the-loop gates prevented speed from replacing judgment.\n2. The final competition champion reached approximately ₹2.893M RMSE after a separate optimization stage tailored to the evaluation environment. That score was decisive for the competition, but it is intentionally reported separately because it may be overfit and should not be interpreted as the model’s expected error on future restaurants.\n3. The broader takeaway is practical: build the validation system before tuning the model, preserve failed experiments, promote only replicated gains, and always distinguish a model that wins a benchmark from a model you would trust in production. And if you use multiple AI agents, make them play volleyball: let them volley work aggressively, but make the important decisions come back to a human before the point is scored.\nLet’s Connect\nLinkedIn\nGitHub",
"text_is_preview": false,
"is_locked": false,
"visibility": "PUBLIC",
"creator.id": "7ba987eb047",
"creator.username": "rolandolbouloyfascitelli",
"creator.name": "Rolando L Bouloy Fascitelli",
"creator.url": "https://medium.com/@rolandolbouloyfascitelli",
"publication.id": null,
"publication.slug": null,
"publication.name": null,
"publication.url": null,
"published_at": "2026-09-04T05:16:02.965000Z",
"updated_at": "2026-09-04T12:33:00.456000Z",
"clap_count": 140,
"response_count": 3,
"voter_count": null,
"reading_time_minutes": 17.217924528301886,
"word_count": 4152,
"language": "en",
"tags": [
"data-science",
"ai",
"machine-learning",
"ai-agent",
"hackathons"
],
"preview_image_url": "https://miro.medium.com/1*4T_RgTg8k9KF6us7SK0nsw.png",
"paragraphs.type": [
"H3",
"IMG",
"P",
"P",
"P",
"P",
"H3",
"P",
"P",
"H3",
"P",
"IMG",
"H3",
"P",
"P",
"PRE",
"H3",
"P",
"P",
"H3",
"P",
"P",
"H3",
"P",
"P",
"H3",
"H3",
"P",
"P",
"IMG",
"H3",
"P",
"IMG",
"P",
"P",
"PRE",
"H3",
"P",
"IMG",
"PRE",
"H3",
"P",
"IMG",
"IMG",
"P",
"IMG",
"H3",
"IMG",
"P",
"IMG",
"H3",
"P",
"IMG",
"IMG",
"H3",
"P",
"P",
"H3",
"P",
"P",
"P",
"H3",
"P",
"P",
"P",
"H3",
"P",
"IMG",
"P",
"H3",
"P",
"IMG",
"P",
"IMG",
"H3",
"P",
"P",
"H3",
"P",
"P",
"PRE",
"H3",
"P",
"P",
"P",
"IMG",
"H3",
"ULI",
"H3",
"ULI",
"H3",
"P",
"P",
"P",
"H3",
"P",
"P"
],
"paragraphs.name": [
"8c3b",
"9cbf",
"fdd0",
"b0fa",
"4032",
"c1fd",
"a602",
"2e18",
"42ef",
"456e",
"d6c5",
"b06e",
"2aee",
"32c6",
"af29",
"8f5e",
"8242",
"69b6",
"028b",
"129a",
"4013",
"e768",
"0401",
"c530",
"c71e",
"4d8c",
"0df9",
"f187",
"d119",
"35ad",
"722a",
"c2c2",
"5dd4",
"408b",
"16b3",
"d865",
"8320",
"fd4d",
"f977",
"074f",
"f9f5",
"f561",
"44ed",
"a9f1",
"5f81",
"7f75",
"8f85",
"c1d2",
"a7aa",
"40ad",
"a904",
"7a09",
"7f6b",
"b9b9",
"dfeb",
"7d0a",
"b0dc",
"02a1",
"85ea",
"6e9a",
"ac41",
"ba5b",
"1ce5",
"7305",
"9170",
"87e3",
"8591",
"dfd9",
"ff9e",
"0753",
"8a97",
"dc4f",
"5733",
"e09b",
"18f1",
"7ad0",
"c72b",
"e2d5",
"6759",
"0bf9",
"3457",
"5712",
"3bc7",
"05ba",
"5328",
"29df",
"d4fd",
"0dff",
"7a5e",
"2a3b",
"fd2e",
"6e83",
"d533",
"23a1",
"1f7d",
"ed26",
"29f2"
],
"paragraphs.text": [
"How ‘Playing Volleyball’ with AI Agents Helped Me Predict Restaurant Turnover — and Win a Hackathon",
"AI generated image",
"In this article, I’ll share the approach I took during the Restaurant Turnover Prediction Hackathon, organized by Great Learning in collaboration with the University of Texas at Austin and the McCombs School of Business.",
"A practical case study in agentic-AI orchestration, human-in-the-loop decision gates, lean ML development, rigorous validation, and the development of a hackathon-winning ensemble.",
"The model was only half the problem. The other half was coordinating multiple AI agents quickly enough to explore competing ideas, while maintaining enough control that every consequential decision remained with a human.",
"That is the role of DontPanic, the agentic orchestration framework I implemented. I designed its workflows around the logic of a volleyball rally: agents could receive a task, set up the next action, volley the work across specialized roles, and dispatch results — but the rally always came back to me at the decision line. The agents accelerated execution; they did not own the judgment.",
"1. The Problem",
"The task was to predict Annual Turnover for restaurants across India using 3,493 labeled training records and 500 unlabeled test records, with roughly 32 raw predictors spanning location, cuisine, restaurant format, amenities, social-media popularity, and customer-experience ratings. In this article, ‘turnover’ means annual sales/revenue, not employee attrition. The evaluation metric was RMSE (Root Mean Squared Error), so a few very large misses could dominate the score because errors are squared before aggregation.",
"The objective was not simply to fit the most complex model. It was to build a defensible forecasting system: audit the data, understand the economic structure of the target, engineer business-relevant signals, validate candidates under stable cross-validation, reject improvements that did not replicate, and finally distinguish the model’s generalization performance from competition-specific optimization.",
"2. Technology Stack",
"The project was built in VS Code as a modular Python package (src/) rather than a collection of disconnected notebook experiments. That architecture mattered: cleaning, feature construction, validation, and inference used the same reusable code paths, reducing the risk that a feature behaved one way during training and another way at submission time.",
"Breakdown of the tech-stack architecture used in the project.",
"3. Agentic AI Orchestration",
"DontPanic was the agentic-AI harness I implemented around the project. Its purpose was not to make the workflow fully autonomous. It was to let multiple agents work quickly while making the decision architecture explicit: who explores, who implements, who challenges, what artifact is authoritative, and when the work must return to me for a human go/no-go decision.",
"That distinction mattered. ML experimentation is a highly iterative process because it creates many locally plausible next steps. An unconstrained agent can keep optimizing the most recent signal, while a human can lose track of whether the underlying hypothesis, validation protocol, or promotion criterion has changed. DontPanic acted as the operating system for the experiment: agents could move the ball, but they could not silently redefine the game.",
"{\n \"schema_version\": \"1.0.0\",\n \"id\": \"agent-claude-cli\",\n \"title\": \"Claude CLI agent runtime\",\n \"kind\": \"agent_cli\",\n \"category\": \"agent-cli\",\n \"summary\": \"External agent CLI used by DontPanic as an implementer, auditor, or goal-auditor runtime.\",\n \"setup_required\": true,\n \"setup_doc\": \"docs/GETTING_STARTED.md#setup-tracks--pick-yours\",\n \"default_in_profiles\": [\"core\"],\n \"use_cases\": [\"U1\", \"U3\", \"U4\", \"U5\", \"U6\", \"U7\"],\n \"requires\": {\n \"commands\": [\"claude\"],\n \"env\": [],\n \"files\": [\"~/.dontpanic/config.json\"],\n \"services\": [\"Claude account / Claude Code or CLI runtime\"],\n \"auth\": [\"Claude CLI authenticated by operator\"],\n \"config\": [\n \"roles.implementer\",\n \"roles.auditor\",\n \"roles.goal_auditor\"\n ]\n },\n \"verify\": {\n \"doctor_profiles\": [\"core\"],\n \"probes\": [\"cli:claude\", \"agent_role_config\"],\n \"readiness\": \"Ready when the claude command is present and the selected DontPanic role points at claude.\"\n },\n \"owner_boundary\": {\n \"dontpanic_core\": [\n \"agent registry entry\",\n \"dispatch envelope\",\n \"audit/signoff capture\",\n \"quota and breaker handling\",\n \"role configuration\"\n ],\n \"adapter\": [\n \"subprocess executor for claude\",\n \"stream/output parsing\",\n \"timeout and envelope normalization\"\n ],\n \"operator\": [\n \"Claude CLI installation\",\n \"account authentication\",\n \"model/quota management\",\n \"local CLI updates\"\n ]\n },\n \"mutation_boundary\": {\n \"writes_dontpanic_state\": true,\n \"external_mutation\": \"agent_subprocess_execution\",\n \"allowed_path\": \"DontPanic supervisor invokes claude through the governed executor and captures artifacts through audit/signoff writers.\",\n \"forbidden\": [\n \"Bypassing supervisor gates\",\n \"Untracked agent writes outside declared plan scope\",\n \"Treating Claude account configuration as DontPanic-owned state\"\n ]\n },\n \"notes\": [\n \"Claude is an external runtime, not bundled by DontPanic.\",\n \"Core profile may also support other agent CLIs; this manifest records the Claude-specific path.\"\n ],\n \"setup_steps\": [\n {\n \"id\": \"install_claude_cli\",\n \"what\": \"Install the Claude CLI so DontPanic can spawn agent runs through the governed executor.\",\n \"automatable\": true,\n \"command_template\": \"npm install -g @anthropic-ai/claude-cli\",\n \"verify_probe\": \"cli:claude\",\n \"human_required_reason\": null\n },\n {\n \"id\": \"authenticate_claude\",\n \"what\": \"Authenticate the Claude CLI against the operator's Claude account or API key.\",\n \"automatable\": false,\n \"command_template\": \"claude auth login --token <YOUR_CLAUDE_API_TOKEN>\",\n \"verify_probe\": \"agent_role_config\",\n \"human_required_reason\": \"Operator must approve scopes for their Claude account and treat the API token as a secret; DontPanic does not provision Claude credentials on the operator's behalf.\"\n }\n ]\n}",
"3.1 The volleyball rally",
"• Serve — I framed the business question, constraints, metric, acceptance criteria, and current champion before an experiment started.\n• Receive — a discovery/research agent inspected the evidence, surfaced anomalies, and proposed testable hypotheses rather than immediately rewriting the model.\n• Set — an implementation agent converted an approved hypothesis into modular code, deterministic artifacts, and a reproducible experiment definition.\n• Volley— a validation/reviewer agent challenged leakage, cross-validation design, seed stability, data provenance, and whether the apparent gain survived comparison with the frozen champion.\n• Dispatch to human — promotion, rejection, expansion, or a change in strategy came back to me. The agents could recommend the shot; they did not own the scoreboard.",
"The practical benefit was not simply faster coding. It was controlled parallelism. Different agents could focus on different failure modes, while the human loop preserved product intent, business plausibility, and accountability. That made the workflow closer to a small product team than to a single chatbot session.",
"3.2 Lean ML product delivery",
"I also mapped the agent workflow to a lean product-development lifecycle. The objective was to make experimentation cheap in DEV, make evidence hard to fake in UAT, and make production states difficult to mutate accidentally.",
"This DEV/UAT/PROD separation became especially valuable as the experiment count grew. A new agent could enter the workflow without relying on conversational memory alone because the system of record lived in files, manifests, out-of-fold (OOF) predictions, champion registries, and explicit promotion decisions. For practitioners, that is the main pattern I would carry forward: use agents for speed, but use artifacts and gates for truth.",
"4. Data Audit: Trust Nothing Until Verified",
"Before modeling, the train and test files were fingerprinted with SHA-256 and audited column-by-column. This was not administrative overhead: several issues could have silently changed the feature space at inference time and degraded predictions without producing an obvious error.",
"• Train had 3,493 rows / 34 columns; test had 500 rows / 33 columns (no target).\n• Data-type mismatches between train and test for ‘Ambience’ and ‘Restaurant Tier’ required explicit coercion so that identical features reached the models in both datasets.\n• A schema typo differed between train (‘Endorsed By’) and test (‘Endoresed By’). Without an explicit mapping, the pipeline could have created an all-missing test feature.\n• Zero duplicate rows and zero duplicate predictor vectors — the dataset was clean at the row level.\n• ‘Registration Number’ behaved like an identifier rather than a business predictor (Pearson r approximately -0.017; Spearman approximately -0.022), so it was excluded from modeling and retained only for final row mapping.",
"5. Exploratory Data Analysis",
"5.1 Univariate: the target is heavily right-skewed",
"Annual Turnover was extremely right-skewed: p90 was about ₹48M, p95 about ₹57M, p99 about ₹100M, and the maximum reached ₹400M. Raw-target skewness was approximately 6.65. A log1p transform made the distribution close to symmetric, so raw, log1p, Yeo-Johnson, and later a square-foot target variant was evaluated. The business implication was important: most restaurants occupied a relatively narrow revenue band, while a tiny group of very large establishments created disproportionate financial error when missed.",
"Modeling consequence: the tail was not just visually unusual; it dominated the loss function. Error analysis showed that a small set of worst-predicted restaurants contributed a large share of total squared error, so tail diagnostics became a first-class part of model evaluation.",
"Figure 1 — Annual Turnover: raw vs log1p transform",
"5.2 Missing data: why one-size-fits-all imputation was wrong",
"Missing values were not treated as one phenomenon. Some represented ordinary data-quality gaps; others encoded business structure, such as an entertainment rating being absent because the restaurant did not offer that amenity. Treating both cases with the same imputation rule would erase useful information.",
"Figure 2 — Missing value percentage by column",
"‘Ordinary’ missingness (for example social-media popularity, overall rating, ambience, and tier) was handled with train-fitted imputation plus explicit missingness indicators. This allowed the model to separate the estimated value from the fact that the observation had been unavailable.",
"‘Structural’ missingness (Live Music, Comedy Gigs, Value Deals, and Live Sports) was translated into availability flags such as has_live_music and has_comedy. The absence of a rating can mean the service itself does not exist, which is a different business state from ‘unknown rating’.",
"ORDINARY_MISSINGNESS_FLAGS = {\n \"facebook_popularity_quotient\": \"facebook_missing\",\n \"instagram_popularity_quotient\": \"instagram_missing\",\n \"overall_restaurant_rating\": \"overall_rating_missing\",\n \"ambience\": \"ambience_missing\",\n \"restaurant_tier\": \"tier_missing\",\n}\n\nSTRUCTURAL_AVAILABILITY_FLAGS = {\n \"live_music_rating\": \"has_live_music\",\n \"comedy_gigs_rating\": \"has_comedy\",\n \"value_deals_rating\": \"has_value_deals\",\n \"live_sports_rating\": \"has_live_sports\",\n}\n\n\ndef add_missingness_features(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Add ordinary-null and structural-availability indicators before imputation.\"\"\"\n required_columns = set(ORDINARY_MISSINGNESS_FLAGS) | set(\n STRUCTURAL_AVAILABILITY_FLAGS\n )\n missing_columns = sorted(required_columns - set(df.columns))\n if missing_columns:\n raise KeyError(f\"Missing required columns for missingness features: {missing_columns}\")\n\n df = df.copy()\n for column, flag in ORDINARY_MISSINGNESS_FLAGS.items():\n df[flag] = df[column].isna().astype(\"int8\")\n for column, flag in STRUCTURAL_AVAILABILITY_FLAGS.items():\n df[flag] = df[column].notna().astype(\"int8\")\n return df",
"5.3 Categorical mess: 297 raw city spellings",
"The City field contained 297 raw spellings for a much smaller set of economic markets: differences in case and whitespace, typographical errors, aliases, and compound multi-city strings all appeared. A reproducible normalization process combined an algorithmically rapidfuzz-match review, a curated alias dictionary, and explicit parsing for compound entries. Rare-city flags and city-frequency features were kept because market size and data support can both influence turnover estimates.",
"Figure 3 — Restaurant count by (cleaned) city, top 15",
"def generate_city_candidate_matches(\n city: pd.Series,\n minimum_similarity: float = 80.0,\n) -> pd.DataFrame:\n \"\"\"Return nearest fuzzy matches for review; this never changes city values.\"\"\"\n normalized = normalize_city_values(city, aliases={})\n counts = normalized.value_counts()\n names = [name for name in counts.index if name != \"unknown\"]\n rows = []\n for raw_city in names:\n candidates = [candidate for candidate in names if candidate != raw_city]\n match = process.extractOne(raw_city, candidates, scorer=fuzz.ratio)\n if match is not None and match[1] >= minimum_similarity:\n rows.append(\n {\n \"Raw City\": raw_city,\n \"Candidate\": match[0],\n \"Similarity\": float(match[1]),\n \"Count\": int(counts[raw_city]),\n }\n )\n return pd.DataFrame(\n rows,\n columns=[\"Raw City\", \"Candidate\", \"Similarity\", \"Count\"],\n ).sort_values([\"Similarity\", \"Count\", \"Raw City\"], ascending=[False, False, True])",
"5.4 Bivariate relationships",
"Restaurant Type and City Tier showed meaningful turnover separation. From a business perspective, those variables capture different revenue environments: restaurant format influences average ticket, throughput, and operating model, while city tier acts as a coarse proxy for demand density, purchasing power, and market scale.",
"Figure 4 — Annual Turnover distribution by Restaurant Type",
"Figure 5 — Annual Turnover distribution by City Tier",
"Individual rating variables were useful but noisy. Food, hygiene, value-for-money, service, and ambience are not independent business levers; they interact with restaurant format, age, market, social visibility, and positioning. That motivated both non-linear learners and carefully controlled interaction features.",
"Figure 6 — Food Rating vs Annual Turnover, colored by Restaurant Tier",
"5.5 Multivariate view & correlation matrix",
"Figure 7 — Correlation matrix across numeric ratings and the target",
"Pearson and Spearman views told different stories. Several predictors had materially stronger monotonic than linear association with turnover, suggesting that useful signal existed even when a straight-line relationship was weak. Pairwise-support checks were also added so apparently extreme correlations based on very few overlapping observations were not mistaken for robust structure.",
"Figure 8 — Multivariate pairplot of core ratings vs Annual Turnover",
"5.6 Engineered temporal features tell a story",
"Restaurant opening date was decomposed into calendar components and age features. Older restaurants tended to show higher turnover, but this was treated as an association rather than a causal claim: age may proxy brand recognition, location survivorship, repeat demand, or accumulated operating scale. A fixed reference date was used so the feature remained reproducible.",
"Figure 9 — Annual Turnover by opening era",
"Figure 10 — Restaurant age (years) vs Annual Turnover",
"6. Handling Imbalance in a Regression Problem",
"Regression does not have class imbalance in the classification sense, but this target had an analogous problem: the upper tail was rare and expensive. With RMSE, a small number of very large residuals can dominate total squared error. In our diagnostics, the worst observations contributed a disproportionate share of SSE, which meant that a model could look reasonable on most restaurants and still score poorly if it missed a few high-turnover cases.",
"Validation therefore used target-stratified 5-fold CV. The continuous target was bucketed into 10 quantile bins only for fold assignment, while the model still trained and scored on raw turnover. Final promotion checks were repeated across independent seeds (17, 42, and 101). This reduced the chance that a candidate became ‘champion’ simply because one favorable split placed the extreme tail in easier folds.",
"7. Feature Engineering",
"Feature construction was separated into stateless transformations and fitted statistics. Stateless logic was reused identically for train and test; fitted values such as medians, frequency maps, and encodings were learned on training data only, versioned, and reused at inference. This made the pipeline auditable and protected against subtle train/test drift introduced by preprocessing.",
"• Missingness & availability flags (see Section 5.2).\n• Calendar features from opening date: year, month, quarter, day-of-week, plus restaurant age in months/years and a 4-bucket ‘opening era’ categorical.\n• Cuisine count: parsed the comma-separated cuisine list into an integer count of cuisines offered.\n• City hierarchy: raw city → cleaned city → primary city → state, plus compound-city flags, region flags, alias flags, frequency, and rare-city indicators at 3 thresholds.\n• Categorical interactions captured business combinations that can have different economics from their components alone: theme × restaurant type, theme × location, liquor × type, and selected entertainment/format combinations.\n• Numeric interactions supported the regularized linear family: restaurant tier × city tier, social visibility × tier, customer-experience × social visibility, and restaurant age × popularity. These converted some non-linear business relationships into a form Ridge could exploit.\n• Frequency and ordinal encodings for every categorical column, learned on train and reused on test.",
"The main frozen modeling pipeline used 71 predictors. Additional engineered families were evaluated by ablation rather than automatically retained; the value of a feature was judged by incremental validation lift, not by how intuitively appealing it sounded.",
"8. External Data as an Enrichment Layer",
"A separate research branch enriched cleaned city/state keys with public geographic and economic reference data. The goal was to test whether local market capacity, urbanization, tourism intensity, and population scale added information beyond the restaurant’s own attributes.",
"• City-level: population, households, household size, log-population, geographic coordinates, and flags for metro status, national-capital-region membership, coastal location, state-capital status, and ‘million-plus city’ status.\n• State-level: population, urban population & urban share, population density, per-capita NSDP, GSDP/NSDP, and domestic/foreign tourism visit volumes (with a derived tourism-per-capita metric).",
"The result was deliberately conservative: several external features showed signal in isolated component tests, but the family did not improve the final ensemble when tested under the full substitution/promotion protocol. It was therefore not promoted into the clean champion. This is a useful business-modeling lesson: a variable can be economically plausible and predictive in isolation yet add little incremental value after stronger correlated signals are already present.",
"9. Models: What Was Tried and Why",
"The dataset mixed continuous ratings, sparse/structural missingness, and high-cardinality categoricals, so multiple model families were used as competing hypotheses rather than assuming one algorithm would dominate.",
"Figure 11 — Breakdown of ML models implemented",
"Ridge and ElasticNet were unexpectedly competitive with CatBoost. That was not a failure of boosting; it reflected the amount of structure moved into engineered features and the value of regularization when many related predictors coexist. Tree models remained important because they captured non-linear interactions that the linear family could not express directly.",
"10. Hyperparameter Tuning",
"During model development, each family was tuned independently with Optuna using repeated, target-stratified out-of-fold RMSE as the objective. Candidate discovery and model promotion were based on internal validation rather than the leaderboard. This distinction matters because the later competition-optimization phase should not be confused with generalization performance.",
"Figure 12 — Breakdown of key tuned hyperparameters used",
"The strongest clean blend combined CatBoost, Ridge, ElasticNet, and a variance-stabilized square-root Ridge variant (WR01) at approximately 30% / 10% / 6% / 54%. Its repeated out-of-fold RMSE was approximately ₹20.10M. The large WR01 weight was informative: the transformed linear model was not the best standalone learner, but its different error geometry made it highly valuable in the ensemble.",
"Figure 13 — Top 15 predictors by CatBoost feature importance",
"12. What Improved — and What Did Not",
"Every experiment was logged with the feature family, model configuration, validation design, OOF predictions, and promotion decision. The project improved because weak ideas were rejected as aggressively as strong ideas were promoted.",
"• Baseline first: mean/median predictors established an RMSE floor around ₹21.6–21.7M, making it easy to detect models that were merely complex rather than useful.\n• Regularization mattered: Ridge and ElasticNet improved substantially over OLS because the engineered feature space contained correlated business signals and interactions.\n• CatBoost added non-linear and categorical strength, but the project did not assume that tuning always helped. One apparently strong CatBoost tuning result improved the optimization split by roughly ₹258K, then failed independent-seed confirmation and was rejected as selection overfit.\n• Feature engineering was model-dependent. Target encodings, interactions, category-frequency features, and restaurant-tenure features were among the more useful families, while several intuitive aggregate features added little incremental information once stronger predictors were present.\n• External city/state enrichment was a useful negative result: some component tests improved, but ensemble substitution worsened performance, so the external branch was excluded from the clean champion.\n• Ensembling delivered the most reliable final model gain because CatBoost and the regularized linear variants made different mistakes. The objective was not maximum algorithmic complexity; it was minimum validated squared error from complementary models.\n• Tail classifiers and residual-correction models showed promising diagnostic lift, but they did not translate into enough regression-RMSE improvement to justify promotion. Diagnostic usefulness and forecast usefulness were treated as separate questions.",
"13. Performance Across Champions",
"The project produced two different kinds of ‘champion’: a clean model champion selected by repeated cross-validation, and a competition champion optimized for the specific evaluation environment. A third intermediate checkpoint, S08, is useful because it shows the effect of a deliberately narrow tail adjustment before the later competition-specific optimization stages. These scores answer different questions and should not be interpreted as interchangeable measures of model generalization.",
"Competition result: LB05 reduced public RMSE by ₹9,195,461.72 versus S08 (approximately 76.1%). That improvement is a competition result, not evidence that the deployable model suddenly generalized at ₹2.89M RMSE.",
"from __future__ import annotations\n\nfrom datetime import datetime, timezone\nfrom pathlib import Path\nimport time\nimport json\n\nimport joblib\nimport numpy as np\nimport pandas as pd\n\nfrom src import config, data, models, submission\nfrom src.pipeline import FeaturePipeline\nfrom main import _prepare_catboost_matrices, _prepare_model_matrices\n\n\nS01_ID = \"S01\"\nS01_WEIGHTS = {\"catboost\": 0.50, \"ridge\": 0.45, \"elasticnet\": 0.05}\n\n\ndef run(output_dir: Path | None = None) -> tuple[Path, Path]:\n output_dir = output_dir or config.SUBMISSIONS_DIR\n output_dir.mkdir(parents=True, exist_ok=True)\n manifest_path = config.EXPERIMENTS_DIR / \"frozen_v1_manifest.json\"\n if not manifest_path.exists():\n raise FileNotFoundError(f\"Frozen V1 manifest is required: {manifest_path}\")\n manifest = json.loads(manifest_path.read_text(encoding=\"utf-8\"))\n if manifest.get(\"feature_pipeline\") != \"processed_v1\" or manifest.get(\"predictor_count\") != 71:\n raise ValueError(\"Frozen V1 manifest does not describe the processed_v1 71-predictor contract\")\n\n train_raw = data.load_train()\n test_raw = data.load_test()\n pipeline = FeaturePipeline().fit(train_raw)\n train = pipeline.transform(train_raw)\n test = pipeline.transform(test_raw)\n target = config.INTERNAL_TARGET\n\n X_train = train.drop(columns=[target, config.INTERNAL_ID_COL], errors=\"ignore\")\n X_test = test.drop(columns=[config.INTERNAL_ID_COL], errors=\"ignore\")\n y = train[target].astype(float).to_numpy()\n X_numeric, X_test_numeric = _prepare_model_matrices(X_train, X_test)\n X_cat, X_test_cat = _prepare_catboost_matrices(X_train, X_test)\n\n predictions = {}\n timings = {}\n\n start = time.perf_counter()\n catboost = models.get_catboost(**{\n key: value for key, value in manifest[\"catboost_config\"].items()\n if key != \"native_categorical\"\n })\n cat_features = [\n index for index, dtype in enumerate(X_cat.dtypes)\n if str(dtype) in {\"object\", \"string\", \"category\"}\n ]\n catboost.fit(X_cat, y, cat_features=cat_features, verbose=False)\n predictions[\"catboost\"] = catboost.predict(X_test_cat)\n timings[\"catboost_seconds\"] = time.perf_counter() - start\n\n start = time.perf_counter()\n ridge = models.get_ridge(**manifest[\"ridge_config\"])\n ridge.fit(X_numeric, y)\n predictions[\"ridge\"] = ridge.predict(X_test_numeric)\n timings[\"ridge_seconds\"] = time.perf_counter() - start\n\n start = time.perf_counter()\n elasticnet = models.get_elasticnet(**manifest[\"elasticnet_config\"])\n elasticnet.fit(X_numeric, y)\n predictions[\"elasticnet\"] = elasticnet.predict(X_test_numeric)\n timings[\"elasticnet_seconds\"] = time.perf_counter() - start\n\n weights = manifest[\"ensemble_weights\"]\n blend_prediction = sum(weights[name] * predictions[name] for name in weights)\n submission_df = submission.build_submission(test_raw, blend_prediction)\n submission_path = output_dir / \"S01_frozen_v1_blend.csv\"\n submission.write_submission(submission_df, submission_path, expected_rows=len(test_raw))\n\n component_paths = {}\n for name, prediction in predictions.items():\n component_paths[name] = output_dir / f\"S01_{name}_predictions.csv\"\n pd.DataFrame({config.ID_COL: test_raw[config.ID_COL].to_numpy(), config.TARGET: prediction}).to_csv(\n component_paths[name], index=False\n )\n\n metadata = {\n \"submission_id\": S01_ID,\n \"model\": \"Frozen V1 Blend\",\n \"feature_version\": \"frozen production\",\n \"oof_rmse\": 20097389.205713525,\n \"catboost_weight\": S01_WEIGHTS[\"catboost\"],\n \"ridge_weight\": S01_WEIGHTS[\"ridge\"],\n \"elasticnet_weight\": S01_WEIGHTS[\"elasticnet\"],\n \"public_leaderboard_rmse\": None,\n \"leaderboard_rank\": None,\n \"timestamp_utc\": datetime.now(timezone.utc).isoformat(timespec=\"seconds\"),\n \"submission_file\": str(submission_path),\n \"component_files\": {name: str(path) for name, path in component_paths.items()},\n \"fit_method\": \"fit_each_frozen_component_on_all_3493_processed_v1_training_rows\",\n \"catboost_production_iterations_rule\": \"fixed_manifest_value_no_early_stopping\",\n \"manifest_path\": str(manifest_path),\n **timings,\n }\n metadata_path = output_dir / \"S01_metadata.json\"\n metadata_path.write_text(json.dumps(metadata, indent=2), encoding=\"utf-8\")\n return submission_path, metadata_path\n\n\nif __name__ == \"__main__\":\n for path in run():\n print(path)",
"14. Competition Performance vs. Generalization",
"After the clean model and its validation protocol were frozen, a separate competition-optimization stage was used to improve predictions for the specific held-out evaluation set. The exact mechanics are intentionally outside the scope of this article; the important methodological point is that this stage used information available from the competition environment rather than new independently labeled training data.",
"For that reason, the final leaderboard RMSE of approximately ₹2.893M should be treated as competition-specific and potentially overfit to that evaluation set. The appropriate estimate of how the underlying forecasting model would generalize to new restaurants remains the repeated-CV result of roughly ₹20.10M. Keeping those two numbers separate is essential for scientific and business interpretation.",
"In a real forecasting deployment, the competition-optimized layer would not be carried forward unless an equivalent calibration signal were available prospectively. The deployable system would instead use the frozen feature pipeline and ensemble, monitor residuals and distribution drift, and retrain when new actual turnover becomes available.",
"",
"15. Main Assumptions",
"Train and test were assumed to arise from sufficiently similar business processes for cross-validation to be meaningful. No formal covariate-shift correction was applied beyond schema and distribution checks.\n• Registration Number was treated strictly as an identifier and excluded from the clean model because it showed no defensible predictive relationship with turnover.\n• Missing amenity ratings were assumed to be structurally informative when the corresponding service was absent; this drove the availability-flag design.\n• All fitted preprocessing statistics had to be learned on training data and reused unchanged at inference; this was enforced in the pipeline rather than left to analyst discipline.\n• External market data was considered admissible only if it improved repeated validation and ensemble-level performance. Economic plausibility alone was not enough for promotion.",
"16. Business and Modeling Recommendations",
"Treat data quality as model performance. Schema mismatches, city-name fragmentation, and inconsistent categoricals can destroy signal before an algorithm ever sees it.\n• Distinguish ‘missing because unknown’ from ‘missing because the business capability does not exist’. The second case is often a feature, not a nuisance.\n• For highly skewed revenue targets, monitor tail RMSE and squared-error concentration in addition to aggregate RMSE. A few large accounts can determine the financial usefulness of the forecast.\n• Use explicit promotion gates: candidate discovery, independent-seed confirmation, and ensemble substitution. This prevents a one-split improvement from becoming a false champion.\n• Treat agentic AI as an operating model, not as permission for autonomous promotion. Let agents propose, implement, and challenge; keep high-impact model and product decisions at explicit human gates.\n• Keep the system of record outside the chat. Persist datasets, manifests, OOF predictions, experiment ledgers, frozen champions, and promotion decisions so a new agent can resume from evidence rather than reconstructing state from conversation history.\n• Use DEV/UAT/PROD boundaries for ML experimentation. Creativity belongs in DEV; replication and adversarial review belong in UAT; PROD should be deterministic, frozen, and reversible.",
"17. Conclusions and Lessons Learned",
"1. The strongest lesson from this project was not that one algorithm won. It was that disciplined problem framing, data auditing, tail-aware validation, feature engineering, residual diversity, and a controlled agentic workflow created a better forecasting system than model complexity alone. DontPanic made the AI agents useful as a team: they accelerated discovery and implementation, while explicit human-in-the-loop gates prevented speed from replacing judgment.",
"2. The final competition champion reached approximately ₹2.893M RMSE after a separate optimization stage tailored to the evaluation environment. That score was decisive for the competition, but it is intentionally reported separately because it may be overfit and should not be interpreted as the model’s expected error on future restaurants.",
"3. The broader takeaway is practical: build the validation system before tuning the model, preserve failed experiments, promote only replicated gains, and always distinguish a model that wins a benchmark from a model you would trust in production. And if you use multiple AI agents, make them play volleyball: let them volley work aggressively, but make the important decisions come back to a human before the point is scored.",
"Let’s Connect",
"LinkedIn",
"GitHub"
],
"paragraphs.image_id": [
null,
"1*4T_RgTg8k9KF6us7SK0nsw.png",
null,
null,
null,
null,
null,
null,
null,
null,
null,
"1*T3_7F3CoBNTWboCtcYgzGQ.png",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
"1*MNnQePxD6EGd3xeRieXZEA.png",
null,
null,
"1*k3i8Q8FTkFIWG8m4JkRv4g.png",
null,
null,
null,
null,
null,
"1*b5pU6zfUWntlc8HJuaxe9A.png",
null,
null,
null,
"1*I5OBHeIOP6ehu9uOJvZIJw.png",
"1*Zg1yFGqT0G0tQZUON0a3Rw.png",
null,
"1*k0qsfOjm9WKMpm8V5kAzyg.png",
null,
"1*nq2ZPrbsBridwnT1g0JofQ.png",
null,
"1*TOayK3UUu1RMPr4DHjNKew.png",
null,
null,
"1*B-XwgVetgXws07uLzf2yzA.png",
"1*2JGWabQFouBvCC2Ts7ymvA.png",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
"1*OQeEGHb8Y9uEaELdrw3Rmg.png",
null,
null,
null,
"1*qw7M8FVrBl6TdOJb235VQw.png",
null,
"1*_I0ZiHyd1m2AsEA8GtiaXQ.png",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
"1*bi2i-iVCs0cmld8OK8DGVA.png",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
],
"paragraphs.media_url": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
]
}

Medium author posts scraper — complete JSON result

{
"result_type": "profile-posts",
"input": "andymcdonaldgeo",
"status": "success",
"id": "bfd47b63fdae",
"url": "https://andymcdonaldgeo.medium.com/adding-a-geological-facies-display-to-a-well-log-plot-in-matplotlib-and-plotly-bfd47b63fdae",
"title": "Adding a Geological Facies Display to a Well Log Plot in Matplotlib and Plotly",
"text": "",
"text_is_preview": true,
"is_locked": true,
"visibility": "LOCKED",
"creator.id": "9c280f85f15c",
"creator.username": "andymcdonaldgeo",
"creator.name": "Andy McDonald",
"creator.url": "https://andymcdonaldgeo.medium.com/",
"publication.id": null,
"publication.slug": null,
"publication.name": null,
"publication.url": null,
"published_at": "2026-09-13T17:19:32.495000Z",
"updated_at": "2026-09-13T17:19:32.495000Z",
"clap_count": 197,
"response_count": 3,
"voter_count": null,
"reading_time_minutes": 11.204716981132076,
"word_count": null,
"language": null,
"tags": [
"data-visualization",
"python",
"matplotlib",
"plotly",
"data-science"
],
"preview_image_url": "https://miro.medium.com/1*GQNo-A-8MOZSYtIwCfHPgg.png",
"paragraphs.type": [],
"paragraphs.name": [],
"paragraphs.text": [],
"paragraphs.image_id": [],
"paragraphs.media_url": []
}

Medium author profiles scraper — complete JSON result

{
"result_type": "profile",
"input": "https://medium.com/@getpy",
"status": "success",
"id": "bb58ccbf9892",
"url": "https://medium.com/@getpy",
"username": "getpy",
"name": "Get Python",
"bio": "Tweets for Python enthusiasts - by @originalankur",
"domain": null,
"avatar_url": "https://miro.medium.com/0*83Nif76AM9clOzVs.jpg",
"followers_count": 5960,
"following_count": 4,
"publications_following_count": 0,
"is_suspended": false
}

Medium author search scraper — complete JSON result

{
"result_type": "profile-search",
"input": "python",
"status": "success",
"id": "bb58ccbf9892",
"url": "https://medium.com/@getpy",
"username": "getpy",
"name": "Get Python",
"bio": "Tweets for Python enthusiasts - by @originalankur",
"domain": null,
"avatar_url": "https://miro.medium.com/0*83Nif76AM9clOzVs.jpg",
"followers_count": null,
"following_count": null,
"publications_following_count": null,
"is_suspended": null
}

Medium publication search scraper — complete JSON result

{
"result_type": "publication-search",
"input": "python",
"status": "success",
"id": "e796ae996a04",
"url": "https://medium.com/codefile",
"name": "Data Visualization, Data Science and Python",
"domain": null,
"avatar_url": "https://miro.medium.com/1*F4ZU2m6KRWqeNaSKATAAkQ.png",
"slug": "codefile",
"description": "Practical hands-on articles and tutorials about Data…"
}

Images, tags and other lists stay with their parent result instead of creating extra rows. Invalid or unavailable inputs, inputs with no results, and requests that fail after all retries produce a row with status: failed. At most one failed row is saved per input; it includes error_code and error_message explaining the outcome. A normal end of pagination after collected results does not add a failed row.

Input requirements and collection settings ⚙️

SettingWhat to enter
What to collect (mode)Choose the information to collect.
Maximum results per search or link (maxResults)Collect up to this many results for each search or link. Minimum: 1.
Search keywords (searchQueries)Enter one search phrase per line. For Post Search, Profile Search, Publication Search.
Post links (postUrls)Paste one link per line. Example: https://medium.com/@tomaspueyo/coronavirus-the-hammer-and-the-dance-be9337092b56 For Post Clappers, Post Comments, Post.
Profile links (profileUrls)Paste one link per line. Example: https://medium.com/@andymcdonaldgeo For Profile Posts, Profile.
Collection modeFields to use
Post ClappersPost links
Post CommentsPost links
PostPost links
Post SearchSearch keywords
Profile PostsProfile links
ProfileProfile links
Profile SearchSearch keywords
Publication SearchSearch keywords

The result limit applies separately to each search or supplied link. Collection ends earlier when no more matching results are available.

Medium scraping use cases 🎯

Editorial topic research

Find articles addressing a subject and compare their angles and reception.

Writer sourcing

Discover writers with relevant biographies and published work.

Publication discovery

Find publications serving a niche for editorial or partnership research.

Thought-leadership benchmarking

Compare public author catalogs and article engagement.

Reader feedback research

Collect responses and visible clapper profiles around selected articles.

Pricing and saved-result behavior 💰

See the Actor's Pricing tab for the active pricing model and current rate. Store settings may change, so this README does not claim a fixed cost.

Under dataset-item pricing:

  • Each collected item saved in the dataset is one result.
  • Images, tags and other values attached to that item do not create additional rows.
  • Automatic retry attempts do not create extra dataset rows.
  • A saved failed row is also one billable dataset item, including invalid inputs, unavailable items, no results, or exhausted retries. At most one failed row is saved per input, including when some results were already collected.
  • maxResults caps all saved rows for each input, including its failed row. Repeated copies of the same input are processed once. More inputs or a higher limit can produce more saved results.

Medium scraper API and integrations 🔌

Replace $ACTOR_ID with the ID shown in the Actor API tab and $APIFY_TOKEN with your token.

curl -X POST "https://api.apify.com/v2/acts/$ACTOR_ID/runs?token=$APIFY_TOKEN" \
-H "Content-Type: application/json" \
-d '{"mode":"post-search","searchQueries":["python"],"maxResults":10}'

Use schedules for recurring collection, webhooks for completion notifications, and Apify integrations for Google Sheets, Make, Zapier, cloud storage, a CRM or your own application.

Reliability, retries, and public-data limits ⚠️

Temporary connection errors, timeouts and access restrictions are retried automatically, up to five attempts. Invalid inputs save a failed row without an HTTP request; confirmed unavailable items save a failed row without unnecessary retries. Exhausted retries also save a failed row. Results already collected remain available if a later request fails, and normal pagination completion adds no error row. Collection also stops after two consecutive fully processed pages add no new results, even if the website provides another cursor. Required detail lookups are completed before checking a page; new results reset the counter, and independent reply branches are checked separately. Failures while initializing the Actor, saving data or scheduling requests stop the run instead of being reported as a failed website result.

Article text is limited to what visitors can read; member-only content is not unlocked.

Post Comments collects root responses.

Medium controls which information is publicly available. Removed, private or restricted items may be unavailable, and optional values can be null or empty. A run can still fail if the results cannot be saved.

Frequently asked questions ❓

Does it require an account on Medium?

No. You do not need to provide an account, password or login cookies. Only publicly available information is collected.

How does maxResults work?

It limits the number of saved results separately for every input. The minimum is 1. With maxResults set to 10, each input returns at most 10 available results. A detail lookup normally returns one record per input.

Can it collect member-only article text?

It collects the text available to visitors and does not unlock restricted sections.

Can I research readers who clapped?

Post Clappers collects the public reader profiles exposed for a selected article.

Why are some fields empty?

The website may not publish that value, or the field may belong to a different collection mode. Missing values remain null or empty instead of being guessed.

Can I export the results to a spreadsheet?

Yes. Download CSV, Excel or JSON from the Apify dataset. All returned fields are included in the same results table.

Support and responsible use 🛟

For a reproducible issue, share the run ID, selected mode, result limit and a safe public example through the support channel. Never disclose access tokens, passwords or proxy credentials.

Use public Medium information lawfully and responsibly. Follow applicable privacy, copyright, data-protection, contractual and platform requirements when storing, analyzing or redistributing results.