1 Introduction

New York City’s 311 service provides a structured record of non-emergency service requests. Automatically classifying complaint descriptions could support analysis and routing, but evaluating a classifier requires careful attention to repeated text. This project trains supervised document classifiers on labeled NYC 311 descriptions and predicts categories for withheld documents and manually written examples.

Research question: How does repeated text affect the performance and generalizability of machine learning models when classifying NYC 311 complaints?

I compare a conventional stratified random record split with a grouped split that prevents identical normalized descriptions from appearing in both training and testing. The expectation is that random testing will yield higher performance because many standardized descriptions recur.

2 Data acquisition and validation

The source is NYC Open Data: 311 Service Requests from 2020 to Present. The Socrata CSV endpoint is https://data.cityofnewyork.us/resource/erm2-nwe9.csv. An initial 100-record connectivity test succeeded; a larger 50,000-record request returned HTTP 503. The revised acquisition script requested the first 5,000 records of each month in 2025, ordered by creation date and complaint ID, with retries and validation. These are not random monthly samples and should not be interpreted as representative annual complaint frequencies.

show(data.frame(field=names(raw),missing=sapply(raw,function(x) sum(is.na(x)|trimws(x)==''))),row.names=FALSE)
field missing
unique_key 0
created_date 0
complaint_type 0
descriptor 216
descriptor_2 34198
location_type 7011
borough 0
stopifnot(!anyDuplicated(raw$unique_key))
print(dim(raw)); print(range(raw$created_date))
## [1] 60000     7
## [1] "2025-01-01T00:00:12.000" "2025-12-01T11:51:00.000"
show(as.data.frame(table(month=substr(raw$created_date,1,7))))
month Freq
2025-01 5000
2025-02 5000
2025-03 5000
2025-04 5000
2025-05 5000
2025-06 5000
2025-07 5000
2025-08 5000
2025-09 5000
2025-10 5000
2025-11 5000
2025-12 5000

The predictors are descriptor and descriptor_2 only. The original complaint_type supplies the target mapping. IDs, borough, location and post-resolution information are not model features. Public descriptors are standardized selections, not original citizen-written narratives.

3 Exploratory data analysis

cat('Original complaint types:',length(unique(raw$complaint_type)))
## Original complaint types: 163
top <- head(sort(table(raw$complaint_type),decreasing=TRUE),12)
par(mar=c(4,13,2,1)); barplot(rev(top),horiz=TRUE,las=1,col='#287a9b',xlab='Records',main='Most frequent original complaint types')

normalize <- function(x) {x[is.na(x)] <- ''; tolower(trimws(x))}
doc <- trimws(gsub('[[:space:]]+',' ',paste(normalize(raw$descriptor),normalize(raw$descriptor_2))))
labels <- toupper(trimws(raw$complaint_type))
amb <- tapply(labels,doc,function(x) length(unique(x)))
show(data.frame(metric=c('Unique document values (including blank)','Repeated occurrences beyond first','Empty documents','Document values with multiple labels'),count=c(length(unique(doc)),sum(duplicated(doc)),sum(doc==''),sum(amb>1))))
metric count
Unique document values (including blank) 1173
Repeated occurrences beyond first 58827
Empty documents 216
Document values with multiple labels 41
show(head(as.data.frame(sort(table(doc),decreasing=TRUE)),10))
doc Freq
loud music/party 9046
blocked hydrant 3059
posted parking sign violation 2359
no access 2120
banging/pounding 2109
n/a 1467
blocked sidewalk 1423
entire building no heat 1317
loud talking 1295
with license plate 1156

Identical descriptions such as loud music/party can occur under several original complaint types. Repeated descriptions are not duplicate service requests: each retained record has its own ID. This distinction motivates retaining the records while explicitly testing for text overlap.

4 Preprocessing and category mapping

The analysis focuses on seven broad categories. Labels are normalized to uppercase, descriptors to lowercase, whitespace is collapsed, and placeholder-only fields (such as N/A or unknown) are removed. Records outside the selected mapping and records with no remaining text are excluded. The mapping is an analytical choice rather than an official NYC taxonomy.

map <- read_data('data/processed/category_mapping.csv')
show(aggregate(complaint_type~category,map,paste,collapse='; '))
category complaint_type
Abandoned Vehicles ABANDONED VEHICLE; DERELICT VEHICLES
Heating HEAT/HOT WATER; NON-RESIDENTIAL HEAT
Noise NOISE; NOISE - RESIDENTIAL; NOISE - COMMERCIAL; NOISE - STREET/SIDEWALK; NOISE - VEHICLE; NOISE - HELICOPTER; NOISE - PARK; NOISE - HOUSE OF WORSHIP
Parking ILLEGAL PARKING; BLOCKED DRIVEWAY; BROKEN PARKING METER
Road Infrastructure STREET CONDITION; TRAFFIC SIGNAL CONDITION; SIDEWALK CONDITION; STREET LIGHT CONDITION; CURB CONDITION; STREET SIGN - DAMAGED; STREET SIGN - DANGLING; STREET SIGN - MISSING; HIGHWAY CONDITION
Sanitation UNSANITARY CONDITION; DIRTY CONDITION; MISSED COLLECTION; ILLEGAL DUMPING
Water and Plumbing PLUMBING; WATER SYSTEM; WATER LEAK; SEWER; SEWER MAINTENANCE; WATER MAINTENANCE; INDOOR SEWAGE
show(data.frame(stage=c('Original','Outside selected scope','Empty after cleaning within scope','Retained'),records=c(nrow(raw),sum(!labels %in% map$complaint_type),sum(labels %in% map$complaint_type)-nrow(clean),nrow(clean))))
stage records
Original 60000
Outside selected scope 15795
Empty after cleaning within scope 51
Retained 44154
ct <- sort(table(clean$category),decreasing=TRUE)
show(data.frame(category=names(ct),records=as.integer(ct),share=pct(as.numeric(ct)/sum(ct))))
category records share
Noise 14447 32.72%
Parking 12668 28.69%
Sanitation 4809 10.89%
Heating 3774 8.55%
Water and Plumbing 3431 7.77%
Road Infrastructure 3127 7.08%
Abandoned Vehicles 1898 4.30%
par(mar=c(4,13,2,1)); barplot(rev(ct),horiz=TRUE,las=1,col='#287a9b',xlab='Records',main='Retained complaint categories')

amb2 <- tapply(clean$category,clean$document,function(x) length(unique(x)))
show(data.frame(metric=c('Unique descriptions','Repeated occurrences','Ambiguous descriptions','Empty descriptions'),count=c(length(unique(clean$document)),sum(duplicated(clean$document)),sum(amb2>1),sum(clean$document==''))))
metric count
Unique descriptions 378
Repeated occurrences 43776
Ambiguous descriptions 0
Empty descriptions 0

The observed corpus contains 44,154 retained records but only 378 distinct descriptions. No ambiguous description values remain after filtering and grouping. This does not establish that the text is independent of the target: the standardized descriptor choices themselves depend on complaint type.

5 Experimental design

Experiment A uses a stratified random approximately 80/20 record split. Experiment B assigns entire normalized description groups to one partition. The grouped split searches 2,000 seeded candidate assignments for class and row balance without considering model performance. Exact 80/20 balance is not guaranteed. Both use seed 607.

splits <- lapply(c('random','grouped'),function(e){
 tr <- read_data(paste0('data/processed/',e,'_train.csv')); te <- read_data(paste0('data/processed/',e,'_test.csv'))
 stopifnot(!anyDuplicated(c(tr$unique_key,te$unique_key)),setequal(c(tr$unique_key,te$unique_key),clean$unique_key),setequal(tr$category,te$category))
 overlap <- intersect(tr$document,te$document)
 if(e=='grouped') stopifnot(length(overlap)==0)
 data.frame(experiment=e,train=nrow(tr),test=nrow(te),test_share=pct(nrow(te)/nrow(clean)),shared_descriptions=length(overlap),seen_test_records=sum(te$document %in% tr$document))
})
show(do.call(rbind,splits))
experiment train test test_share shared_descriptions seen_test_records
random 35320 8834 20.01% 240 8822
grouped 36676 7478 16.94% 0 0

The random test contains 8,822 previously seen descriptions among 8,834 records. Grouped testing has no exact description overlap. Different test distributions and vocabulary coverage mean the performance gap is descriptive, not a controlled causal estimate of duplication alone.

6 Feature extraction

Each training partition independently determines its unigram vocabulary. Punctuation is replaced with spaces; short words and negation are retained. Bag of Words counts token occurrences. TF-IDF uses recognized-token relative frequency and smoothed inverse document frequency:

\[\mathrm{TFIDF}(t,d)=\frac{c(t,d)}{\max(1,\sum_{v\in V}c(v,d))}\left[\log\frac{1+N}{1+DF(t)}+1\right].\]

Here \(V\) is the training vocabulary, \(N\) is the number of training records and \(DF(t)\) is training document frequency. Unseen test words are ignored; all-zero vectors remain in evaluation.

coverage <- do.call(rbind,lapply(c('random','grouped'),function(e){
 f <- readRDS(paste0('data/features/',e,'_features.rds'))
 te <- read_data(paste0('data/processed/',e,'_test.csv'))
 tokens <- lapply(strsplit(trimws(gsub('[^[:alnum:]]+',' ',tolower(te$document))),' ',fixed=TRUE),function(t)t[nzchar(t)])
 stopifnot(identical(te$unique_key,f$test_id))
 data.frame(experiment=e,vocabulary=length(f$vocabulary),unseen_tokens=sum(vapply(tokens,function(t)sum(!t %in% f$vocabulary),integer(1))),total_tokens=sum(lengths(tokens)),zero_vectors=sum(f$zero_test),coverage=pct(mean(!f$zero_test)))
}))
show(coverage); gc(verbose=FALSE)
experiment vocabulary unseen_tokens total_tokens zero_vectors coverage
random 462 1 28755 0 100.00%
grouped 413 8741 22470 2860 61.75%
##           used (Mb) gc trigger  (Mb) max used  (Mb)
## Ncells  771628 41.3    1463745  78.2  1339393  71.6
## Vcells 2293957 17.6   39127587 298.6 48909089 373.2

7 Classification models

The majority-class baseline predicts the most frequent training category. Multinomial Naive Bayes uses word counts, empirical class priors and Laplace smoothing of 1. For each class it scores the log prior plus the sum of token counts multiplied by log conditional word probabilities. Multinomial logistic regression uses TF-IDF with ridge regularization (glmnet, alpha = 0, lambda = 0.01, standardize = FALSE). These fixed settings were chosen before test evaluation; no test-set hyperparameter tuning was performed.

Accuracy measures the fraction of correct predictions. Precision measures correctness among predictions for a class; recall measures recovery of actual class members. F1 is their harmonic mean, and macro F1 averages F1 equally across all seven classes. Undefined precision is set to zero. Unique-description accuracy gives each distinct test description equal weight rather than each record.

8 Model evaluation

show(transform(comparison,accuracy=pct(accuracy),macro_f1=pct(macro_f1),unique_document_accuracy=pct(unique_document_accuracy),zero_feature_accuracy=ifelse(is.na(zero_feature_accuracy),'N/A',pct(zero_feature_accuracy)),recognized_accuracy=pct(recognized_accuracy)))
experiment model accuracy macro_f1 unique_document_accuracy zero_feature_accuracy recognized_accuracy
random Baseline 32.71% 7.04% 8.76% N/A 32.71%
random Naive_Bayes 99.00% 98.34% 96.81% N/A 99.00%
random Logistic_Regression 99.09% 98.83% 91.24% N/A 99.09%
grouped Baseline 31.60% 6.86% 10.67% 73.74% 5.50%
grouped Naive_Bayes 77.37% 66.55% 81.33% 73.74% 79.62%
grouped Logistic_Regression 75.54% 67.13% 76.00% 73.74% 76.66%
mat <- xtabs(accuracy~experiment+model,comparison)
barplot(mat,beside=TRUE,col=c('#c58a42','#287a9b'),ylim=c(0,1.15),ylab='Accuracy',legend.text=rownames(mat),args.legend=list(x='topright',bty='n'),names.arg=c('Baseline','Logistic regression','Naive Bayes'))

Both classifiers outperform the majority baseline. Random accuracy is approximately 99% for both, but grouped accuracy falls to 77.37% for Naive Bayes and 75.54% for logistic regression. Logistic regression has slightly higher grouped macro F1 (67.13% versus 66.55%), so the preferred model depends on the metric. Naive Bayes has higher grouped unique-description accuracy (81.33% versus 76%).

for(e in c('random','grouped')) for(m in c('Naive_Bayes','Logistic_Regression')) {
 cat('\n\n### ',e,' — ',gsub('_',' ',m),'\n\n',sep='')
 cm <- read.csv(paste0('data/results/',e,'_',m,'_confusion.csv'),row.names=1,check.names=FALSE)
 print(knitr::kable(cm,caption='Rows: actual category; columns: predicted category'))
 cat('\n\n')
}

8.0.1 random — Naive Bayes

Rows: actual category; columns: predicted category
Abandoned Vehicles Heating Noise Parking Road Infrastructure Sanitation Water and Plumbing
Abandoned Vehicles 380 0 0 0 0 0 0
Heating 0 755 0 0 0 0 0
Noise 0 0 2887 0 0 3 0
Parking 58 0 0 2469 1 6 0
Road Infrastructure 1 0 0 5 620 0 0
Sanitation 0 0 0 0 0 962 0
Water and Plumbing 0 14 0 0 0 0 673

8.0.2 random — Logistic Regression

Rows: actual category; columns: predicted category
Abandoned Vehicles Heating Noise Parking Road Infrastructure Sanitation Water and Plumbing
Abandoned Vehicles 380 0 0 0 0 0 0
Heating 0 755 0 0 0 0 0
Noise 0 0 2890 0 0 0 0
Parking 0 0 0 2533 0 0 1
Road Infrastructure 0 0 4 57 564 0 1
Sanitation 0 0 1 2 0 954 5
Water and Plumbing 0 0 0 9 0 0 678

8.0.3 grouped — Naive Bayes

Rows: actual category; columns: predicted category
Abandoned Vehicles Heating Noise Parking Road Infrastructure Sanitation Water and Plumbing
Abandoned Vehicles 0 0 742 0 0 0 0
Heating 0 928 0 0 0 0 0
Noise 0 0 2363 0 0 0 0
Parking 225 0 0 1257 0 0 0
Road Infrastructure 0 0 7 48 639 4 4
Sanitation 0 0 0 0 639 129 4
Water and Plumbing 0 17 2 0 0 0 470

8.0.4 grouped — Logistic Regression

Rows: actual category; columns: predicted category
Abandoned Vehicles Heating Noise Parking Road Infrastructure Sanitation Water and Plumbing
Abandoned Vehicles 0 0 742 0 0 0 0
Heating 0 928 0 0 0 0 0
Noise 0 0 2363 0 0 0 0
Parking 225 0 0 1257 0 0 0
Road Infrastructure 0 0 9 96 587 4 6
Sanitation 0 0 643 0 0 129 0
Water and Plumbing 0 0 2 102 0 0 385
for(m in c('Naive_Bayes','Logistic_Regression')) {
 cat('\n\n### Grouped ',gsub('_',' ',m),'\n\n',sep='')
 z <- read.csv(paste0('data/results/grouped_',m,'_class_metrics.csv'))
 print(knitr::kable(z,digits=3)); cat('\n\n')
}

8.0.5 Grouped Naive Bayes

category precision recall f1 support
Abandoned Vehicles 0.000 0.000 0.000 742
Heating 0.982 1.000 0.991 928
Noise 0.759 1.000 0.863 2363
Parking 0.963 0.848 0.902 1482
Road Infrastructure 0.500 0.910 0.645 702
Sanitation 0.970 0.167 0.285 772
Water and Plumbing 0.983 0.961 0.972 489

8.0.6 Grouped Logistic Regression

category precision recall f1 support
Abandoned Vehicles 0.000 0.000 0.000 742
Heating 1.000 1.000 1.000 928
Noise 0.629 1.000 0.772 2363
Parking 0.864 0.848 0.856 1482
Road Infrastructure 1.000 0.836 0.911 702
Sanitation 0.970 0.167 0.285 772
Water and Plumbing 0.985 0.787 0.875 489

Both grouped models have zero recall for Abandoned Vehicles and approximately 16.71% recall for Sanitation. All 742 grouped Abandoned Vehicles records have zero recognized features. The 2,860 zero-feature grouped records are all predicted as Noise; their 73.74% accuracy reflects the prevalence of Noise among those records, not text understanding. The grouped split therefore exposes weaknesses hidden by random testing.

9 Predictions on new documents

Eight manually written examples cover all seven categories, with two Abandoned Vehicles examples. They are illustrative, not independently collected citizen narratives. Existing models and vocabularies are reused without retraining.

show(aggregate(correct~experiment+model,examples,mean),digits=3)
experiment model correct
grouped Logistic_Regression 0.75
random Logistic_Regression 0.75
grouped Naive_Bayes 0.75
random Naive_Bayes 0.75
show(subset(examples,experiment=='grouped',select=c(model,document,expected,predicted,recognized_tokens,total_tokens,correct)))
model document expected predicted recognized_tokens total_tokens correct
17 Naive_Bayes A car has been left on the street for several weeks Abandoned Vehicles Road Infrastructure 4 11 FALSE
18 Naive_Bayes There is no heat in my apartment Heating Heating 4 7 TRUE
19 Naive_Bayes Neighbors are playing loud music at night Noise Noise 3 7 TRUE
20 Naive_Bayes A vehicle is blocking my driveway Parking Parking 3 6 TRUE
21 Naive_Bayes There is a large pothole in the road Road Infrastructure Road Infrastructure 3 8 TRUE
22 Naive_Bayes Garbage has not been collected from our building Sanitation Sanitation 4 8 TRUE
23 Naive_Bayes Water is leaking from the ceiling Water and Plumbing Water and Plumbing 5 6 TRUE
24 Naive_Bayes The automobile appears deserted and immobile Abandoned Vehicles Heating 2 6 FALSE
25 Logistic_Regression A car has been left on the street for several weeks Abandoned Vehicles Noise 4 11 FALSE
26 Logistic_Regression There is no heat in my apartment Heating Heating 4 7 TRUE
27 Logistic_Regression Neighbors are playing loud music at night Noise Noise 3 7 TRUE
28 Logistic_Regression A vehicle is blocking my driveway Parking Parking 3 6 TRUE
29 Logistic_Regression There is a large pothole in the road Road Infrastructure Road Infrastructure 3 8 TRUE
30 Logistic_Regression Garbage has not been collected from our building Sanitation Sanitation 4 8 TRUE
31 Logistic_Regression Water is leaking from the ceiling Water and Plumbing Water and Plumbing 5 6 TRUE
32 Logistic_Regression The automobile appears deserted and immobile Abandoned Vehicles Noise 2 6 FALSE

Each model configuration correctly classifies six of eight examples (75%). Both Abandoned Vehicles examples are misclassified even though some tokens are recognized. This small exercise demonstrates prediction on new documents, not an estimate of real-world free-text accuracy.

10 Limitations and future work

  • Standardized descriptors are dependent on complaint type and may encode the target; grouping identical text does not eliminate this structural dependence.
  • The first 5,000 records per month are a convenience sample concentrated near month starts, not a representative sample of NYC complaints.
  • Only seven selected categories are modeled. Excluded complaint types and empty descriptions are outside the evaluated scope.
  • The corpus has few distinct descriptions and substantial class imbalance. A single grouped split may be sensitive to which descriptions are withheld.
  • Unigram models cannot reliably handle unfamiliar synonyms, context or unseen vocabulary. The eight synthetic examples are too few for population-level conclusions.

Future work could use independently labeled free-text complaints, multiple grouped validation folds, temporal holdouts, character n-grams and an abstention mechanism for low-coverage inputs. Any model tuning should occur on training/validation data rather than the held-out test set.

11 Conclusion

The project demonstrates supervised document classification with two models and two evaluation designs. High random-split accuracy did not translate into equally high performance on unseen standardized descriptions. Grouped testing revealed substantial vocabulary gaps and class-specific failures. The results support reporting both record-level and description-level performance and checking for repeated text before interpreting classification accuracy. They do not establish readiness for automated routing of real citizen narratives.

12 Reproducibility and references

Keep this R Markdown file beside the five R scripts and the data directory. The default render reads previously generated outputs. To rebuild from the acquisition stage, install glmnet, rmarkdown and knitr, then run rmarkdown::render('Project_4.Rmd', params=list(rebuild=TRUE)). The acquisition script reuses validated monthly CSVs when available; downloading again may yield changed source records. The following code listings document the complete pipeline.

12.0.1 01_NYC311_Data_Acquisition_and_EDA.R

# DATA 607 - Project 4: Document Classification
# NYC 311 Complaint Classification | Mohd Afwan Shaikh
# Stage 1: Data acquisition, validation, EDA and leakage investigation
# Research question: How does repeated text affect classification generalization?
# Source: https://data.cityofnewyork.us/d/erm2-nwe9
# Run from the project root in RStudio using Source.
# Base R only. Existing data dictionary and validated CSVs are preserved.
# No model training or train/test splitting is performed in this stage.

# 1. Setup and API connection test ----------------------------------------
options(timeout = 300)
cat('Working directory:', getwd(), '\n')
dir.create('data/raw', recursive = TRUE, showWarnings = FALSE)
base_url <- 'https://data.cityofnewyork.us/resource/erm2-nwe9.csv'
read_data <- function(path) read.csv(path, colClasses = 'character',
                                    na.strings = '', check.names = FALSE)
test_path <- 'data/nyc311_test.csv'
# Original test: 100 rows, 44 columns; date range 2026-12-04 01:30:26 to 02:06:20.
# This was an API connectivity test, not part of the 2025 training corpus.
if (!file.exists(test_path)) {
  tryCatch(download.file(paste0(base_url, '?$limit=100'), test_path,
                         mode = 'wb', method = 'libcurl'),
           error = function(e) message('Optional API test failed: ', conditionMessage(e)))
}
if (file.exists(test_path)) {
  tryCatch({
    sample_data <- read_data(test_path)
    print(dim(sample_data)); print(names(sample_data))
    print(head(sample_data[, c('complaint_type', 'descriptor', 'descriptor_2')], 30))
    print(sort(table(sample_data$complaint_type), decreasing = TRUE))
    print(colSums(is.na(sample_data) | sample_data == '', na.rm = TRUE))
    print(range(sample_data$created_date, na.rm = TRUE))
  }, error = function(e) message('Optional test inspection failed: ', conditionMessage(e)))
}

# 2. Download monthly data ------------------------------------------------
# Original single request for 50,000 rows returned HTTP 503.
# Revised method: first 5,000 records of each month in 2025 (not random).
# January succeeded on attempt 2; August on attempt 3; all other months on attempt 1.
columns <- c('unique_key', 'created_date', 'complaint_type', 'descriptor',
             'descriptor_2', 'location_type', 'borough')
boundaries <- seq(as.Date('2025-01-01'), as.Date('2026-01-01'), by = 'month')
limit <- 5000L
paths <- file.path('data/raw', paste0('nyc311_', format(boundaries[1:12], '%Y_%m'), '.csv'))
valid <- function(path, start, end) {
  if (!file.exists(path)) return(FALSE)
  tryCatch({
    d <- read_data(path)
    identical(names(d), columns) && nrow(d) == limit &&
      !anyNA(d$unique_key) && all(nzchar(trimws(d$unique_key))) &&
      !anyDuplicated(d$unique_key) && !anyNA(d$created_date) &&
      all(substr(d$created_date, 1, 10) >= start & substr(d$created_date, 1, 10) < end)
  }, error = function(e) FALSE)
}
for (i in seq_along(paths)) {
  start <- format(boundaries[i], '%Y-%m-%d')
  end <- format(boundaries[i+1], '%Y-%m-%d')
  path <- paths[i]
  if (valid(path, start, end)) { cat('Already validated:', path, '\n'); next }
  where <- sprintf("created_date >= '%sT00:00:00' AND created_date < '%sT00:00:00'", start, end)
  url <- paste0(base_url, '?$select=', URLencode(paste(columns, collapse=','), reserved=TRUE),
                '&$where=', URLencode(where, reserved=TRUE),
                '&$order=', URLencode('created_date ASC,unique_key ASC', reserved=TRUE),
                '&$limit=', limit)
  tmp <- paste0(path, '.part')
  for (attempt in 1:3) {
    cat('Downloading', start, '- attempt', attempt, '\n')
    unlink(tmp)
    ok <- tryCatch({
      status <- download.file(url, tmp, mode='wb', method='libcurl')
      status == 0 && valid(tmp, start, end)
    }, error=function(e) { message(conditionMessage(e)); FALSE })
    if (isTRUE(ok)) {
      if (!file.copy(tmp, path, overwrite=TRUE)) stop('Cannot save ', path)
      unlink(tmp); cat('Validated:', path, '\n'); break
    }
    unlink(tmp)
    if (attempt < 3) Sys.sleep(5 * attempt)
  }
  Sys.sleep(3)
}
checks <- vapply(seq_along(paths), function(i) valid(paths[i], format(boundaries[i], '%Y-%m-%d'), format(boundaries[i+1], '%Y-%m-%d')), logical(1))
if (!all(checks)) stop('Incomplete download. Rerun script: ', paste(paths[!checks], collapse=', '))

# 3. Combine and validate -------------------------------------------------
nyc311 <- do.call(rbind, lapply(paths, read_data))
cat('Rows before duplicate removal:', nrow(nyc311), '\n')
cat('Duplicate complaint IDs:', sum(duplicated(nyc311$unique_key)), '\n')
nyc311 <- nyc311[!duplicated(nyc311$unique_key), , drop=FALSE]
output <- 'data/nyc311_2025.csv'
# Preserve existing combined CSV if identical in content; otherwise stop for review.
if (file.exists(output)) {
  if (!identical(read_data(output), nyc311)) stop('Existing combined CSV differs from monthly files. Review before replacing.')
} else write.csv(nyc311, output, row.names=FALSE, na='')
print(dim(nyc311))
print(colSums(is.na(nyc311) | nyc311 == '', na.rm=TRUE))
print(range(nyc311$created_date))
# Observed: 60,000 rows, 7 columns, 0 duplicate IDs.
# Missing: descriptor 216; descriptor_2 34,198; location_type 7,011.
# Other four columns had no missing values.
# Date range: 2025-01-01T00:00:12.000 to 2025-12-01T11:51:00.000.

# 4. Exploratory data analysis -------------------------------------------
cat('Unique original complaint types:', length(unique(nyc311$complaint_type)), '\n')
print(sort(table(nyc311$complaint_type), decreasing=TRUE))
cat('Unique primary descriptor values:', length(unique(nyc311$descriptor)), '\n')
cat('Unique secondary descriptor values:', length(unique(nyc311$descriptor_2)), '\n')
print(table(substr(nyc311$created_date, 1, 7)))
# Observed: 163 complaint types; 659 primary and 513 secondary descriptor values
# (including missing/blank values); 5,000 records per month.
# Top categories: Illegal Parking 9,670; Noise - Residential 8,655;
# HEAT/HOT WATER 3,761; Blocked Driveway 2,946; Noise - Street/Sidewalk 2,557.

# 5. Initial text normalization ------------------------------------------
# Preserve original labels and source CSV. Changes below are in memory only.
nyc311$complaint_type_original <- nyc311$complaint_type
nyc311$complaint_type <- toupper(trimws(nyc311$complaint_type))
clean_text <- function(x) {
  x[is.na(x)] <- ''
  tolower(trimws(x))
}
nyc311$document <- trimws(paste(clean_text(nyc311$descriptor), clean_text(nyc311$descriptor_2)))
nyc311$document <- gsub('\\s+', ' ', nyc311$document)
# Keep N/A placeholders for now to reproduce the original investigation.

# 6. Repeated text and ambiguous labels ----------------------------------
cat('Unique document values:', length(unique(nyc311$document)), '\n')
cat('Repeated documents beyond first occurrence:', sum(duplicated(nyc311$document)), '\n')
cat('Empty documents:', sum(nyc311$document == ''), '\n')
print(head(sort(table(nyc311$document), decreasing=TRUE), 20))
label_counts <- tapply(nyc311$complaint_type, nyc311$document,
                       function(x) length(unique(x)))
cat('Document values associated with multiple labels:', sum(label_counts > 1), '\n')
print(head(sort(label_counts[label_counts > 1], decreasing=TRUE), 20))
# Observed: 1,173 unique document values (including empty string),
# 58,827 repeated occurrences (98.045%), 216 empty documents, 41 ambiguous values.
# loud music/party: 9,046 records, five original complaint types.
# blocked hydrant: 3,059; posted parking sign violation: 2,359.
# n/a: 1,467 records, eight complaint types.

# 7. Findings, limitations and next steps --------------------------------
# The public dataset provides standardized descriptors, not original narratives.
# Descriptors depend on complaint type, creating potential target leakage.
# Random record splitting can also put identical text in train and test sets.
# Proposed comparison: random 80/20 split vs grouped split by normalized document.
# Grouping prevents exact text overlap but cannot eliminate source-label dependence.
# Proposed categories (not yet mapped or validated): Noise, Parking, Heating,
# Sanitation, Road Infrastructure, Water and Plumbing, Abandoned Vehicles.
# Next stage: finalize mapping, handle placeholders, check ambiguity again,
# prepare splits, fit training-only text features, compare Naive Bayes and
# Logistic Regression using accuracy, precision, recall, macro F1 and confusion matrices.
# Independently written examples may illustrate predictions, not establish real-world accuracy.
# No preprocessing exports, model training, or evaluation have been completed yet.
cat('\nStage 1 complete. Next: category mapping and preprocessing.\n')

12.0.2 02_Data_Preprocessing.R

# DATA 607 Project 4 - Phase 2: Data preprocessing
# Run from the project directory. Base R only.
# Inputs are standardized descriptors, not citizen-written narratives.
# Preserve repeated records; compare random and document-grouped splits.
set.seed(607)
input <- 'data/nyc311_2025.csv'
out <- 'data/processed'
stopifnot(file.exists(input))
dir.create(out, recursive=TRUE, showWarnings=FALSE)
d <- read.csv(input, colClasses='character', na.strings='', check.names=FALSE)
stopifnot(all(c('unique_key','complaint_type','descriptor','descriptor_2') %in% names(d)), !anyNA(d$unique_key), !anyDuplicated(d$unique_key))
cat('Original rows:', nrow(d), '\n')
# Explicit mapping: scope is selected complaint types, not all NYC 311 requests.
map <- list(
  'Noise'=c('NOISE','NOISE - RESIDENTIAL','NOISE - COMMERCIAL','NOISE - STREET/SIDEWALK','NOISE - VEHICLE','NOISE - HELICOPTER','NOISE - PARK','NOISE - HOUSE OF WORSHIP'),
  'Parking'=c('ILLEGAL PARKING','BLOCKED DRIVEWAY','BROKEN PARKING METER'),
  'Heating'=c('HEAT/HOT WATER','NON-RESIDENTIAL HEAT'),
  'Sanitation'=c('UNSANITARY CONDITION','DIRTY CONDITION','MISSED COLLECTION','ILLEGAL DUMPING'),
  'Water and Plumbing'=c('PLUMBING','WATER SYSTEM','WATER LEAK','SEWER','SEWER MAINTENANCE','WATER MAINTENANCE','INDOOR SEWAGE'),
  'Road Infrastructure'=c('STREET CONDITION','TRAFFIC SIGNAL CONDITION','SIDEWALK CONDITION','STREET LIGHT CONDITION','CURB CONDITION','STREET SIGN - DAMAGED','STREET SIGN - DANGLING','STREET SIGN - MISSING','HIGHWAY CONDITION'),
  'Abandoned Vehicles'=c('ABANDONED VEHICLE','DERELICT VEHICLES'))
lookup <- setNames(rep(names(map), lengths(map)), unlist(map, use.names=FALSE))
stopifnot(!anyDuplicated(names(lookup)))
d$complaint_type <- toupper(trimws(d$complaint_type))
d$category <- unname(lookup[d$complaint_type])
cat('Excluded outside scope:', sum(is.na(d$category)), '\n')
print(sort(table(d$complaint_type[is.na(d$category)]), decreasing=TRUE))
d <- d[!is.na(d$category), , drop=FALSE]
clean <- function(x) {
  x[is.na(x)] <- ''
  x <- tolower(trimws(gsub('[[:space:]]+', ' ', x)))
  x[x %in% c('n/a','na','not applicable','unknown','other/unknown','unspecified')] <- ''
  x
}
d$document <- trimws(paste(clean(d$descriptor), clean(d$descriptor_2)))
cat('Excluded empty or placeholder-only documents:', sum(d$document==''), '\n')
d <- d[d$document!='', , drop=FALSE]
# Keep only ID, text and labels in modeling exports. Original label is for audit only.
d <- d[,c('unique_key','complaint_type','category','document')]
cat('Retained rows:', nrow(d), '\n'); print(table(d$category))
cat('Unique documents:', length(unique(d$document)), '\n')
cat('Repeated records beyond first occurrence:', sum(duplicated(d$document)), '\n')
ambiguity <- tapply(d$category,d$document,function(x) length(unique(x)))
cat('Ambiguous document values after mapping:', sum(ambiguity>1), '\n')
cat('Rows with ambiguous documents:', sum(d$document %in% names(ambiguity)[ambiguity>1]), '\n')
# A: stratified random record split, approximately 80/20.
idx <- split(seq_len(nrow(d)),d$category)
stopifnot(all(lengths(idx)>=2))
a <- sort(unlist(lapply(idx,function(i) sample(i, max(1,min(length(i)-1,floor(.8*length(i))))))))
# B: assign entire document groups to one partition. Search seeded candidate
# splits for reasonable row and class balance, without using model performance.
groups <- unique(d$document)
gid <- match(d$document,groups)
counts <- table(factor(gid,levels=seq_along(groups)),d$category)
totals <- colSums(counts)
stopifnot(all(colSums(counts>0)>=2))
best <- Inf; chosen <- NULL
for (iteration in seq_len(2000)) {
  test_groups <- sample(seq_along(groups), max(1,floor(.2*length(groups))))
  n <- colSums(counts[test_groups,,drop=FALSE])
  if(any(n==0 | n==totals)) next
  score <- mean((n/totals-.2)^2) + (sum(n)/sum(totals)-.2)^2
  if(score<best) {best <- score; chosen <- test_groups}
}
if(is.null(chosen)) stop('No valid grouped split found; inspect class support.')
b <- which(!gid %in% chosen)
validate <- function(train,test,grouped=FALSE) {
  stopifnot(nrow(train)+nrow(test)==nrow(d), !anyDuplicated(c(train$unique_key,test$unique_key)), setequal(c(train$unique_key,test$unique_key),d$unique_key), setequal(train$category,test$category))
  overlap <- intersect(train$document,test$document)
  if(grouped) stopifnot(length(overlap)==0)
  cat('Train:',nrow(train),' Test:',nrow(test),' Shared document values:',length(overlap),'\n')
  cat('Test rows with previously seen text:',sum(test$document %in% train$document),'\n')
  print(cbind(train=table(train$category),test=table(test$category)))
}
random_train <- d[a,]; random_test <- d[-a,]
grouped_train <- d[b,]; grouped_test <- d[-b,]
cat('\nRandom split\n'); validate(random_train,random_test)
cat('\nGrouped split\n'); validate(grouped_train,grouped_test,TRUE)
outputs <- list(nyc311_cleaned=d,random_train=random_train,random_test=random_test,grouped_train=grouped_train,grouped_test=grouped_test)
for(nm in names(outputs)) write.csv(outputs[[nm]],file.path(out,paste0(nm,'.csv')),row.names=FALSE,na='')
write.csv(data.frame(complaint_type=names(lookup),category=unname(lookup)),file.path(out,'category_mapping.csv'),row.names=FALSE)
cat('\nSaved processed datasets and category mapping in',out,'\n')
# Next phase: fit vocabulary and TF-IDF on training text only, separately for
# each split. Never use complaint_type, category or unique_key as predictors.
# Grouped evaluation prevents exact-text overlap but not label-derived semantics.

12.0.3 03_Feature_Extraction.R

# DATA 607 Project 4 | Phase 3: Feature extraction
# Run from project root. Base R only. No model fitting in this phase.
# Fit vocabulary and IDF separately on each training partition only.
# Keep repeated records; never use labels or IDs as predictors.
input <- 'data/processed'
out <- 'data/features'
dir.create(out, recursive=TRUE, showWarnings=FALSE)
read_split <- function(name) {
  d <- read.csv(file.path(input,paste0(name,'.csv')), colClasses='character', check.names=FALSE)
  stopifnot(all(c('unique_key','category','document') %in% names(d)), !anyNA(d$document), all(nzchar(d$document)), !anyNA(d$category), !anyNA(d$unique_key), !anyDuplicated(d$unique_key))
  d
}
# Unigrams; retain negation and other short words (e.g. no heat).
tokenize <- function(x) {
  x <- trimws(gsub('[^[:alnum:]]+', ' ', tolower(x)))
  lapply(strsplit(x, ' ', fixed=TRUE), function(t) t[nzchar(t)])
}
# Dense matrices are practical for this small standardized vocabulary.
make_counts <- function(tokens, vocab) {
  m <- matrix(0, nrow=length(tokens), ncol=length(vocab), dimnames=list(NULL,vocab))
  for(i in seq_along(tokens)) {
    j <- match(tokens[[i]],vocab,nomatch=0L)
    m[i,] <- tabulate(j[j>0L],nbins=length(vocab))
  }
  m
}
make_tfidf <- function(counts,idf) {
  stopifnot(identical(colnames(counts),names(idf)))
  tf <- counts / pmax(rowSums(counts),1)
  sweep(tf,2,idf,'*')
}
for (experiment in c('random','grouped')) {
  train <- read_split(paste0(experiment,'_train'))
  test <- read_split(paste0(experiment,'_test'))
  stopifnot(length(intersect(train$unique_key,test$unique_key))==0, setequal(train$category,test$category))
  if(experiment=='grouped') stopifnot(length(intersect(train$document,test$document))==0)
  tr_tokens <- tokenize(train$document)
  te_tokens <- tokenize(test$document)
  vocab <- sort(unique(unlist(tr_tokens,use.names=FALSE)))
  stopifnot(length(vocab)>0)
  x_train <- make_counts(tr_tokens,vocab)
  x_test <- make_counts(te_tokens,vocab)
  df <- colSums(x_train>0)
  # Smoothed inverse document frequency: log((1+N)/(1+DF))+1.
  idf <- setNames(log((1+nrow(train))/(1+df))+1,vocab)
  tf_train <- make_tfidf(x_train,idf)
  tf_test <- make_tfidf(x_test,idf)
  stopifnot(identical(colnames(x_train),colnames(x_test)), all(is.finite(tf_train)), all(is.finite(tf_test)))
  classes <- sort(unique(train$category))
  y_train <- factor(train$category,levels=classes)
  y_test <- factor(test$category,levels=classes)
  unknown <- sum(vapply(te_tokens,function(t) sum(!t %in% vocab),integer(1)))
  total <- sum(lengths(te_tokens))
  zero <- sum(rowSums(x_test)==0)
  cat('\nExperiment:',experiment,'\n')
  cat('Vocabulary size:',length(vocab),'\n')
  cat('Training matrix:',dim(x_train),'\nTesting matrix:',dim(x_test),'\n')
  cat('Unseen test token occurrences:',unknown,'of',total,'\n')
  cat('All-zero training rows:',sum(rowSums(x_train)==0),'\n')
  cat('All-zero test rows:',zero,'\n')
  print(table(category=y_test,zero_features=rowSums(x_test)==0))
  # Keep zero-feature rows in evaluation; report coverage instead of silently dropping them.
  saveRDS(list(vocabulary=vocab,idf=idf,counts_train=x_train,counts_test=x_test,
    tfidf_train=tf_train,tfidf_test=tf_test,y_train=y_train,y_test=y_test,
    train_id=train$unique_key,test_id=test$unique_key,zero_test=rowSums(x_test)==0),
    file.path(out,paste0(experiment,'_features.rds')))
  write.csv(data.frame(term=vocab,document_frequency=as.numeric(df),idf=as.numeric(idf)),file.path(out,paste0(experiment,'_vocabulary.csv')),row.names=FALSE)
}
cat('\nFeature extraction complete. Next: train multinomial Naive Bayes on counts and regularized multinomial logistic regression on TF-IDF.\n')

12.0.4 04_Model_Training_and_Evaluation.R

# DATA 607 Project 4 | Phase 4: Training and evaluation
# Run from project root. Install glmnet once if needed:
# install.packages('glmnet')
# Fixed hyperparameters chosen before evaluating test results.
if (!requireNamespace('glmnet', quietly=TRUE)) stop("Install glmnet: install.packages('glmnet')")
set.seed(607)
out <- 'data/results'; dir.create(out, recursive=TRUE, showWarnings=FALSE)
metrics <- function(y,p,classes) {
  cm <- table(actual=factor(y,levels=classes), predicted=factor(p,levels=classes))
  tp <- diag(cm); precision <- tp/pmax(colSums(cm),1); recall <- tp/pmax(rowSums(cm),1)
  f1 <- ifelse(precision+recall>0,2*precision*recall/pmax(precision+recall,1e-15),0)
  list(cm=cm, accuracy=sum(tp)/sum(cm), macro_f1=mean(f1), per_class=data.frame(category=classes,precision=precision,recall=recall,f1=f1,support=rowSums(cm)))
}
results <- list()
for (experiment in c('random','grouped')) {
  f <- readRDS(file.path('data/features',paste0(experiment,'_features.rds')))
  test <- read.csv(file.path('data/processed',paste0(experiment,'_test.csv')),colClasses='character')
  stopifnot(identical(test$unique_key,f$test_id), identical(test$category,as.character(f$y_test)))
  classes <- levels(f$y_train); y <- f$y_train
  prior <- as.numeric(table(y))/length(y)
  # Multinomial NB with Laplace smoothing (alpha=1).
  totals <- rowsum(f$counts_train, y, reorder=TRUE)[classes,,drop=FALSE]+1
  logprob <- log(totals/rowSums(totals))
  scores <- sweep(f$counts_test %*% t(logprob),2,log(prior),'+')
  nb <- classes[max.col(scores,ties.method='first')]
  # Ridge multinomial logistic regression; fixed lambda avoids test-set tuning.
  fit <- glmnet::glmnet(f$tfidf_train,y,family='multinomial',alpha=0,lambda=0.01,standardize=FALSE)
  lr <- as.character(predict(fit,newx=f$tfidf_test,s=0.01,type='class'))
  predictions <- list(Baseline=rep(classes[which.max(prior)],length(f$y_test)),Naive_Bayes=nb,Logistic_Regression=lr)
  saveRDS(list(vocabulary=f$vocabulary,idf=f$idf,classes=classes,prior=prior,nb_logprob=logprob,logistic=fit,lambda=0.01),file.path(out,paste0(experiment,'_models.rds')))
  for (model in names(predictions)) {
    p <- predictions[[model]]; stopifnot(length(p)==length(f$y_test),all(p %in% classes))
    m <- metrics(f$y_test,p,classes)
    # Each distinct standardized description has equal weight in this supplementary metric.
    unique_accuracy <- mean(vapply(split(p==as.character(f$y_test),test$document),mean,numeric(1)))
    zero <- f$zero_test
    row <- data.frame(experiment=experiment,model=model,accuracy=m$accuracy,macro_f1=m$macro_f1,unique_document_accuracy=unique_accuracy,zero_feature_accuracy=if(any(zero)) mean(p[zero]==as.character(f$y_test[zero])) else NA_real_,recognized_accuracy=if(any(!zero)) mean(p[!zero]==as.character(f$y_test[!zero])) else NA_real_)
    results[[length(results)+1L]] <- row
    cat('\n',experiment,model,'\n'); print(row); print(m$cm); print(m$per_class)
    prefix <- file.path(out,paste(experiment,model,sep='_'))
    write.csv(as.data.frame.matrix(m$cm),paste0(prefix,'_confusion.csv'))
    write.csv(m$per_class,paste0(prefix,'_class_metrics.csv'),row.names=FALSE)
    write.csv(data.frame(unique_key=f$test_id,actual=f$y_test,predicted=p,zero_features=zero),paste0(prefix,'_predictions.csv'),row.names=FALSE)
  }
}
summary <- do.call(rbind,results); print(summary); write.csv(summary,file.path(out,'model_comparison.csv'),row.names=FALSE)
# Zero-feature rows remain in all overall metrics. Standardized descriptors
# are label-dependent; grouped results are not evidence of free-text accuracy.
cat('\nPhase 4 complete. Results saved in data/results.\n')

12.0.5 05_Unseen_Document_Predictions.R

# DATA 607 Project 4 | Phase 5: Illustrative unseen document predictions
# Run from project root after Phase 4. Requires glmnet.
# Synthetic examples are not independently collected citizen narratives.
# Do not tune models or vocabulary using these examples.
stopifnot(requireNamespace('glmnet', quietly=TRUE))
out <- 'data/results'
examples <- data.frame(document=c(
 'A car has been left on the street for several weeks',
 'There is no heat in my apartment',
 'Neighbors are playing loud music at night',
 'A vehicle is blocking my driveway',
 'There is a large pothole in the road',
 'Garbage has not been collected from our building',
 'Water is leaking from the ceiling',
 'The automobile appears deserted and immobile'),
 expected=c('Abandoned Vehicles','Heating','Noise','Parking','Road Infrastructure','Sanitation','Water and Plumbing','Abandoned Vehicles'))
tokenize <- function(x) lapply(strsplit(trimws(gsub('[^[:alnum:]]+', ' ',tolower(x))), ' ',fixed=TRUE),function(t)t[nzchar(t)])
results <- list()
for (experiment in c('random','grouped')) {
 m <- readRDS(file.path(out,paste0(experiment,'_models.rds')))
 train <- read.csv(file.path('data/processed',paste0(experiment,'_train.csv')),colClasses='character')
 stopifnot(!any(examples$document %in% train$document))
 tokens <- tokenize(examples$document)
 x <- matrix(0,nrow=nrow(examples),ncol=length(m$vocabulary),dimnames=list(NULL,m$vocabulary))
 for(i in seq_along(tokens)) {
  j <- match(tokens[[i]],m$vocabulary,nomatch=0L)
  x[i,] <- tabulate(j[j>0],nbins=ncol(x))
 }
 tf <- sweep(x/pmax(rowSums(x),1),2,m$idf,'*')
 nb <- m$classes[max.col(sweep(x %*% t(m$nb_logprob),2,log(m$prior),'+'),ties.method='first')]
 lr <- as.character(predict(m$logistic,newx=tf,s=m$lambda,type='class'))
 zero <- rowSums(x)==0
 for(model in c('Naive_Bayes','Logistic_Regression')) {
  p <- if(model=='Naive_Bayes') nb else lr
  results[[length(results)+1L]] <- data.frame(experiment,model,examples,predicted=p,recognized_tokens=rowSums(x),total_tokens=lengths(tokens),zero_features=zero,correct=p==examples$expected,review_recommended=zero)
 }
}
result <- do.call(rbind,results)
print(result,row.names=FALSE)
write.csv(result,file.path(out,'unseen_document_predictions.csv'),row.names=FALSE)
cat('\nIllustrative example accuracy (not a population estimate):\n')
print(aggregate(correct~experiment+model,result,mean))
cat('\nPhase 5 complete. No models were retrained.\n')
sessionInfo()
## R version 4.6.1 (2026-06-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26300)
## 
## Matrix products: default
##   LAPACK version 3.12.1
## 
## locale:
## [1] LC_COLLATE=English_United States.utf8 
## [2] LC_CTYPE=English_United States.utf8   
## [3] LC_MONETARY=English_United States.utf8
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.utf8    
## 
## time zone: America/New_York
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.39     R6_2.6.1          fastmap_1.2.0     xfun_0.60        
##  [5] cachem_1.1.0      knitr_1.52        htmltools_0.5.9   rmarkdown_2.32   
##  [9] lifecycle_1.0.5   cli_3.6.6         sass_0.4.10       jquerylib_0.1.4  
## [13] compiler_4.6.1    rstudioapi_0.19.0 tools_4.6.1       evaluate_1.0.5   
## [17] bslib_0.12.0      yaml_2.3.12       otel_0.2.0        jsonlite_2.0.0   
## [21] rlang_1.3.0

13 Project Resources

The interactive dashboard allows users to explore complaint distributions, data leakage, model performance, and predictions for new complaint descriptions.