-
Notifications
You must be signed in to change notification settings - Fork 0
Collapse file tree
Files
Search this repository(forward slash) forward slash/
/
Copy pathregional_anomaly_detection2.py
More file actions
More file actions
Latest commit
553 lines (428 loc) · 18.2 KB
/
regional_anomaly_detection2.py
File metadata and controls
553 lines (428 loc) · 18.2 KB
You must be signed in to make or propose changes
More edit options
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Regional anomaly detection for Eurostat NUTS2 data (year 2022).
Outputs:
- regional_indicators.csv
- regional_anomaly_results.csv
- fig_pca_iforest.pdf
Requires:
pip install eurostat pandas numpy scikit-learn matplotlib
"""
from __future__ import annotations
import logging
import re
from typing import List
import numpy as np
import pandas as pd
import eurostat
from sklearn.preprocessing import StandardScaler
from sklearn.covariance import EmpiricalCovariance
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.svm import OneClassSVM
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn as sns
# ==========================================================
# Logging
# ==========================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)
# ==========================================================
# Helpers: Eurostat reshape and filters
# ==========================================================
def eurostat_wide_to_long(df: pd.DataFrame) -> pd.DataFrame:
"""
Convert Eurostat wide format (freq, unit, geo\\TIME_PERIOD, 2000, 2001, ..., 2023)
to long format with columns: freq, unit, geo, time, values.
If the DataFrame already has a 'time' column, it is returned unchanged.
"""
if "time" in df.columns:
return df
year_cols = [c for c in df.columns if re.fullmatch(r"\d{4}", str(c))]
if not year_cols:
raise ValueError(
f"Could not find year columns in Eurostat data. "
f"Columns: {df.columns.tolist()}"
)
id_cols = [c for c in df.columns if c not in year_cols]
df_long = df.melt(
id_vars=id_cols,
value_vars=year_cols,
var_name="time",
value_name="values",
)
if "geo\\TIME_PERIOD" in df_long.columns:
df_long = df_long.rename(columns={"geo\\TIME_PERIOD": "geo"})
df_long["time"] = df_long["time"].astype(str)
return df_long
def filter_nuts2_and_year(df: pd.DataFrame, year: int, time_col: str = "time") -> pd.DataFrame:
"""
Filter Eurostat long-format DataFrame to:
- a single reference year
- NUTS2 regions (geo codes length == 4, e.g. RO32, DE21)
"""
df = df.copy()
df[time_col] = df[time_col].astype(str)
df = df[df[time_col] == str(year)]
df = df[df["geo"].notna()]
# Keep only NUTS2 (4-char codes)
df["geo"] = df["geo"].astype(str)
df = df[df["geo"].str.len() == 4]
return df
# ==========================================================
# Download functions
# ==========================================================
def download_gdp_pc(year: int) -> pd.DataFrame:
"""
GDP per capita in PPS at NUTS2 from nama_10r_2gdp.
Try units:
- PPS_HAB_EU27_2020
- PPS_EU27_2020_HAB
- PPS_HAB
"""
logging.info("Downloading GDP per capita (PPS) from nama_10r_2gdp ...")
df = eurostat.get_data_df("nama_10r_2gdp")
df = eurostat_wide_to_long(df)
units = sorted(df["unit"].unique().tolist())
logging.info(f"Available units in nama_10r_2gdp: {units}")
preferred_units = ["PPS_HAB_EU27_2020", "PPS_EU27_2020_HAB", "PPS_HAB"]
chosen_unit = None
for u in preferred_units:
if u in units:
chosen_unit = u
break
if chosen_unit is None:
raise ValueError(f"No expected PPS per capita unit found. Units: {units}")
logging.info(f"Using unit = {chosen_unit} for GDP per capita in PPS")
df = df[df["unit"] == chosen_unit]
df = filter_nuts2_and_year(df, year)
df = df[["geo", "time", "values"]].rename(columns={"values": "gdp_pc_pps"})
return df
def download_unemployment_rate(year: int) -> pd.DataFrame:
"""
Unemployment rate 15–74 at NUTS2:
dataset: lfst_r_lfu3rt
filter: sex = T, age = Y15-74, unit = PC
"""
logging.info("Downloading unemployment rate from lfst_r_lfu3rt ...")
df = eurostat.get_data_df("lfst_r_lfu3rt")
df = eurostat_wide_to_long(df)
df = df[
(df["sex"] == "T") &
(df["age"] == "Y15-74") &
(df["unit"] == "PC")
]
df = filter_nuts2_and_year(df, year)
df = df[["geo", "time", "values"]].rename(columns={"values": "unemployment_rate"})
return df
def download_tertiary_share(year: int) -> pd.DataFrame:
"""
Share of population with tertiary education 25–64 at NUTS2:
dataset: edat_lfse_04
filter: sex = T, age = Y25-64, isced11 = ED5-8, unit = PC
"""
logging.info("Downloading tertiary education share from edat_lfse_04 ...")
df = eurostat.get_data_df("edat_lfse_04")
df = eurostat_wide_to_long(df)
df = df[
(df["sex"] == "T") &
(df["age"] == "Y25-64") &
(df["isced11"] == "ED5-8") &
(df["unit"] == "PC")
]
df = filter_nuts2_and_year(df, year)
df = df[["geo", "time", "values"]].rename(columns={"values": "tertiary_share_25_64"})
return df
def download_population_density(year: int) -> pd.DataFrame:
"""
Population density at NUTS2:
dataset: demo_r_d3dens
"""
logging.info("Downloading population density from demo_r_d3dens ...")
df = eurostat.get_data_df("demo_r_d3dens")
df = eurostat_wide_to_long(df)
df = filter_nuts2_and_year(df, year)
df = df[["geo", "time", "values"]].rename(columns={"values": "pop_density"})
return df
def build_regional_dataset(year: int) -> pd.DataFrame:
"""
Download all indicators for the specified year and merge by (geo, time).
Returns columns:
region_code, year, gdp_pc_pps, unemployment_rate, tertiary_share_25_64
"""
logging.info(f"Building regional dataset for year {year} ...")
df_gdp = download_gdp_pc(year)
df_unemp = download_unemployment_rate(year)
df_tert = download_tertiary_share(year)
df_pop = download_population_density(year)
# Merge step-by-step
df = df_gdp.copy()
for other in [df_unemp, df_tert, df_pop]:
df = pd.merge(df, other, on=["geo", "time"], how="outer")
# Rename and basic cleaning
df = df.rename(columns={"geo": "region_code", "time": "year"})
df["year"] = df["year"].astype(int)
# Keep only valid NUTS2 region codes: non-null, length 4
df = df[df["region_code"].notna()].copy()
df["region_code"] = df["region_code"].astype(str)
df = df[df["region_code"].str.len() == 4].copy()
indicator_cols = ["gdp_pc_pps", "unemployment_rate", "tertiary_share_25_64", "pop_density"]
# Collapse duplicates per region_code: first non-null per column
def first_non_null(series: pd.Series):
return series.dropna().iloc[0] if series.dropna().size > 0 else np.nan
df = df.sort_values(["region_code", "year"])
df = df.groupby("region_code", as_index=False).agg(
{
"year": "first",
"gdp_pc_pps": first_non_null,
"unemployment_rate": first_non_null,
"tertiary_share_25_64": first_non_null,
"pop_density": first_non_null,
}
)
# Drop rows where all indicators are NaN
all_nan_rows = df[indicator_cols].isna().all(axis=1)
if all_nan_rows.any():
logging.info(f"Dropping {all_nan_rows.sum()} rows with all indicators NaN")
df = df[~all_nan_rows].copy()
return df
# ==========================================================
# Preprocessing (no duplication of original columns)
# ==========================================================
def preprocess_indicators(df: pd.DataFrame, indicator_cols: List[str]):
"""
Transform skewed variables, impute missing values, and standardise indicators.
Returns:
df_std: dataframe with std_ columns only (same index as df)
scaler: fitted StandardScaler
"""
# Work only on a numeric copy
X = df[indicator_cols].copy()
# Log-transform skewed GDP-per-capita indicator
skewed_candidates = ["gdp_pc_pps"]
for col in indicator_cols:
if col in skewed_candidates and X[col].notna().any():
min_val = X[col].min()
shift = 1.0 - min_val if (pd.notna(min_val) and min_val <= 0) else 0.0
X[col] = np.log(X[col] + shift)
# Median imputation
for col in indicator_cols:
median_val = X[col].median()
X[col] = X[col].fillna(median_val)
# Sanity check: no NaNs allowed now
if X.isna().any().any():
bad_cols = X.columns[X.isna().any()].tolist()
raise ValueError(f"NaNs remain in columns after imputation: {bad_cols}")
scaler = StandardScaler()
X_std = scaler.fit_transform(X.values)
df_std = pd.DataFrame(X_std, columns=[f"std_{c}" for c in indicator_cols], index=df.index)
return df_std, scaler
# ==========================================================
# Classical outlier detection
# ==========================================================
def compute_univariate_z_outliers(df_std: pd.DataFrame, indicator_cols: List[str], threshold: float = 3.0) -> pd.Series:
df = df[df["region_code"].astype(str).str.len() == 4].copy()
# Convert flags to bool
flag_cols = ['flag_zscore','flag_mahal','flag_iforest','flag_lof','flag_ocsvm']
for col in flag_cols:
df[col] = df[col].astype(bool)
# Count number of flags
df["flag_count"] = df[flag_cols].sum(axis=1)
# Keep only regions with >=3 flags (the true anomalies)
anom = df[df["flag_count"] >= 3].copy()
# Deduplicate (first occurrence of each NUTS2 region)
anom = anom.groupby("region_code").first().reset_index()
# ----------------------------------------------------------
# Select the indicator columns
# ----------------------------------------------------------
indicators = ["gdp_pc_pps", "unemployment_rate", "pop_density", "tertiary_share_25_64"]
# Extract indicator matrix
X = anom[indicators].copy()
# Standardize indicators
scaler = StandardScaler()
X_std = scaler.fit_transform(X)
# Build heatmap DataFrame with region_code as index
heat_df = pd.DataFrame(
X_std,
columns=["GDP per capita (std)", "Unemployment rate (std)", "Population density", "Tertiary education (std)"],
index=anom["region_code"]
)
# ----------------------------------------------------------
# Plot heatmap
# ----------------------------------------------------------
plt.figure(figsize=(8, 8))
ax = sns.heatmap(
heat_df,
cmap="coolwarm",
center=0,
linewidths=0.5,
linecolor="grey",
cbar_kws={"label": "Standardized value (z-score)"}
)
# Axis titles
plt.title(
"Standardized Indicators for Anomalous NUTS2 Regions (2022)",
fontsize=16
)
plt.xlabel("Indicators", fontsize=14)
plt.ylabel("Region", fontsize=14)
# Tick labels (x = indicators, y = regions)
plt.xticks(fontsize=12, rotation=45, ha="right")
plt.yticks(fontsize=12)
# Colour bar label + tick labels
cbar = ax.collections[0].colorbar
cbar.ax.set_ylabel("Standardized value (z-score)", fontsize=14)
cbar.ax.tick_params(labelsize=12)
plt.tight_layout()
plt.savefig("heatmap_anomalies.pdf")
plt.close()
print("Saved heatmap to heatmap_anomalies.pdf")
if __name__ == "__main__":
main()