Skip to content
Snippets Groups Projects
Commit 99f23d97 authored by Pietro Zambelli's avatar Pietro Zambelli
Browse files

Update code to pre-process and perform and filter clusters

parent 6eeab2b0
Branches main
No related tags found
No related merge requests found
......@@ -40,80 +40,32 @@ The main structure of the repository is the follow:
- README.md
```
cd existing_repo
git remote add origin https://gitlab.inf.unibz.it/URS/justnature/clustering.git
git branch -M main
git push -uf origin main
```
## How to install and run the code
## Integrate with your tools
The python packages are managed by [`poetry`](https://python-poetry.org/), so ensure that `poetry` is properly installed in your machine.
- [ ] [Set up project integrations](https://gitlab.inf.unibz.it/URS/justnature/clustering/-/settings/integrations)
Then:
1. clone the repository: `git clone git@gitlab.inf.unibz.it:URS/justnature/clustering.git`;
2. move inside the new created folder `cd clustering`;
3. install the required python packages with: `poetry install`;
4. enable the virtualenv with: `poetry shell` or execute the python command instead of `python justclust/analysis/bolzano.py` use: `poetry run python justclust/analysis/bolzano.py`
## Collaborate with your team
## How to use
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
Under the folder [`justclust/analysis/`](justclust/analysis/) you find a python file for each CiPeLs (at the moment only [`bolzano.py`](justclust/analysis/bolzano.py)), once installed the python packages (see previous section), you can launch the analysis with:
`python justclust/analysis/bolzano.py`
## Test and Deploy
The analysis performed a first exploration of different data pre-processing preparing the data for the clustering task. All different pre-processing pipelines are defined in `get_preprocs` function available in [`justclust/explore/preprocs.py`](justclust/explore/preprocs.py), more than 300 pre-processing pipelines are tested.
Use the built-in continuous integration in GitLab.
The result of the pre-processing tests are written to an excel file in `report/{city}/scores_preprocess.xlsx` (e.g. `report/bolzano/scores_preprocess.xlsx`).
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
The file is used as cache, therefore the pre-processing is not computed again but load the result from the excel file, if you need to re-execute the pre-processing analysis move/rename/delete the excel file and launch the program again.
***
Once the pre-processing task is executed choose a pre-processing pipe line that you want to apply on your data before exploring the result of different clustering algorithms, therefore open the excel file, compare the different hopkins metrics and select a pre-processing pipeline of your interest. Copy the index key from the excel file into the `pre_key` variable in [`justclust/analysis/bolzano.py`](justclust/analysis/bolzano.py).
# Editing this README
If you launch the program again, the pre-processing will be read by the excel file and it will start exploring different clustering options and algorithms, as in the previous step all the clustering algorithms that are tested are defined by the function `get_algclusters` defined in [`justclust/explore/algclusters.py`](justclust/explore/algclusters.py), for each clustering algorithm several metrics are computed by the [`compute_metrics`](justclust/explore/algclusters.py) function (i.e. Silhouette score, Davies Bouldin score, Calinski Harabasz score).
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
To limit the amount of columns in the resulting geopackage file it is possible to define some criteria, like for instance the range of valid cluster to be identified, the thresholds for the min or max values.
To make the GPKG easier to handle and not too heavy the columns are split by algorithm and by number of clusters.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
import os
import sys
import pandas as pd
from justclust.data.bolzano import cols, read_data, wcols
# from justclust.explore.algclusters import explore_models
from justclust.data.bolzano import cols, read_data, sez_cols, wcols
from justclust.explore.algclusters import explore_models, get_algclusters
from justclust.explore.preprocs import ApplyW, explore_preprocs, get_preprocs
from justclust.paths.bolzano import report_dir
......@@ -20,10 +21,17 @@ selected = raw.loc[:, cols].dropna()
# %%
# Explore clustering pre-processing
# create a directory if does not exists
os.makedirs(report_dir, exist_ok=True)
# weighted = selected * wcols
apply_weight = ApplyW(wcols)
preprocs = get_preprocs(selected, apply_weight)
os.makedirs(report_dir, exist_ok=True)
# Select a small subset to test the whole workflow
# pkeys = sorted(preprocs.keys())[:10]
# preprocs = {k: preprocs[k] for k in pkeys}
prescorefile = report_dir / "scores_preprocess.xlsx"
if prescorefile.exists():
......@@ -33,22 +41,87 @@ else:
print(
f"Pre-processed file ({prescorefile}) not found, start computing the main metrics"
)
# weighted = selected * wcols
apply_weight = ApplyW(wcols)
pre_scores = explore_preprocs(selected)
pre_scores = explore_preprocs(selected, preprocs)
pre_scores.to_excel(prescorefile)
print("=" * 50)
print(f"BEST PRE-PROCESSING (10/{len(pre_scores)}):")
print(pre_scores.sort_values("hopkins", ascending=True).loc[:10, :])
print(
pre_scores.sort_values("hopkins", ascending=True)
.iloc[:10, :]
.loc[:, ["short_label"]]
)
print("-" * 50)
print("Hopkins statistics of main pre-processing options")
print(pre_scores["hopkins"].describe())
# explore_models(
# data: pd.DataFrame,
# cldf: gpd.GeoDataFrame,
# rdir: Path,
# models: Dict[str, Dict[str, Any]] = None,
# n_jobs: int=-1
# )
# %%
# select a preprocessing
pre_key = (
"s:RobustScaler(quantile_range=(2, 98))|"
"w:true|"
"d:DictionaryLearning(alpha=0.1, fit_algorithm='cd', n_jobs=-1)"
)
if pre_key not in preprocs.keys():
skeys = "\n".join([f" - {k!r}" for k in sorted(preprocs.keys())])
print("You must select a pre-processing available from this list:\n" f"{skeys}")
sys.exit(1)
pre = preprocs[pre_key]
# %%
# explore the clustering space
geo_out = raw.loc[selected.index, sez_cols]
models = get_algclusters(preprocs=pre)
sc, fi = explore_models(
data=selected,
cldf=geo_out,
rdir=report_dir,
models=models,
n_jobs=-1,
filters=[
("n_clusters", (5.0, 15.0)),
# silhouette_score: The best value is 1 and the worst value is -1.
# Values near 0 indicate overlapping clusters. Negative values generally
# indicate that a sample has been assigned to the wrong cluster, as a
# different cluster is more similar.
("silhouette", (0.5, None)),
# davies_bouldin_score: The minimum score is zero, with lower values
# indicating better clustering.
# ("davies bouldin", (None, 0.6)),
# calinski_harabasz_score: higher Calinski-Harabasz score relates
# to a model with better defined clusters
# ("calinski harabasz", (10, None)),
# mean_el_per_cl: if you need to filter clusters with a mean
# number of elements
# ("mean_el_per_cl", (10, None)),
# % covered by clusters: percentage o, f elements that have been assigned
# to a cluster
("% covered by clusters", (50, None)),
],
)
# split file to make them not too heavy
cc = [c for c in geo_out.columns if c not in sez_cols]
algs = sorted(set([c.split("__")[0].split("_")[-1] for c in cc]))
for alg in algs:
acols = [c for c in cc if alg in c]
if len(acols) > 20:
kl = [c.split("_")[0] for c in acols]
for k in kl:
klfile = report_dir / f"clusters_{alg}_{k}.gpkg"
kcols = [c for c in acols if c.startswith(k)]
print(f"Saving {klfile} with cols: {kcols}")
geo_out.loc[:, sez_cols + kcols].to_file(klfile, driver="GPKG")
# save all columns to open all the clusters
clfile = report_dir / f"clusters_{alg}.gpkg"
print(f"Saving {clfile}")
geo_out.to_file(clfile, driver="GPKG")
clscorefile = report_dir / "scores_clusters.xlsx"
sc.to_excel(clscorefile)
fimpfile = report_dir / "feature_importances.xlsx"
fi.to_excel(fimpfile)
......@@ -73,6 +73,7 @@ socio_perc_cols = [
"%Single",
]
# columns selected for the columns of the outputs
sez_cols = ["geometry", "SEZ", "SEZ2011", "COD_REG", "COD_ISTAT", "PRO_COM"]
# %%
......
from collections import Counter
from itertools import product
from pathlib import Path
from typing import Any, Callable, Dict, List, Tuple
from typing import Any, Callable, Dict, List, Optional, Tuple
import geopandas as gpd
import numpy as np
import pandas as pd
from hdbscan import HDBSCAN
from joblib import Parallel, delayed
from sklearn import ensemble as ens
from sklearn.metrics import (calinski_harabasz_score, davies_bouldin_score,
silhouette_score)
from sklearn.metrics import (
calinski_harabasz_score,
davies_bouldin_score,
silhouette_score,
)
from tqdm import tqdm
from justclust.hopkins import hopkins
......@@ -207,7 +211,16 @@ def feature_importances(
).sort_values(label, ascending=False)
def compute_metrics(model, data, labels, alpha_k=0.02):
def compute_metrics(
model, data: pd.DataFrame, labels: np.array, alpha_k: float = 0.02
) -> Tuple[
int,
Optional[float],
Optional[float],
Optional[float],
Optional[float],
Optional[float],
]:
k = len(set(labels)) - 1
# avoid to compute metrics for outliers, rm: -1
valid = labels >= 0
......@@ -303,7 +316,11 @@ def cls_counter(labels: List[int]) -> Tuple[pd.DataFrame, float]:
def model_worker(
mname: str, model: Dict[str, Any], opts: Dict[str, Any], tdata: pd.DataFrame
mname: str,
model: Dict[str, Any],
opts: Dict[str, Any],
tdata: pd.DataFrame,
rdir: Path = None,
) -> Tuple[str, str, List[Any], pd.DataFrame]:
"""Excute the single model and compute the main scores
......@@ -356,11 +373,95 @@ def model_worker(
return long_label, labels, xcores, fimp
def apply_filter(
sd: Dict[str, int | float], filters: List[Tuple[str, Tuple[float, float]]]
) -> List[bool]:
"""Check conditions to a dictionary. Return a list of booleans for each condition.
Parameters
----------
sd : Dict[str, int | float]
Dictionary with the values to be filtered
filters : List[Tuple[str, Tuple[float, float]]]
List of rules and checked to be verified
Returns
-------
List[bool]
List of booleans with the condition that are satisfied
Examples
--------
>>> apply_filter(
... dict(a=10, b=50, c=100),
... [
... ("a", (5, None)),
... ("b", (40, 60)),
... ("c", (None, 100)),
... ]
... )
[True, True, True]
>>> apply_filter(
... dict(a=10, b=50, c=100),
... [
... ("a", (15, None)),
... ("b", (60, 80)),
... ("c", (None, 90)),
... ]
... )
[False, Flase, False]
>>> apply_filter(
... dict(a=None, b=50, c=100),
... [
... ("a", (15, None)),
... ("b", (60, 80)),
... ("c", (None, 90)),
... ]
... )
[False, Flase, False]
"""
appends = []
for fname, (fmin, fmax) in filters:
val = sd[fname]
if val is None:
val = np.nan
if fmin is not None:
# fmin is defined check min value
if val >= fmin:
if fmax is not None:
# fmax is defined check max value
if val <= fmax:
appends.append(True)
else:
appends.append(False)
else:
# ignore max value
appends.append(True)
else:
# fmin value condition not correct
appends.append(False)
else:
# fmin not defined
if fmax is not None:
# fmax is defined
if val <= fmax:
# fmax is valid
appends.append(True)
else:
appends.append(False)
else:
# fmax is not defined
appends.append(True)
return appends
def explore_models(
data: pd.DataFrame,
cldf: gpd.GeoDataFrame,
rdir: Path,
models: Dict[str, Dict[str, Any]] = None,
filters: List[Tuple[str, Tuple[float, float]]] = None,
n_jobs: int = -1,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Execute all the models and save the labels' result
......@@ -424,44 +525,62 @@ def explore_models(
pll = Parallel(n_jobs=n_jobs, verbose=0)
tasks = [
(mname, model, opts, trans[mname])
(
mname,
model,
opts,
pd.DataFrame(trans[mname], index=data.index, columns=data.columns),
)
for mname, model in models.items()
for opts in model["opts"]
]
# DEBUG: on
# mname, model, opts, df = tasks[0]
# worker(mname, model, opts, df)
# DBEUG: off
res = pll(
delayed(worker)(mname, model, opts, trans[mname])
delayed(model_worker)(mname, model, opts, df)
for mname, model, opts, df in tqdm(tasks)
)
scores, fimps = [], []
cols = [
"model",
"label",
"long_label",
"% covered by clusters",
"n_of_cl1",
"mean_el_per_cl",
"std_el_per_cl",
"n_clusters",
"inertia",
"scaled_inertia",
"silhouette",
"davies bouldin",
"calinski harabasz",
]
scores, fimps, sels = [], [], []
for long_label, labels, xcores, fimp in res:
if filters is not None:
sd = {k: v for k, v in zip(cols, xcores)}
appends = apply_filter(sd, filters)
else:
# skip filters
appends = [
True,
]
# save results
scores.append(xcores)
fimps.append(fimp)
cldf.loc[data.index, long_label] = labels
# check conditions to save it in the vector layer only
# when filter conditions are satisfied
if all(appends):
cldf.loc[data.index, long_label] = labels
sels.append(True)
else:
sels.append(False)
sc = pd.DataFrame(
scores,
columns=[
"model",
"label",
"long_label",
"% covered by clusters",
"n_of_cl1",
"mean_el_per_cl",
"std_el_per_cl",
"n_clusters",
"inertia",
"scaled_inertia",
"silhouette",
"davies bouldin",
"calinski harabasz",
],
columns=cols,
)
sc["selected"] = sels
fi = pd.concat(fimps, axis=1)
return sc, fi
from hashlib import shake_128
from itertools import product
from typing import Any, Callable, Dict, List, Optional, Tuple
......@@ -64,8 +65,8 @@ def get_preprocs(selected=None, apply_weight=None):
]
]
if selected is not None:
scalers.append(pre.minmax_scale(selected))
# if selected is not None:
# scalers.append(pre.minmax_scale(selected))
ap_weights = (
[
......@@ -87,7 +88,7 @@ def get_preprocs(selected=None, apply_weight=None):
dec.DictionaryLearning(fit_algorithm="cd", alpha=0.1, n_jobs=-1),
]
preprocs = {
f"s:{s}|w:{w}|d:{d}": (s, w, d)
f"s:{s}|w:{'true' if w else 'false'}|d:{d}": (s, w, d)
for s, w, d in product(scalers, ap_weights, decomps)
}
return preprocs
......@@ -95,7 +96,7 @@ def get_preprocs(selected=None, apply_weight=None):
def preprocs_worker(
data: pd.DataFrame, plabel: str, palgs: List[Optional[Callable]]
) -> Dict[str, str | float]:
) -> Tuple[str, Dict[str, str | float]]:
"""Excute the single model and compute the main scores
Parameters
......@@ -143,15 +144,23 @@ def preprocs_worker(
hop = hopkins(df, sampling_size=150)
return dict(
short_label=f"s:{sn}|w:{wn}|d:{dn}",
long_label=f"s:{s!r}|w:{w!r}|d:{d!r}",
scaler_class=sn,
scaler_details=f"{s!r}",
weight_class=wn,
decomposer_class=dn,
decomposer_details=f"{d!r}",
hopkins=hop,
long_label = f"s:{s!r}|w:{w!r}|d:{d!r}"
pre_id = shake_128(long_label.encode()).hexdigest(4)
return (
plabel,
dict(
key=plabel,
pre_id=pre_id,
short_label=f"s:{sn}|w:{wn}|d:{dn}",
long_label=long_label,
scaler_class=sn,
scaler_details=f"{s!r}",
weight_class=wn,
decomposer_class=dn,
decomposer_details=f"{d!r}",
hopkins=hop,
),
)
......@@ -194,7 +203,10 @@ def explore_preprocs(
delayed(preprocs_worker)(data, plabel, palg) for plabel, palg in tqdm(tasks)
)
scores = pd.DataFrame.from_records(res)
index = [idx for idx, _ in res]
records = [rec for _, rec in res]
scores = pd.DataFrame.from_records(records, index=index)
# scores.set_index("pre_id", inplace=True)
scores.sort_values("hopkins", ascending=True, inplace=True)
return scores
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment