Predicting Apartment Lease Renewals and Categorizing Move-Out Reasons
Medium · Machine Learning · Data Scientist · Technical Screen
Prompt
You are given a 24-hour data science take-home assignment, followed by a 30-minute live technical review where you present your findings and walk through your code. Your goal is two-fold: build a supervised model that estimates whether each apartment resident will renew an expiring lease, and use an unsupervised-to-supervised workflow to uncover and classify the reasons non-renewing residents move out.
Both input sources are already divided into training and test splits:
- Tenant messaging logs (JSON): 1,000 chat transcripts recorded with residents who are deciding whether to extend their leases.
- Property database (SQLite): Three relational tables supplied without a column dictionary, key diagram, or explicit target specification—you must inspect the files directly to identify column meanings, join keys, and where the renewal outcome is stored:
| Table | Summary |
|---|---|
residents |
Per-resident profile and tenancy records |
maintenance_history |
Repair and service requests logged by residents |
renewal_offers |
Proposed lease-extension terms issued per apartment unit |
Complete four connected deliverables:
- Supervised renewal predictor: Join the SQLite tables and chat transcripts at a clearly stated row grain, document your preprocessing and feature engineering, audit every table and transcript for temporal or label leakage, and train a model suited to roughly 1,000 mixed tabular-and-text records.
- Baseline evaluation and test CSV: Choose a performance metric whose random-guess expectation is known, explain why it fits this decision problem, estimate generalization honestly on the training split, and generate a test-set CSV with one row per test resident. Required columns are
resident_id,unit_number, andrenewal_decision, plusprobability_of_renewalif your estimator produces probability scores (reviewers evaluate this file on held-out labels). For example, two illustrative output rows look like:text resident_id,unit_number,renewal_decision,probability_of_renewal RES-401,3B,0,0.18 RES-403,5A,1,0.86 - Move-out reason categorization (
gte-base): Starting with zero labeled reason tags, encode conversation text using thegte-basesentence-transformer model, discover and define a taxonomy of non-renewal reasons, train and validate a reason categorizer, and connect the resulting categories back to structured database attributes. - Technical deep-dive: Package a clean, reproducible Jupyter notebook alongside a concise presentation covering framing, validation results, business insights, limitations, and next steps for the 30-minute live session.
Scope & Expectations
- Systematic schema discovery, explicit row-grain alignment across resident-level and unit-level tables, and rigorous target-leakage checks across structured fields and free-text chats.
- Right-sized feature compression and model selection for a modest tabular-plus-text sample size, with all transformations fit strictly inside training folds.
- Grouped cross-validation with uncertainty estimates, clear comparison against analytical random and base-rate baselines, and verified probability/threshold orientation in the exported CSV.
- Granular tenant-turn embedding with
gte-base, human-curated cluster naming, holdout evaluation without pre-existing labels, and statistically grounded links to structured property records.
Step-by-step walkthrough
Explore the database and lock in one row per resident
Because no schema is provided, your first hour belongs to systematic data discovery—and your notebook should keep this evidence visible because interviewers will ask, "How did you verify what the label means?"
Start by establishing the grain of your modeling table. A table's grain is what a single row represents (for example, one repair ticket, one apartment unit, or one resident). Here, the required test CSV has one row per resident, so your training table must also have one row per resident.
Run four concrete checks before engineering any features:
- Inventory tables and columns: List every table name, row count, and column type in
train.db. - Verify primary and foreign keys: Confirm with counts—not by eye—whether
resident_idis unique inresidentsand whetherrenewal_offershas one row perunit_numberor multiple historical offers across years. - Locate and audit the target label: Find where the renewal outcome lives (such as a
renewedcolumn onresidents, amove_out_date, or anoffer_statusonrenewal_offers). Check its distinct values, missing rate, and whether roommates in the same unit always share the same outcome. - Count unmatched rows with anti-joins: An anti-join finds rows in one table that have no matching key in another. Count residents with no renewal offer, offers with no resident, and JSON conversations that match no known resident or unit.
import sqlite3 import pandas as pd # Connect to the training SQLite database and inspect every table's shape con = sqlite3.connect("train.db") table_names = pd.read_sql( "SELECT name FROM sqlite_master WHERE type = 'table'", con )["name"] for table_name in table_names: row_count = pd.read_sql(f'SELECT COUNT(*) AS n FROM "{table_name}"', con)["n"][0] columns = pd.read_sql(f'PRAGMA table_info("{table_name}")', con)[["name", "type"]] print(f"=== {table_name} ({row_count} rows) ===") print(columns, "\n") residents = pd.read_sql("SELECT * FROM residents", con) offers = pd.read_sql("SELECT * FROM renewal_offers", con) # Verify key uniqueness and how many offers each unit receives print("resident_id unique:", residents["resident_id"].is_unique) print(offers.groupby("unit_number").size().describe())Before joining, roll every table up to the one-row-per-resident spine so no join accidentally duplicates residents:
Source table Raw grain How to bring it to 1 row per resident -------------------- ----------------------- ---------------------------------------------------- residents 1 row per resident Spine table (keep resident_id, unit_number, tenure) maintenance_history 0..N rows per resident Aggregate per resident_id: total tickets, tickets in last 90 days, open tickets, median days to close renewal_offers 1..N rows per unit Filter to the current lease term's offer per unit, then left-join on unit_number (% hike, lead days) conversations (JSON) 0..N chats per tenant Concatenate pre-cutoff tenant turns per resident_id and add a binary has_conversation indicator (0 or 1)For a concrete example, suppose resident
RES-401in unit3Bhas 4 repair tickets (2 in the last 90 days, 1 still open) and one current renewal offer carrying an 8.5% rent increase sent 65 days before lease end. After aggregation,RES-401sits on a single clean row:n_tickets=4, n_tickets_90d=2, n_open=1, rent_increase_pct=8.5, offer_lead_days=65.Two structural details matter right away: - Roommates in the same unit: Two residents sharing unit
3B(RES-401andRES-402) receive the same unit-level renewal offer and usually move or stay together. Keep both rows (the submission requires one row per resident), but keepunit_numberas a grouping key so roommates are never split across training and validation sets. - Missing conversations: With 1,000 conversations total across train and test, some residents may have none. Left-join the text, fill missing text with"", and addhas_conversation(1or0), because reaching out to management can itself signal hesitation.- Inventory tables and columns: List every table name, row count, and column type in
Audit every data source for target leakage
Target leakage happens when a feature contains information recorded after the outcome was decided—or directly encodes the outcome itself—giving unrealistically high validation scores that collapse in real use. Walk through every table and ask: "Would the property team already know this value at the exact moment they run the model?"
Timeline for one lease: [Repair tickets] ---> [Offer sent] ---> [Tenant chats] ---> [PREDICTION CUTOFF] ---> [Final decision & move-out] SAFE SAFE CHECK TIMING! LEAKAGE (exclude!)- Renewal offers: The offered rent, dollar change, percentage increase, and days before lease end are known when the offer goes out—safe. An
offer_statuscolumn ("accepted","declined","signed") is the final outcome and must never be used as an input feature. - Maintenance history: Work orders filed after a non-renewal decision—such as
"move-out inspection","key return", or"turnover repaint"—leak the move-out. Filtermaintenance_historyto tickets created strictly before your prediction cutoff date. - Conversations: Free text is the highest-risk source. Read 20–30 transcripts by hand. If tenants say "I just signed the renewal" or "Here is our 30-day notice, we bought a house", the conversation includes the final decision. State your cutoff assumption explicitly in the notebook, and strip or exclude post-decision messages if timestamps allow.
- Preprocessing leakage: Imputers, scalers, text vocabularies, and dimensionality reduction must learn statistics from the training fold only, never the full dataset. Wrapping every step inside a scikit-learn
Pipelineguarantees each cross-validation fold fits its own preprocessors from scratch.
Run a fast single-source leakage probe on the text alone. TF-IDF (term frequency–inverse document frequency) weights words by how often they appear in one conversation relative to how rare they are across all conversations. If a simple linear model on TF-IDF hits 0.98 AUC using words like
"signed"or"movers", you caught a leaked label:import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline def top_predictive_words(texts, y_renew, n_words=15): """Fit a text-only linear probe to spot giveaway outcome words.""" clean_texts = pd.Series(texts).fillna("") probe = make_pipeline( TfidfVectorizer(min_df=3, stop_words="english"), LogisticRegression(C=1.0, max_iter=1000), ) probe.fit(clean_texts, y_renew) vocab = probe[0].get_feature_names_out() weights = probe[1].coef_[0] sorted_idx = weights.argsort() # Lowest weights push toward 0 (non-renewal); highest push toward 1 (renewal) non_renewal_words = list(vocab[sorted_idx[:n_words]]) renewal_words = list(vocab[sorted_idx[-n_words:]]) return non_renewal_words, renewal_words- Renewal offers: The offered rent, dollar change, percentage increase, and days before lease end are known when the offer goes out—safe. An
Build features and choose a right-sized model
With roughly 1,000 total conversations (say ~800 training rows and ~200 test rows), a model with thousands of free parameters will memorize noise—a problem called overfitting (fitting quirks of the training sample that do not repeat on new data). Keep the feature set compact and well-regularized:
- Tabular features: Include resident attributes (
tenure_months,current_rent), offer terms (rent_increase_pct,offer_lead_days), maintenance summaries (n_tickets,n_tickets_90d,n_open,median_days_to_close), andhas_conversation. Interaction ratios likerent_increase_pctalongsiden_openhelp capture tenants hit by both a steep hike and unresolved repairs. - Text features without drowning tabular signals: Encoding each conversation with
gte-baseyields 768 numbers per row. Feeding 768 dense embedding columns directly alongside 9 tabular columns into a tree model on 800 rows lets noisy embedding dimensions overwhelm the structured features. Two clean ways to prevent this inside each cross-validation fold are:- PCA compression: Use PCA (Principal Component Analysis, a linear projection that keeps the directions of largest variance) inside the pipeline to compress the 768 embedding dimensions down to 10–20 components.
- Out-of-fold stacking: Train a regularized logistic regression on the text/embeddings alone, record its cross-validated renewal probability for each resident, and pass that single summary probability into the tabular model alongside the 9 structured columns.
- Model progression: Always benchmark a simple regularized logistic regression baseline first, then compare a shallow gradient-boosted decision tree (
HistGradientBoostingClassifierwithmax_depth=3and L2 regularization), which naturally captures nonlinear thresholds (for instance, rent hikes above 8% triggering a sharp drop in renewals) and missing values. Skip deep neural networks: ~800 tabular rows are far too few to train them reliably.
from sklearn.compose import ColumnTransformer from sklearn.decomposition import PCA from sklearn.ensemble import HistGradientBoostingClassifier from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline, make_pipeline from sklearn.preprocessing import StandardScaler TABULAR_COLS = [ "tenure_months", "current_rent", "rent_increase_pct", "offer_lead_days", "n_tickets", "n_tickets_90d", "n_open", "median_days_to_close", "has_conversation", ] EMBED_COLS = [f"emb_{i}" for i in range(768)] # Preprocess tabular columns and compress 768-dim embeddings inside each CV fold preprocessor = ColumnTransformer([ ("tab", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), TABULAR_COLS), ("txt", PCA(n_components=15, random_state=0), EMBED_COLS), ]) # Linear baseline: fast, interpretable, and hard to overfit baseline_model = Pipeline([ ("prep", preprocessor), ("clf", LogisticRegression(C=0.5, max_iter=1000)), ]) # Nonlinear contender: shallow boosted trees with strong regularization boosted_model = Pipeline([ ("prep", preprocessor), ("clf", HistGradientBoostingClassifier( max_depth=3, learning_rate=0.05, max_iter=200, l2_regularization=2.0, random_state=0, )), ])- Tabular features: Include resident attributes (
Choose metrics with known baselines
Keep your target coding aligned with the required CSV (
y_renew = 1if the resident renews,0if they leave) so you never invert probabilities by mistake. When evaluating how well the model catches departures, look atp_leave = 1 - p_renewas well, because non-renewals are the rarer event the retention team acts on.Compare standard metrics by what a random uniform scorer (guessing random numbers in
[0, 1]) and a constant base-rate predictor (predicting the overall class average for everyone) achieve when 70% renew and 30% leave (r = 0.30non-renewal rate):Metric What it measures Random / trivial baseline (at 70% renew, 30% leave) ------------------------------ ---------------------------------- --------------------------------------------------- ROC-AUC Pairwise ranking of renew vs leave 0.50 exact (independent of class balance!) PR-AUC (on non-renewal, r=0.3) Precision across recall for leavers ~0.30 (equals the positive class base rate r) Accuracy Fraction of exact 0/1 matches 0.50 fair coin; 0.58 biased coin (0.7^2 + 0.3^2); 0.70 if trivially predicting "everyone renews" Brier score Mean squared error of probabilities 0.333 uniform random [0,1]; mean((y - p)^2), lower is better 0.210 constant base-rate p=0.70 (0.7 * 0.3 = 0.21) Log-loss Cross-entropy penalty on probs 1.000 uniform random [0,1]; 0.611 constant base-rate -(0.7 ln 0.7 + 0.3 ln 0.3)Use ROC-AUC (Area Under the Receiver Operating Characteristic curve: the probability that a randomly chosen renewer receives a higher renewal score than a randomly chosen non-renewer) as the headline metric because its random baseline is always 0.50 regardless of the renewal rate, and it evaluates ranking before picking a cutoff. Pair it with two companion numbers: - PR-AUC on non-renewal (Area Under the Precision-Recall curve, baseline
r = 0.30), which checks whether the highest-risk tenants at the top of the call list are genuinely leaving. - Brier score (mean squared error between0/1outcomes and predicted probabilities, baseliner(1 - r) = 0.21), which checks calibration—whether predicted"80% renewal"residents actually renew about 80% of the time.On a finite dataset of 800 training rows, even pure random noise fluctuates around its theoretical baseline. A quick simulation quantifies that noise floor:
import numpy as np from sklearn.metrics import average_precision_score, roc_auc_score rng = np.random.default_rng(0) random_aucs = [] random_pr_aucs = [] for _ in range(2000): y_renew = (rng.random(800) < 0.70).astype(int) # 70% renew, 30% leave noise_prob = rng.random(800) # model that knows nothing random_aucs.append(roc_auc_score(y_renew, noise_prob)) random_pr_aucs.append(average_precision_score(1 - y_renew, 1 - noise_prob)) # Mean ~0.50 (std ~0.021) for ROC-AUC; mean ~0.30 (std ~0.021) for non-renewal PR-AUC print(f"Random ROC-AUC: {np.mean(random_aucs):.3f} +/- {np.std(random_aucs):.3f}") print(f"Random PR-AUC: {np.mean(random_pr_aucs):.3f} +/- {np.std(random_pr_aucs):.3f}")With a standard deviation of
0.021, a model scoring0.53ROC-AUC on 800 rows is barely 1.4 standard deviations above pure guessing—you want clear separation well above that noise band.Cross-validate by unit, set thresholds, and verify the CSV
Evaluate on the training split using 5-fold StratifiedGroupKFold: - Stratified keeps the ~70% renewal rate balanced in every validation fold. - Grouped by
unit_numberforces roommates in the same apartment into the same fold so shared rent hikes and shared move-out decisions never leak across train and validation.Wrong (Random K-Fold): Unit 3B RES-401 -> Train | Unit 3B RES-402 -> Val (LEAKS!) Right (Grouped K-Fold): Unit 3B RES-401 & RES-402 both -> Train (Fold 1..4) or both -> Val (Fold 5)Collect out-of-fold (OOF) predictions—where every training resident's probability is predicted by the model trained on the 4 folds that excluded their unit—and compute a 95% bootstrap confidence interval (resampling residents with replacement 1,000 times to measure estimation spread). On 800 rows (560 renewals, 240 non-renewals), an AUC around
0.80has a standard error of roughly0.019, giving a 95% interval of[0.76, 0.84]. Two models differing by0.008AUC are statistically tied; prefer the simpler one.import numpy as np from sklearn.metrics import roc_auc_score from sklearn.model_selection import StratifiedGroupKFold, cross_val_predict def evaluate_oof(model, X, y_renew, unit_groups, seed=0, n_boot=1000): """Compute unit-grouped out-of-fold ROC-AUC and a 95% bootstrap interval.""" y_array = np.asarray(y_renew) cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=seed) # Column 1 is P(y_renew == 1), matching probability_of_renewal directly oof_prob_renew = cross_val_predict( model, X, y_array, groups=unit_groups, cv=cv, method="predict_proba" )[:, 1] rng = np.random.default_rng(seed) boot_scores = [] for _ in range(n_boot): sample_idx = rng.integers(0, len(y_array), size=len(y_array)) if 0 < y_array[sample_idx].sum() < len(sample_idx): boot_scores.append(roc_auc_score(y_array[sample_idx], oof_prob_renew[sample_idx])) ci_low, ci_high = np.percentile(boot_scores, [2.5, 97.5]) return roc_auc_score(y_array, oof_prob_renew), (ci_low, ci_high), oof_prob_renewKeep two distinct thresholds separate in your write-up, and tune both on out-of-fold predictions (never on the test set): 1. Submission threshold (
renewal_decisionin the CSV): Match the exact label format in the training data (0/1or text string). Pickrenewal_thresholdon calibrated OOF probabilities to optimize the graders' likely hard-label metric (0.50for accuracy, or the threshold maximizing F1). If boosted-tree probabilities look S-shaped on a calibration curve, wrap the classifier inCalibratedClassifierCV. 2. Business retention threshold (who the leasing office calls): Outreach is an economic decision. Suppose a retention call or concession offer costsC = $100, losing a tenant costsV = $2,000in turnover/vacancy, and outreach saves a departing tenant with probabilitys = 0.25(assuming outreach does not push happy tenants away). Calling pays off wheneverP(leave) × s × V > C, which givesP(leave) > 100 / (0.25 × 2000) = 0.20—so you contact anyone withprobability_of_renewal < 0.80, far more inclusive than0.50.Finally, refit the winning pipeline on 100% of the training data, generate the test CSV, and run strict assertions before saving:
def verify_submission_df(sub, test_residents, renewal_threshold=0.50): """Catch silent schema, ID-alignment, or inverted-probability bugs before export.""" expected_cols = ["resident_id", "unit_number", "renewal_decision", "probability_of_renewal"] assert list(sub.columns) == expected_cols assert len(sub) == len(test_residents) assert sub["resident_id"].is_unique assert set(sub["resident_id"]) == set(test_residents["resident_id"]) assert sub["probability_of_renewal"].between(0.0, 1.0).all() # Confirm hard decisions match probability_of_renewal and threshold consistently expected_decision = (sub["probability_of_renewal"] >= renewal_threshold).astype(int) assert (sub["renewal_decision"] == expected_decision).all()Discover and validate non-renewal reasons with gte-base
Part 3 starts with no reason labels, so you combine unsupervised representation discovery with human taxonomy design and supervised classification.
- Extract tenant-only reason segments: Strip out the leasing agent's turns first—agent greetings and scripted prompts appear in every chat and would make clusters group by script template rather than tenant grievances. Next, split tenant messages into individual sentences or short turns rather than embedding whole conversations:
- One tenant often gives multiple reasons ("The 9% increase is too steep, and our upstairs neighbor is loud"); averaging an entire chat blurs two clear reasons into one muddled midpoint.
thenlper/gte-basehas a 512-token input limit and truncates anything longer.
- Embed with L2 normalization: An embedding maps each text snippet into a 768-number vector where similar meanings land close together. Setting
normalize_embeddings=Truescales every vector to length 1, so cosine similarity (the cosine of the angle between two vectors) equals their simple dot product—for example, unit vectors(0.6, 0.8)and(0.8, 0.6)have cosine similarity0.6 × 0.8 + 0.8 × 0.6 = 0.96. Even better, for unit vectors, squared Euclidean distance||u - v||² = 2 - 2(u · v)is strictly proportional to cosine distance, so standardKMeansclusters by cosine similarity automatically! - Cluster across
kand curate categories by reading: Run k-means fork = 4..15on segments from non-renewers, logging the silhouette score (a-1to+1measure of how tight each cluster is compared with neighboring clusters). Never pickkby silhouette score alone: inspect the 15 segments closest to each cluster center plus 10 random members, name coherent themes (e.g., Rent Increase, Unresolved Maintenance, Space / Unit Layout, Relocation / Home Purchase, Noise / Safety), merge redundant clusters that management would act on identically, and include an Other / Unclear category. - Train and validate the categorizer: Hand-verify ~30–50 segments per named category to clean noisy cluster assignments, then train a regularized multinomial
LogisticRegressionon the 768-dimgte-basevectors (using multi-label binary classifiers if a single sentence frequently states two reasons, or aggregating predicted sentence categories up to a multi-label set per resident). To validate honestly without starting labels, hold out 150–200 segments untouched during clustering/training and have two people label them independently. Report Cohen's kappa (inter-rater agreement adjusted for chance) between the two humans to verify the taxonomy is clear, plus macro-F1 (the unweighted average of F1 scores across all categories, giving small categories equal weight) and the confusion matrix of the trained classifier against the human gold labels.
from sentence_transformers import SentenceTransformer from sklearn.cluster import KMeans from sklearn.linear_model import LogisticRegression from sklearn.metrics import f1_score, silhouette_score # 1. Encode tenant-only sentence segments into unit-length 768-d vectors encoder = SentenceTransformer("thenlper/gte-base") vectors = encoder.encode(tenant_segments, normalize_embeddings=True, batch_size=32) # 2. Sweep cluster counts k to guide (not replace) human inspection silhouette_by_k = {} for k in range(4, 16): cluster_ids = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(vectors) silhouette_by_k[k] = silhouette_score(vectors, cluster_ids, metric="cosine") # 3. After curating category names & cleaning a training set, fit the categorizer # and evaluate on a strictly held-out, human-labeled validation split categorizer = LogisticRegression(C=1.0, max_iter=1000) categorizer.fit(X_train_vec, y_train_cat) val_preds = categorizer.predict(X_holdout_vec) print("Holdout Macro-F1:", f1_score(y_holdout_human, val_preds, average="macro"))- Extract tenant-only reason segments: Strip out the leasing agent's turns first—agent greetings and scripted prompts appear in every chat and would make clusters group by script template rather than tenant grievances. Next, split tenant messages into individual sentences or short turns rather than embedding whole conversations:
Link categories to structured data and structure the deep-dive
Reason categories create business value when connected back to the SQLite tables to separate controllable friction from uncontrollable churn: - Price complaints vs
rent_increase_pct: Check how sharply price-reason prevalence rises across rent-hike brackets (<3%,3–6%,>6%). - Maintenance complaints vsn_openandmedian_days_to_close: Verify whether tenants citing property quality actually waited longer for repairs inmaintenance_history. - Life events (job relocation, buying a home) vstenure_months/ unit size: Flagging uncontrollable reasons saves the leasing team from wasting rent concessions on tenants moving out of state.Back every claim with a statistical check rather than eyeballing bar charts. For example, suppose among 160 non-renewers, 36 of 80 (
45%) facing a rent hike above 6% cite Rent Increase, compared with 16 of 80 (20%) facing a hike of 6% or less: - Pooled proportion:p_pool = (36 + 16) / 160 = 52 / 160 = 0.325- Standard error of difference:SE = √(0.325 × 0.675 × (1/80 + 1/80)) = √0.005484375 ≈ 0.0741- Two-proportion z-statistic:z = (0.45 - 0.20) / 0.0741 ≈ 3.38(two-sidedp < 0.001)Frame these carefully as observational associations, not causal elasticities, and adjust for multiple testing (such as Benjamini–Hochberg false discovery rate) if scanning many category-feature pairs.
For the 30-minute deep-dive, keep slides to 12–15 minutes so at least half the slot stays open for live Q&A in the notebook:
Minutes Slide / Notebook Section Key Question Answered & Ready Evidence Cell ------- ------------------------------ ------------------------------------------------------------ 0 - 2 1. Objective & Decision Timing Who uses the score, at what cutoff date, and for what action 2 - 4 2. Schema, Grain & Label Audit 1 row/resident join diagram, orphan counts, label verification 4 - 6 3. Leakage Review What was excluded (offer status, late tickets/chats) & probe 6 - 9 4. Model, Metrics & Thresholds Unit-grouped OOF ROC-AUC/PR-AUC/Brier +/- CI vs baselines 9 - 12 5. gte-base Reason Taxonomy Tenant-turn clustering, k selection, quotes, human holdout F1 12 - 15 6. Structured Insights & Next Tested table links, honest sample-size/timing caveats 15 - 30 Live Q&A in Jupyter Notebook Clean top-to-bottom run, cached embeddings, fixed seedsBefore submitting, cache
gte-baseembeddings to disk so the notebook reruns from a fresh kernel (Restart & Run All) in under two minutes with fixed random seeds and zero hidden state.
Intuition & how it works
Think of this take-home like helping an apartment manager review tenant folders 60 days before leases expire. For each resident, you gather a single summary sheet combining their rent-increase notice, past repair tickets, and chat messages as of that pre-decision date, rank who is most at risk of moving out (Part 1 & Part 2), and group past departing tenants' complaints by theme to understand why people leave (Part 3).
The obvious approach—joining all SQLite tables directly, throwing raw 768-dimensional chat embeddings and structured columns into a complex model with random K-fold splits, and reporting accuracy—fails in three quiet ways. First, joining raw repair tickets or multi-year offers multiplies rows for frequent callers and duplicates residents. Second, random splits place roommates from the same apartment on opposite sides of train and validation, while late conversations ("just signed the renewal!") leak the final answer—making validation look near-perfect while test-set predictions crash. Third, when 70% of tenants renew, a useless model that predicts "everyone renews" already scores 70% accuracy.
Walk through a tiny 4-resident miniature to see how the disciplined pipeline works instead:
- Fix the grain (1 row per resident): Residents RES-401 and RES-402 are roommates in Unit 3B (8.5% rent hike; RES-401 logged 4 repair tickets with 1 open HVAC issue and chatted "An 8.5% jump while our AC still rattles is tough"). RES-403 lives in Unit 5A (2% hike, 0 tickets, no chat). RES-404 lives in Unit 7C (7% hike, 0 tickets, chatted "Relocating to Seattle next month for work"). Each resident becomes one aggregated row with has_conversation (1, 1, 0, 1), keeping only pre-decision records.
- Evaluate honestly against random: Unit-grouped cross-validation keeps RES-401 and RES-402 together in the same fold. Out-of-fold renewal probabilities (RES-401: 0.18, RES-402: 0.24, RES-404: 0.29, RES-403: 0.86) rank the true renewer (RES-403) above the non-renewers (ROC-AUC = 1.00 vs 0.50 for random guessing) and match renewal_decision cleanly in the exported CSV.
- Categorize reasons from tenant sentences: Splitting tenant-only turns into short sentences and encoding them with gte-base maps RES-401's clause "8.5% jump" into a Rent Increase cluster, "AC still rattles" into Maintenance, and RES-404's "Relocating to Seattle" into Relocation—separating issues management can fix from moves no discount would prevent.
Key points
- Lock in the grain before joining: Because the test CSV has one row per
resident_id, rollmaintenance_historyup per resident, pick the current lease term's offer perunit_numberfromrenewal_offers, and aggregate pre-decision chat turns per resident (adding ahas_conversationindicator). - Verify keys, labels, and orphans explicitly: Show programmatic checks for key uniqueness, missing values, and unmatched rows (anti-joins, meaning rows in one table with no match in another) in the first section of your notebook.
- Audit every feature source for target leakage: Target leakage (feeding future or outcome-derived data into features) hides in offer statuses (
"signed"), post-decision move-out work orders, and late chat messages stating the final decision. Fit all scalers, TF-IDF vocabularies, and PCA (Principal Component Analysis, compressing correlated columns into top variance directions) inside a scikit-learnPipelineper fold. - Right-size the model for ~800 training rows: Benchmark regularized logistic regression against shallow gradient-boosted trees (
max_depth=3), and compress 768-dimensional embeddings (via PCA to ~10–20 components or out-of-fold text probabilities) so text vectors do not drown out a handful of high-signal tabular columns. - Benchmark against explicit random and base-rate baselines: ROC-AUC (probability of ranking a random renewer above a random non-renewer) always scores
0.50for random noise; PR-AUC (Area Under the Precision-Recall curve) on non-renewals scores roughly the non-renewal rater; Brier score (mean squared probability error) scores0.333for uniform random numbers andr(1 - r)for always predicting the constant base rate. - Group by unit, quantify uncertainty, and separate the two thresholds: Use
StratifiedGroupKFoldgrouped byunit_numberand report a 95% bootstrap confidence interval (resampling out-of-fold predictions with replacement; roughly±0.04AUC atn = 800). Tune the CSVrenewal_decisioncutoff on out-of-fold metrics, keep it distinct from the business outreach cutoff (P(leave) × save_rate × vacancy_cost > call_cost), and assert exact column alignment and probability orientation (probability_of_renewal) before saving. - Embed tenant sentences, curate clusters, then validate on human labels: Encode tenant-only sentence segments with
thenlper/gte-base(normalize_embeddings=Trueso Euclidean k-means matches cosine similarity), combine silhouette scores with reading cluster examples to name actionable categories, train a fast linear classifier on the embeddings, and validate on a untouched human-labeled holdout set with macro-F1 (unweighted mean F1 across classes) and Cohen's kappa (chance-adjusted agreement between two human labelers). - Test structured links as associations, not causes: Connect categories to rent hikes and open tickets with two-proportion tests or regressions, while reminding stakeholders that observational correlations do not prove causal retention lift.
Common mistakes
- Row multiplication during joins: Joining raw
maintenance_historyor multi-yearrenewal_offersdirectly ontoresidentsduplicates tenants, corrupts training weights, and breaks the required one-row-per-resident CSV shape. - Inverted probability or mismatched threshold orientation: Training with
1 = non-renewalinternally and forgetting to convert1 - p(or flipping>=vs>at ties) when writingprobability_of_renewalsilently tanks test-set AUC below0.50(worse than random!). - Splitting roommates across random K-fold: Standard
StratifiedKFoldputs two roommates from Unit3Binto train and validation simultaneously, leaking unit-level rent hikes and shared move-out plans. - Blindly embedding entire chat transcripts (including the agent): Leasing-agent scripts dominate cluster similarity, multi-reason tenants get averaged into mush, and messages past token 512 are silently truncated by
gte-base. - Reporting accuracy alone on imbalanced renewals: Scoring 73% accuracy sounds decent until a reviewer asks what the renewal rate is and points out that predicting
1for every row scores 70%. - Validating the reason classifier against its own k-means cluster IDs: High accuracy against raw k-means assignments only proves logistic regression can trace linear boundaries between k-means centroids—it says nothing about whether those clusters match real human-meaningful reasons.
Follow-up questions
-
What changes if you need to score churn risk several months ahead of lease expiration, before renewal terms go out or any chat takes place? Strip every feature generated during the renewal window (offered rent hike, offer lead time, renewal chats) and rebuild each training row as a strict point-in-time snapshot—for example, "as of 120 days before lease expiration." Use only features available on that date: current rent relative to comparable units in the building, prior renewal count, tenure, payment history, and maintenance tickets logged before day
-120. Expect a noticeably lower AUC without rent-hike and conversation signals, quantify that exact gap by comparing the early-warning model against the renewal-window model, or frame the problem with survival analysis (modeling time until move-out while accounting for leases still in progress). -
How can you verify that your discovered move-out taxonomy stays consistent across different random seeds and alternative cluster counts? Run k-means across multiple random seeds and bootstrap resamples of the segments, then measure pairwise cluster agreement using the adjusted Rand index (ARI) (a
0to1score measuring how consistently pairs of points land together or apart across two clusterings, where1.0means identical partitions and0.0means random chance). Across neighboring values ofk(such ask = 6vsk = 8), inspect a cross-tabulation matrix to check hierarchical nesting—splitting one broad cluster cleanly into two sub-themes rather than reshuffling every category—and confirm matched cluster centroids keep high cosine similarity (> 0.90). Any cluster that fractures across seeds or resamples should be merged or folded into Other.
```python from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score
def seed_stability_ari(vectors, k, seeds=range(10)): """Average pairwise adjusted Rand index across k-means random seeds.""" partitions = [ KMeans(n_clusters=k, n_init=1, random_state=seed).fit_predict(vectors) for seed in seeds ] pair_scores = [] for i in range(len(partitions)): for j in range(i + 1, len(partitions)): pair_scores.append(adjusted_rand_score(partitions[i], partitions[j])) return sum(pair_scores) / len(pair_scores) ```
-
Suppose your held-out evaluation score from the reviewers drops sharply compared to your local cross-validation estimate—how would you debug the gap? Check fast mechanical bugs first: inverted
probability_of_renewal(P(leave)instead ofP(renew)), misalignedresident_idrow order after a join or sort, or0/1vs string label mismatch inrenewal_decision. Second, audit hidden leakage that slipped past cross-validation—such as preprocessors or embeddings fit on the whole dataset, roommates split across folds, or training chats containing post-decision phrases while test chats were truncated earlier. Third, test for covariate shift (a change in input distributions between train and test, such as test leases coming from a later season with steeper rent hikes) by training an adversarial classifier to distinguish train rows from test rows (AUC >> 0.50flags a shift). Finally, check sample-size variance: on ~200 test residents, the standard error of an0.80AUC is nearly0.04, so a0.04dip is well within normal sampling noise. -
Could outputs from the move-out reason classifier be added as features in the renewal predictor, and what data-leakage pitfalls could arise? Predicted category probabilities per resident (such as
prob_mentions_priceorprob_mentions_maintenance) make compact, interpretable text features that beat 768 raw embedding numbers and give the leasing team a clear explanation alongside every risk score. However, this creates severe target leakage if categories were discovered exclusively on known non-renewers or extracted from late exit conversations—because "expressed a non-renewal reason" then acts as a proxy for "already decided to leave." To feed categories back safely, restrict inputs strictly to pre-decision messages from all residents (renewers and non-renewers alike), include a No Complaint / Neutral Inquiry class, and fit the clustering and categorizer inside each training fold before scoring validation or test folds.
Follow-up questions
- What changes if you need to score churn risk several months ahead of lease expiration, before renewal terms go out or any chat takes place?
- How can you verify that your discovered move-out taxonomy stays consistent across different random seeds and alternative cluster counts?
- Suppose your held-out evaluation score from the reviewers drops sharply compared to your local cross-validation estimate—how would you debug the gap?
- Could outputs from the move-out reason classifier be added as features in the renewal predictor, and what data-leakage pitfalls could arise?
Similar questions
- Auditing Uniformity of Naive Swap Shuffles
- Critiquing an Engineering Practice From a Past Team
- Weighing Architectural Trade-Offs and Introducing Peer Review Habits
- Opening Engineering Introduction and Next-Role Priorities
- Code Review of an In-Place Random List-Swap Function
- Presenting a Past System, Key Trade-Offs, and Hardest Challenge
More EliseAI interview questions
- Critiquing an Engineering Practice From a Past Team Easy
- Opening Engineering Introduction and Next-Role Priorities Easy
- Code Review of an In-Place Random List-Swap Function Easy Pro
- Presenting a Past System, Key Trade-Offs, and Hardest Challenge Easy Pro
- Auditing Uniformity of Naive Swap Shuffles Medium Pro
- Weighing Architectural Trade-Offs and Introducing Peer Review Habits Medium Pro