
Detecting Problems Before They Become Emergencies | Part 3
Can AI detect urban problems before they escalate? Explore anomaly detection, time-series analysis, Python, and Amazon SageMaker AI to identify unusual patterns in smart-city sensor data and support early warnings.
Series: THE CITY THAT CAN FEEL: Building an Artificial Nervous System for Smart Cities Using AWS (7 articles)
- …
- 3Detecting Problems Before They Become Emergencies | Part 3 This article
THE CITY THAT CAN FEEL | PART 03/07
Detecting Problems Before They Become Emergencies: Building an AI-Powered Urban Anomaly Detection System on AWS
1. Introduction: What if a city could recognize the early signs of trouble?
Imagine a drainage sensor reporting a gradual increase in water levels.
At first, the readings appear normal. A few minutes later, the values begin increasing faster than expected.
At the same time, rainfall measurements are rising, and a nearby road sensor reports decreasing vehicle speeds.
Individually, these signals may not be enough to identify a serious problem.
But together, they could indicate a developing urban disruption.
What if an intelligent system could recognize these patterns, investigate related signals, and alert city operators before the situation becomes more severe?
This is where machine learning becomes an important part of our artificial nervous system for smart cities.
In Part 1, we introduced the idea of a city that can sense its environment.
In Part 2, we explored how IoT devices communicate and how their signals can be collected using AWS.
Now, in Part 3, we move from data collection to intelligent analysis.
Our objective is to design a proposed AI-powered urban anomaly detection system that learns patterns in sensor data and identifies unusual behavior.
The central question is:
How can we teach a machine to recognize when a city is behaving differently from normal?
«Architecture disclosure: This article presents a proposed technical architecture, illustrative Python experiments, and an implementation approach. It does not claim that a city-scale system has been deployed, that predictions have been validated in a real city, or that any particular accuracy has been achieved.»
2. Understanding anomaly detection
An anomaly is an observation or pattern that differs significantly from expected behavior.
In a smart city, anomalies can appear in many forms.
A. Water infrastructure anomalies
Examples:
- Unexpected increases in water level
- Sudden changes in pipeline pressure
- Unusual water consumption
- Irregular flow measurements
B. Environmental anomalies
Examples:
- Unexpected increases in noise levels
- Sudden changes in particulate matter
- Unusual temperature patterns
- Unexpected pollution readings
C. Traffic anomalies
Examples:
- Sudden reductions in average vehicle speed
- Unusual increases in traffic density
- Unexpected congestion during normally quiet periods
- Irregular traffic flow
D. Energy anomalies
Examples:
- Unusual electricity consumption
- Unexpected voltage variations
- Abnormal equipment operating patterns
- Sudden changes in energy demand
An important distinction:
An anomaly is not automatically an emergency.
A sudden increase in water level could be caused by rainfall, a sensor malfunction, a scheduled water release, or a real drainage problem.
The system should identify unusual patterns and support further investigation rather than immediately declaring an emergency.
3. Why traditional threshold monitoring is not always enough
A conventional monitoring system might use a fixed threshold.
For example:
if water_level > 80:
print("WARNING")
This is simple and useful for well-defined safety limits.
However, it does not understand context.
Consider two hypothetical situations:
Situation A
A water-level reading of 75 cm is recorded during heavy rainfall.
Situation B
The same reading of 75 cm is recorded during a normally dry period.
The numerical value is identical, but the surrounding conditions are different.
Similarly, a noise reading of 80 dB near a busy road may have a different interpretation from the same reading in a normally quiet residential area.
Fixed thresholds cannot independently account for all these patterns.
Machine learning can help identify deviations from learned historical behavior.
However, fixed thresholds should not be discarded. Where engineering or safety limits are defined by authorities, they should remain independent controls.
A stronger monitoring system combines:
- Known operational thresholds
- Historical statistical baselines
- Machine learning anomaly scores
- Contextual information
- Human verification
4. Three machine learning approaches for urban anomaly detection
Different types of urban data require different analytical methods.
Let's explore three useful approaches.
Approach 1: Statistical anomaly detection
This is a good starting point for understanding unusual values.
One simple technique is the Z-score.
The Z-score measures how far an observation is from the mean in units of standard deviation.
Formula:
Z = (X - μ) / σ
Where:
- X = observed value
- μ = historical mean
- σ = standard deviation
For example, suppose the average water level in a particular operating period is 40 cm and the standard deviation is 5 cm.
A reading of 55 cm produces:
Z = (55 - 40) / 5 = 3
The reading is three standard deviations above the mean.
A configured rule might flag this as an unusual observation.
But this method assumes the selected baseline is meaningful. It can produce misleading results when the data is strongly seasonal, non-normal, or changing over time.
Approach 2: Machine learning-based anomaly detection
Machine learning can identify more complex patterns.
One example is Isolation Forest.
Instead of simply calculating distance from the average, Isolation Forest identifies observations that can be isolated relatively easily through random feature splits.
It can be useful when multiple sensor features are available.
For example:
- Water level
- Rate of water-level change
- Rainfall
- Nearby sensor readings
- Time of day
Another relevant method is Random Cut Forest (RCF).
Amazon SageMaker AI documentation describes RCF as an unsupervised anomaly detection algorithm for observations that diverge from expected patterns, including unusual spikes and breaks in time-series behavior.
It is one option to evaluate for suitable datasets.
Approach 3: Time-series anomaly detection
Urban sensor data is usually time-dependent.
A reading at 10:00 AM should often be interpreted in relation to earlier readings.
For example, traffic speed may naturally decrease during peak hours.
A time-series approach can consider:
- Trend
- Seasonality
- Recent observations
- Rate of change
- Forecast residuals
One useful approach is to predict an expected value and compare it with the actual observation.
Residual = Actual value - Predicted value
If the residual is unusually large, the system can flag the observation for investigation.
This is especially useful when normal behavior changes throughout the day or across seasons.
5. Proposed AWS architecture
Now let's integrate anomaly detection into the artificial nervous system.
The proposed architecture contains six stages:
1. Sensor data collection
2. Streaming ingestion
3. Data preparation
4. Machine learning inference
5. Alert generation
6. Monitoring and human investigation
Layer 1: Collect sensor readings
The sensor network generates measurements from different urban locations.
Example sources:
- Water-level sensors
- Noise monitoring devices
- Traffic monitoring systems
- Environmental stations
In our previous episode, we explored AWS IoT Core and MQTT for collecting device messages.
We will reuse that data pipeline.
Layer 2: Stream the incoming information
Amazon Kinesis Data Streams can receive continuous sensor records.
AWS Lambda can process records from the stream in batches.
The processing stage should validate:
- Sensor identifiers
- Timestamps
- Measurement units
- Missing values
- Invalid measurements
- Duplicate events
Preserving event timestamps is important because sensor messages may arrive late or out of order.
Layer 3: Prepare features for machine learning
Raw sensor readings may not contain enough information to identify unusual behavior.
We can derive additional features.
Suppose we receive water-level measurements.
Useful features could include:
Feature| Meaning
Current level| Latest water-level measurement
Previous level| Earlier measurement
Change rate| Difference over a time interval
Rolling average| Average of recent readings
Rolling standard deviation| Recent measurement variability
Rainfall| Supporting environmental context
Time of day| Temporal context
Feature engineering can improve the usefulness of anomaly detection models.
However, feature values must be calculated without accidentally using information from the future.
Layer 4: Machine learning with Amazon SageMaker AI
Amazon SageMaker AI provides capabilities for building, training, and deploying machine learning models.
A proposed development workflow:
1. Store historical sensor data in Amazon S3.
2. Prepare the training dataset using Python.
3. Explore normal operating patterns.
4. Select an anomaly detection method.
5. Train and evaluate the model.
6. Deploy a suitable model for inference.
7. Send incoming feature records for scoring.
Possible models include:
- Isolation Forest
- Random Cut Forest
- Statistical residual-based anomaly detection
- Forecasting models with anomaly detection on residuals
For a small prototype, Scikit-learn can be used to experiment with Isolation Forest locally before deciding whether to train and deploy through SageMaker AI.
The model selection should depend on the sensor characteristics, data volume, interpretability requirements, and evaluation results.
Layer 5: Alert processing
A model produces an anomaly score or prediction.
The application then combines the model output with configured thresholds and operational rules.
For example:
Sensor Reading
|
v
Feature Extraction
|
v
ML Anomaly Score
|
v
Operational Rule Evaluation
|
v
Alert Classification
|
v
Human Review
An alert can contain:
- Sensor identifier
- Location
- Event timestamp
- Measured value
- Expected value or baseline
- Anomaly score
- Relevant supporting signals
- Recommended investigation priority
The alert should communicate uncertainty clearly.
It should not claim that a flood, pipeline failure, or other emergency has occurred unless that conclusion has been established through appropriate verification.
Layer 6: Monitoring and historical learning
The system should preserve its predictions and later compare them with verified outcomes.
For example:
- Was the anomaly a genuine infrastructure problem?
- Was it a faulty sensor?
- Was the event caused by expected weather conditions?
- Did the model generate a false alarm?
These feedback records can improve future evaluation and model development.
Amazon CloudWatch can monitor application logs, metrics, and operational alarms.
For model quality and drift, design an explicit monitoring workflow around stored predictions, baseline datasets, and subsequently verified outcomes.
Important service note: AWS documentation states that SageMaker Model Monitor is no longer open to new customers. New implementations should not depend on it as a newly available service. A custom monitoring pipeline using stored inference records, scheduled analysis, CloudWatch metrics, and alerts is an alternative to evaluate.
6. Practical implementation: Detecting unusual sensor readings using Python
Let's create a small experiment.
We will simulate historical water-level readings and introduce a few unusual values.
Then we will use Isolation Forest to identify potential anomalies.
This example runs locally and does not require an AWS account.
Step 1: Install the required libraries
pip install numpy pandas scikit-learn matplotlib
Step 2: Generate illustrative sensor data
import numpy as np
import pandas as pd
np.random.seed(42)
normal_readings = np.random.normal(
loc=45,
scale=5,
size=300
)
anomalies = np.array([
85, 92, 100, 12, 8
])
readings = np.concatenate([
normal_readings,
anomalies
])
df = pd.DataFrame({
"water_level": readings
})
print(df.tail())
Here, most observations are generated around a hypothetical normal level of 45 cm.
Five extreme values are added intentionally to test the detection method.
These are simulated values, not measurements from an actual drainage system.
Step 3: Train an Isolation Forest model
from sklearn.ensemble import IsolationForest
model = IsolationForest(
contamination=0.02,
random_state=42
)
df["prediction"] = model.fit_predict(
df[["water_level"]]
)
df["anomaly"] = df["prediction"].apply(
lambda value: "Anomaly"
if value == -1
else "Normal"
)
print(df["anomaly"].value_counts())
Isolation Forest returns:
- "1" for an observation classified as normal.
- "-1" for an observation classified as an anomaly.
The contamination setting is an assumed proportion used by the algorithm to determine its decision boundary. It is not a measured real-world anomaly rate.
Step 4: Visualize the detected observations
import matplotlib.pyplot as plt
normal = df[df["anomaly"] == "Normal"]
anomalies = df[df["anomaly"] == "Anomaly"]
plt.figure(figsize=(12, 5))
plt.scatter(
normal.index,
normal["water_level"],
label="Normal"
)
plt.scatter(
anomalies.index,
anomalies["water_level"],
label="Potential anomaly"
)
plt.xlabel("Observation")
plt.ylabel("Water Level (cm)")
plt.title("Illustrative Urban Water-Level Anomaly Detection")
plt.legend()
plt.grid(True)
plt.show()
The visualization allows us to inspect which readings the model has identified as unusual.
The model is not expected to identify every real-world problem correctly. Its output must be evaluated against labeled observations and domain knowledge.
Step 5: Extend the experiment
The simple model uses only water level.
A more realistic prototype could include:
features = [
"water_level",
"rainfall",
"rate_of_change",
"rolling_average",
"hour_of_day"
]
We could train the model using these features instead.
This may help distinguish a normal increase during heavy rainfall from an unusual increase under otherwise stable conditions.
However, the model needs representative historical data. Adding more features does not automatically improve performance.
7. From a local experiment to an AWS implementation
The previous example demonstrates the algorithm.
To move towards an AWS prototype, we can use the following implementation plan.
Step 1: Store historical sensor readings in Amazon S3.
Step 2: Prepare the data using Python and suitable preprocessing jobs.
Step 3: Train an anomaly detection model using SageMaker AI or a suitable custom training environment.
Step 4: Evaluate the model on separate historical data.
Step 5: Deploy the selected model using an appropriate SageMaker AI inference option.
Step 6: Connect the inference workflow to processed sensor events.
Step 7: Store anomaly scores and predictions for investigation.
Step 8: Use AWS Lambda and Amazon EventBridge to coordinate alert workflows.
Step 9: Use Amazon CloudWatch to monitor service health, processing failures, and operational metrics.
For continuous high-volume data, inference architecture should be designed around throughput, latency, batching, and cost. Not every incoming sensor reading needs a separate real-time model invocation.
A practical system might aggregate readings into short time windows before scoring them.
8. How do we evaluate an anomaly detection system?
An anomaly detection model should not be judged by accuracy alone.
In a city-scale monitoring application, the number of false alarms can be as important as the number of detected problems.
Consider these evaluation metrics:
Metric| Why it matters
Precision| How many flagged observations are genuine anomalies?
Recall| How many known anomalies did the model identify?
F1-score| Balances precision and recall
False-positive rate| How frequently does normal behavior trigger alerts?
Detection delay| How long does the system take to flag an event?
Processing latency| How quickly can incoming records be analyzed?
For example, a system that flags every unusual reading might achieve high recall but overwhelm city operators with false alarms.
The goal is to develop a system that detects meaningful changes while keeping the investigation workload manageable.
A robust evaluation dataset should contain:
- Normal operating periods
- Known incidents
- Seasonal changes
- Sensor faults
- Missing data
- Communication interruptions
- Rare and unusual events
It should also preserve time order when splitting training and test datasets to avoid future-data leakage.
9. The challenges of predicting urban problems
Changing normal behavior
Urban patterns change across weekdays, weekends, seasons, and special events.
A model trained on one period may not generalize to another.
Sensor malfunction
A faulty sensor can produce an anomaly that looks like a genuine infrastructure problem.
Sensor health checks should be included in the pipeline.
Rare events
Serious infrastructure incidents may be uncommon, making labeled training data difficult to obtain.
False alarms
Too many false alerts can reduce operator trust.
Model drift
Environmental conditions and infrastructure behavior change over time. The system needs a process to review whether its baseline remains relevant.
Explainability
Operators should understand why a reading was flagged, which signals contributed, and what evidence is available.
Safety and accountability
An anomaly score should not automatically trigger high-impact infrastructure actions. Alerts should be reviewed through appropriate operational procedures.
10. What have we achieved in this episode?
We have explored how a proposed urban intelligence platform can move from continuous data collection to anomaly detection.
The technical progression is:
Sensor Data → Feature Engineering → Machine Learning → Anomaly Scoring → Alert Evaluation → Human Investigation
We also created a local Python experiment using Isolation Forest to demonstrate how unusual readings can be identified.
The larger vision is to integrate this analytical capability into the AWS architecture introduced in the earlier episodes.
11. What comes next? Part 4 of the series
We now have a system that can identify unusual behavior.
But an important question remains.
What happens when one infrastructure problem is connected to several other parts of a city?
Suppose an unusual water-level reading occurs near a road, a drainage network, and a public facility.
How can an AI system understand these relationships?
In Part 4, we will explore:
Connecting the Dots: Building a Knowledge Graph of City Infrastructure.
We will examine:
- Infrastructure entities and relationships
- Graph database fundamentals
- Amazon Neptune
- Knowledge graph construction
- Connected infrastructure analysis
- Graph-based impact investigation
The city has learned to recognize unusual signals.
Now we will teach it how to connect the dots.
THE CITY THAT CAN FEEL — Seven days. Seven technical deep dives. One intelligent city vision.
References and further reading
1. "Amazon SageMaker AI – Random Cut Forest" ( https://docs.aws.amazon.com/sagemaker/latest/dg/rcf\_how-it-works.html )
2. "Amazon SageMaker AI – Real-Time Inference" ( https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints.html )
3. "Amazon SageMaker AI – Inference Options" ( https://docs.aws.amazon.com/sagemaker/latest/dg/deploy-model-options.html )
4. "Amazon Kinesis Data Streams with AWS Lambda" ( https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html )
5. "Amazon CloudWatch Documentation" ( https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html )
6. "AWS Prescriptive Guidance – Machine Learning Monitoring" ( https://docs.aws.amazon.com/prescriptive-guidance/latest/ml-operations-planning/monitoring.html )
Disclaimer: This article presents a proposed architecture and a local illustrative machine learning experiment. The Python-generated data is simulated, and no real-world predictive accuracy or emergency prevention capability is claimed. Any real deployment requires validated sensor data, domain-specific thresholds, operational testing, security reviews, and human oversight.
Series: THE CITY THAT CAN FEEL: Building an Artificial Nervous System for Smart Cities Using AWS (7 articles)
- …
- 3Detecting Problems Before They Become Emergencies | Part 3 This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article