Model Training and Evaluation (Philippines)

import sys
sys.path.append("../../")

import os

import uuid
import numpy as np
import geopandas as gpd
import pandas as pd
from shapely import wkt

from geowrangler import dhs
from povertymapping import settings, osm, ookla, nightlights
from povertymapping.dhs import generate_dhs_cluster_level_data
from povertymapping.osm import OsmDataManager
from povertymapping.ookla import OoklaDataManager
import getpass
import pickle

from sklearn.model_selection import train_test_split, KFold, RepeatedKFold
from sklearn.model_selection import GroupKFold, cross_val_predict, cross_val_score
from sklearn.metrics import r2_score
import matplotlib.pyplot as plt
import seaborn as sns

import shap
/home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/env/lib/python3.9/site-packages/geopandas/_compat.py:111: UserWarning: The Shapely GEOS version (3.10.3-CAPI-1.16.1) is incompatible with the GEOS version PyGEOS was compiled with (3.10.1-CAPI-1.16.0). Conversions between both will be slow.
  warnings.warn(
/home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/env/lib/python3.9/site-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
%reload_ext autoreload
%autoreload 2

Load Target Country From DHS data

# Set country-specific variables
country_osm = 'philippines'
ookla_year = 2019
nightlights_year = 2017
dhs_household_dta_path = settings.DATA_DIR/"dhs/ph/PHHR71DT/PHHR71FL.DTA"
dhs_geographic_shp_path = settings.DATA_DIR/"dhs/ph/PHGE71FL/PHGE71FL.shp"
dhs_gdf = generate_dhs_cluster_level_data(
    dhs_household_dta_path, 
    dhs_geographic_shp_path, 
    col_rename_config="ph",
    convert_geoms_to_bbox=True,
    bbox_size_km=2.4
).reset_index(drop=True)
dhs_gdf.explore()
Make this Notebook Trusted to load map: File -> Trust Notebook
dhs_gdf.head()
DHSCLUST Wealth Index DHSID DHSCC DHSYEAR CCFIPS ADM1FIPS ADM1FIPSNA ADM1SALBNA ADM1SALBCO ... DHSREGCO DHSREGNA SOURCE URBAN_RURA LATNUM LONGNUM ALT_GPS ALT_DEM DATUM geometry
0 1 -31881.608696 PH201700000001 PH 2017.0 NULL NULL NULL NULL NULL ... 15.0 ARMM GPS R 6.674652 122.109807 9999.0 10.0 WGS84 POLYGON ((122.09894 6.68544, 122.12067 6.68544...
1 2 -2855.375000 PH201700000002 PH 2017.0 NULL NULL NULL NULL NULL ... 15.0 ARMM GPS R 6.662256 122.132027 9999.0 5.0 WGS84 POLYGON ((122.12116 6.67305, 122.14289 6.67305...
2 3 -57647.047619 PH201700000003 PH 2017.0 NULL NULL NULL NULL NULL ... 15.0 ARMM GPS R 6.621822 122.179496 9999.0 47.0 WGS84 POLYGON ((122.16863 6.63261, 122.19036 6.63261...
3 4 -54952.666667 PH201700000004 PH 2017.0 NULL NULL NULL NULL NULL ... 15.0 ARMM GPS R 6.485298 122.137965 9999.0 366.0 WGS84 POLYGON ((122.12710 6.49609, 122.14883 6.49609...
4 6 -80701.695652 PH201700000006 PH 2017.0 NULL NULL NULL NULL NULL ... 15.0 ARMM GPS R 6.629457 121.916094 9999.0 151.0 WGS84 POLYGON ((121.90523 6.64025, 121.92696 6.64025...

5 rows × 22 columns

Set up Data Access

# Instantiate data managers for Ookla and OSM
# This auto-caches requested data in RAM, so next fetches of the data are faster.
osm_data_manager = OsmDataManager(cache_dir=settings.ROOT_DIR/"data/data_cache")
ookla_data_manager = OoklaDataManager(cache_dir=settings.ROOT_DIR/"data/data_cache")
# Log-in using EOG credentials
username = os.environ.get('EOG_USER',None)
username = username if username is not None else input('Username?')
password = os.environ.get('EOG_PASSWORD',None)
password = password if password is not None else getpass.getpass('Password?') 

# set save_token to True so that access token gets stored in ~/.eog_creds/eog_access_token
access_token = nightlights.get_eog_access_token(username,password, save_token=True)
2023-01-31 14:01:05.870 | INFO     | povertymapping.nightlights:get_eog_access_token:48 - Saving access_token to ~/.eog_creds/eog_access_token
2023-01-31 14:01:05.873 | INFO     | povertymapping.nightlights:get_eog_access_token:56 - Adding access token to environmentt var EOG_ACCESS_TOKEN

Generate Base Features

If this is your first time running this notebook for this specific area, expect a long runtime for the following cell as it will download and cache the ff. datasets from the internet.

  • OpenStreetMap Data from Geofabrik
  • Ookla Internet Speed Data
  • VIIRS nighttime lights data from NASA EOG

On subsequent runs, the runtime will be much faster as the data is already stored in your filesystem.

%%time
country_data = dhs_gdf.copy()

# Add in OSM features
country_data = osm.add_osm_poi_features(country_data, country_osm, osm_data_manager)
country_data = osm.add_osm_road_features(country_data, country_osm, osm_data_manager)

# Add in Ookla features
country_data = ookla.add_ookla_features(country_data, 'fixed', ookla_year, ookla_data_manager)
country_data = ookla.add_ookla_features(country_data, 'mobile', ookla_year, ookla_data_manager)

# Add in the nighttime lights features
country_data = nightlights.generate_nightlights_feature(country_data, '2017') 
2023-01-31 14:01:06.394 | INFO     | povertymapping.osm:download_osm_country_data:187 - OSM Data: Cached data available for philippines at /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/osm/philippines? True
2023-01-31 14:01:06.395 | DEBUG    | povertymapping.osm:load_pois:149 - OSM POIs for philippines being loaded from /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/osm/philippines/gis_osm_pois_free_1.shp
2023-01-31 14:01:42.655 | INFO     | povertymapping.osm:download_osm_country_data:187 - OSM Data: Cached data available for philippines at /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/osm/philippines? True
2023-01-31 14:01:42.659 | DEBUG    | povertymapping.osm:load_roads:168 - OSM Roads for philippines being loaded from /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/osm/philippines/gis_osm_roads_free_1.shp
2023-01-31 14:04:49.021 | DEBUG    | povertymapping.ookla:load_type_year_data:68 - Contents of data cache: []
2023-01-31 14:04:50.124 | INFO     | povertymapping.ookla:load_type_year_data:83 - Cached data available at /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/ookla/processed/2f858b388182d50703550c8ef9d321df.csv? True
2023-01-31 14:04:50.126 | DEBUG    | povertymapping.ookla:load_type_year_data:88 - Processed Ookla data for aoi, fixed 2019 (key: 2f858b388182d50703550c8ef9d321df) found in filesystem. Loading in cache.
2023-01-31 14:04:51.440 | DEBUG    | povertymapping.ookla:load_type_year_data:68 - Contents of data cache: ['2f858b388182d50703550c8ef9d321df']
2023-01-31 14:04:51.442 | INFO     | povertymapping.ookla:load_type_year_data:83 - Cached data available at /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/ookla/processed/5a45dc45080a935951e6c2b6c0052b13.csv? True
2023-01-31 14:04:51.443 | DEBUG    | povertymapping.ookla:load_type_year_data:88 - Processed Ookla data for aoi, mobile 2019 (key: 5a45dc45080a935951e6c2b6c0052b13) found in filesystem. Loading in cache.
2023-01-31 14:04:52.525 | INFO     | povertymapping.nightlights:get_clipped_raster:414 - Retrieving clipped raster file /home/jc_tm/.geowrangler/nightlights/clip/295bf47ce6753c7f06ab79012b769f2a.tif
CPU times: user 3min 19s, sys: 24.5 s, total: 3min 43s
Wall time: 3min 53s

Inspect the combined target country data

country_data.info()
<class 'geopandas.geodataframe.GeoDataFrame'>
Int64Index: 1213 entries, 0 to 1212
Data columns (total 83 columns):
 #   Column                             Non-Null Count  Dtype   
---  ------                             --------------  -----   
 0   DHSCLUST                           1213 non-null   int64   
 1   Wealth Index                       1213 non-null   float64 
 2   DHSID                              1213 non-null   object  
 3   DHSCC                              1213 non-null   object  
 4   DHSYEAR                            1213 non-null   float64 
 5   CCFIPS                             1213 non-null   object  
 6   ADM1FIPS                           1213 non-null   object  
 7   ADM1FIPSNA                         1213 non-null   object  
 8   ADM1SALBNA                         1213 non-null   object  
 9   ADM1SALBCO                         1213 non-null   object  
 10  ADM1DHS                            1213 non-null   float64 
 11  ADM1NAME                           1213 non-null   object  
 12  DHSREGCO                           1213 non-null   float64 
 13  DHSREGNA                           1213 non-null   object  
 14  SOURCE                             1213 non-null   object  
 15  URBAN_RURA                         1213 non-null   object  
 16  LATNUM                             1213 non-null   float64 
 17  LONGNUM                            1213 non-null   float64 
 18  ALT_GPS                            1213 non-null   float64 
 19  ALT_DEM                            1213 non-null   float64 
 20  DATUM                              1213 non-null   object  
 21  geometry                           1213 non-null   geometry
 22  poi_count                          1213 non-null   float64 
 23  atm_count                          1213 non-null   float64 
 24  atm_nearest                        1213 non-null   float64 
 25  bank_count                         1213 non-null   float64 
 26  bank_nearest                       1213 non-null   float64 
 27  bus_station_count                  1213 non-null   float64 
 28  bus_station_nearest                1213 non-null   float64 
 29  cafe_count                         1213 non-null   float64 
 30  cafe_nearest                       1213 non-null   float64 
 31  charging_station_count             1213 non-null   float64 
 32  charging_station_nearest           1213 non-null   float64 
 33  courthouse_count                   1213 non-null   float64 
 34  courthouse_nearest                 1213 non-null   float64 
 35  dentist_count                      1213 non-null   float64 
 36  dentist_nearest                    1213 non-null   float64 
 37  fast_food_count                    1213 non-null   float64 
 38  fast_food_nearest                  1213 non-null   float64 
 39  fire_station_count                 1213 non-null   float64 
 40  fire_station_nearest               1213 non-null   float64 
 41  food_court_count                   1213 non-null   float64 
 42  food_court_nearest                 1213 non-null   float64 
 43  fuel_count                         1213 non-null   float64 
 44  fuel_nearest                       1213 non-null   float64 
 45  hospital_count                     1213 non-null   float64 
 46  hospital_nearest                   1213 non-null   float64 
 47  library_count                      1213 non-null   float64 
 48  library_nearest                    1213 non-null   float64 
 49  marketplace_count                  1213 non-null   float64 
 50  marketplace_nearest                1213 non-null   float64 
 51  pharmacy_count                     1213 non-null   float64 
 52  pharmacy_nearest                   1213 non-null   float64 
 53  police_count                       1213 non-null   float64 
 54  police_nearest                     1213 non-null   float64 
 55  post_box_count                     1213 non-null   float64 
 56  post_box_nearest                   1213 non-null   float64 
 57  post_office_count                  1213 non-null   float64 
 58  post_office_nearest                1213 non-null   float64 
 59  restaurant_count                   1213 non-null   float64 
 60  restaurant_nearest                 1213 non-null   float64 
 61  social_facility_count              1213 non-null   float64 
 62  social_facility_nearest            1213 non-null   float64 
 63  supermarket_count                  1213 non-null   float64 
 64  supermarket_nearest                1213 non-null   float64 
 65  townhall_count                     1213 non-null   float64 
 66  townhall_nearest                   1213 non-null   float64 
 67  road_count                         1213 non-null   float64 
 68  fixed_2019_mean_avg_d_kbps_mean    878 non-null    float64 
 69  fixed_2019_mean_avg_u_kbps_mean    878 non-null    float64 
 70  fixed_2019_mean_avg_lat_ms_mean    878 non-null    float64 
 71  fixed_2019_mean_num_tests_mean     878 non-null    float64 
 72  fixed_2019_mean_num_devices_mean   878 non-null    float64 
 73  mobile_2019_mean_avg_d_kbps_mean   838 non-null    float64 
 74  mobile_2019_mean_avg_u_kbps_mean   838 non-null    float64 
 75  mobile_2019_mean_avg_lat_ms_mean   838 non-null    float64 
 76  mobile_2019_mean_num_tests_mean    838 non-null    float64 
 77  mobile_2019_mean_num_devices_mean  838 non-null    float64 
 78  avg_rad_min                        1213 non-null   float64 
 79  avg_rad_max                        1213 non-null   float64 
 80  avg_rad_mean                       1213 non-null   float64 
 81  avg_rad_std                        1213 non-null   float64 
 82  avg_rad_median                     1213 non-null   float64 
dtypes: float64(69), geometry(1), int64(1), object(12)
memory usage: 828.3+ KB
country_data.head()
DHSCLUST Wealth Index DHSID DHSCC DHSYEAR CCFIPS ADM1FIPS ADM1FIPSNA ADM1SALBNA ADM1SALBCO ... mobile_2019_mean_avg_d_kbps_mean mobile_2019_mean_avg_u_kbps_mean mobile_2019_mean_avg_lat_ms_mean mobile_2019_mean_num_tests_mean mobile_2019_mean_num_devices_mean avg_rad_min avg_rad_max avg_rad_mean avg_rad_std avg_rad_median
0 1 -31881.608696 PH201700000001 PH 2017.0 NULL NULL NULL NULL NULL ... 168.733664 204.390127 0.358840 0.008752 0.008752 0.226479 0.303841 0.257313 0.020025 0.260396
1 2 -2855.375000 PH201700000002 PH 2017.0 NULL NULL NULL NULL NULL ... 248.639351 303.828619 2.804412 0.198795 0.119334 0.261510 6.881082 1.390439 1.719010 0.452909
2 3 -57647.047619 PH201700000003 PH 2017.0 NULL NULL NULL NULL NULL ... 892.382403 714.202439 2.925917 0.075383 0.049202 0.224655 0.865518 0.343708 0.146519 0.288261
3 4 -54952.666667 PH201700000004 PH 2017.0 NULL NULL NULL NULL NULL ... NaN NaN NaN NaN NaN 0.203245 0.264794 0.227876 0.016931 0.226401
4 6 -80701.695652 PH201700000006 PH 2017.0 NULL NULL NULL NULL NULL ... NaN NaN NaN NaN NaN 0.232324 0.285085 0.250609 0.012259 0.246076

5 rows × 83 columns

Data Preparation

Split into labels and features

# Set parameters
label_col = 'Wealth Index'
# Split train/test data into features and labels

# For labels, we just select the target label column
labels = country_data[[label_col]]

# For features, drop all columns from the input country geometries
# If you need the cluster data, refer to country_data / country_test
input_dhs_cols = dhs_gdf.columns
features = country_data.drop(input_dhs_cols, axis=1)

features.shape, labels.shape
((1213, 61), (1213, 1))
# Clean features
# For now, just impute nans with 0
# TODO: Implement other cleaning steps
features = features.fillna(0)

Base Features List

The features can be subdivided by the source dataset

OSM

  • <poi type>_count: number of points of interest (POI) of a specified type in that area
    • ex. atm_count: number of atms in cluster
    • poi_count: number of all POIs of all types in cluster
  • <poi_type>_nearest: distance of nearest POI of the specified type
    • ex. atm_nearest: distance of nearest ATM from that cluster
  • OSM POI types included: atm, bank, bus_stations, cafe, charging_station, courthouse, dentist (clinic), fast_food, fire_station, food_court, fuel (gas station), hospital, library, marketplace, pharmacy, police, post_box, post_office, restaurant, social_facility, supermarket, townhall, road

Ookla

The network metrics features follow the following name convention:

<type>_<year>_<yearly aggregate>_<network variable>_<cluster aggregate>

  • type: kind of network connection measured
    • fixed: connection from fixed sources (landline, fiber, etc.)
    • mobile: connection from mobile devices
  • year: Year of source data
  • yearly aggregate: How data was aggregated into yearly data
    • Note: Ookla provides data per quarter, so a yearly mean takes the average across 4 quarters
    • For this model, we only aggregate by yearly mean
  • network variable: network characteristic described
    • avg_d_kbps: average download speed in kbps
    • avg_u_kbps: average upload speed in kbps
    • avg_lat_ms: average latency in ms
    • num_devices: number of devices measured
  • cluster aggregate: how the data was aggregated per cluster aggregate
    • Types: min, mean, max, median, std.
      • For this model: only mean is used
    • This is calculated using area zonal stats, which weighs the average by the intersection of the Ookla tile with the cluster geometry.

Ex. fixed_2019_mean_avg_d_kbps_median takes the cluster median of 2019 yearly average download speed.

Nightlights (VIIRS)

All nightlights features are taken as the zonal aggregate of the raster data per cluster

  • ex. avg_rad_mean: cluster mean of the average radiance
  • aggregations used: min, mean, max, median
features.info()
<class 'geopandas.geodataframe.GeoDataFrame'>
Int64Index: 1213 entries, 0 to 1212
Data columns (total 61 columns):
 #   Column                             Non-Null Count  Dtype  
---  ------                             --------------  -----  
 0   poi_count                          1213 non-null   float64
 1   atm_count                          1213 non-null   float64
 2   atm_nearest                        1213 non-null   float64
 3   bank_count                         1213 non-null   float64
 4   bank_nearest                       1213 non-null   float64
 5   bus_station_count                  1213 non-null   float64
 6   bus_station_nearest                1213 non-null   float64
 7   cafe_count                         1213 non-null   float64
 8   cafe_nearest                       1213 non-null   float64
 9   charging_station_count             1213 non-null   float64
 10  charging_station_nearest           1213 non-null   float64
 11  courthouse_count                   1213 non-null   float64
 12  courthouse_nearest                 1213 non-null   float64
 13  dentist_count                      1213 non-null   float64
 14  dentist_nearest                    1213 non-null   float64
 15  fast_food_count                    1213 non-null   float64
 16  fast_food_nearest                  1213 non-null   float64
 17  fire_station_count                 1213 non-null   float64
 18  fire_station_nearest               1213 non-null   float64
 19  food_court_count                   1213 non-null   float64
 20  food_court_nearest                 1213 non-null   float64
 21  fuel_count                         1213 non-null   float64
 22  fuel_nearest                       1213 non-null   float64
 23  hospital_count                     1213 non-null   float64
 24  hospital_nearest                   1213 non-null   float64
 25  library_count                      1213 non-null   float64
 26  library_nearest                    1213 non-null   float64
 27  marketplace_count                  1213 non-null   float64
 28  marketplace_nearest                1213 non-null   float64
 29  pharmacy_count                     1213 non-null   float64
 30  pharmacy_nearest                   1213 non-null   float64
 31  police_count                       1213 non-null   float64
 32  police_nearest                     1213 non-null   float64
 33  post_box_count                     1213 non-null   float64
 34  post_box_nearest                   1213 non-null   float64
 35  post_office_count                  1213 non-null   float64
 36  post_office_nearest                1213 non-null   float64
 37  restaurant_count                   1213 non-null   float64
 38  restaurant_nearest                 1213 non-null   float64
 39  social_facility_count              1213 non-null   float64
 40  social_facility_nearest            1213 non-null   float64
 41  supermarket_count                  1213 non-null   float64
 42  supermarket_nearest                1213 non-null   float64
 43  townhall_count                     1213 non-null   float64
 44  townhall_nearest                   1213 non-null   float64
 45  road_count                         1213 non-null   float64
 46  fixed_2019_mean_avg_d_kbps_mean    1213 non-null   float64
 47  fixed_2019_mean_avg_u_kbps_mean    1213 non-null   float64
 48  fixed_2019_mean_avg_lat_ms_mean    1213 non-null   float64
 49  fixed_2019_mean_num_tests_mean     1213 non-null   float64
 50  fixed_2019_mean_num_devices_mean   1213 non-null   float64
 51  mobile_2019_mean_avg_d_kbps_mean   1213 non-null   float64
 52  mobile_2019_mean_avg_u_kbps_mean   1213 non-null   float64
 53  mobile_2019_mean_avg_lat_ms_mean   1213 non-null   float64
 54  mobile_2019_mean_num_tests_mean    1213 non-null   float64
 55  mobile_2019_mean_num_devices_mean  1213 non-null   float64
 56  avg_rad_min                        1213 non-null   float64
 57  avg_rad_max                        1213 non-null   float64
 58  avg_rad_mean                       1213 non-null   float64
 59  avg_rad_std                        1213 non-null   float64
 60  avg_rad_median                     1213 non-null   float64
dtypes: float64(61)
memory usage: 619.8 KB

Model Training

# Set parameters
cv_col = 'ADM1NAME'
cv_num_splits = 5
cv_num_repeats = 5
train_test_seed = 42
test_size = 0.2

Create train/test cross-validation indices

# train_features, test_features, train_labels, test_labels = train_test_split(
#     features, labels, test_size=test_size, random_state=train_test_seed
# )

# Cross validation
print(f"Performing {cv_num_splits}-fold CV...")
cv = RepeatedKFold(n_splits=cv_num_splits, n_repeats=cv_num_repeats, random_state=train_test_seed)

print(cv.split(features))
Performing 5-fold CV...
<generator object _RepeatedSplits.split at 0x7f3d8cc795f0>

Instantiate model

For now, we will train a simple random forest model

from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators=100, random_state=train_test_seed, verbose=0)
model
RandomForestRegressor(random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

Evaluate model training using cross-validation

We evalute the model’s generalizability when training over different train/test splits

Ideally for R^2

  • We want a high mean: This means that we achieve a high model performance over the different train/test splits
  • We want a low standard deviation (std): This means that the model performance is stable over multiple training repetitions
R_cv = cross_val_score(model, features.values, labels.values.ravel(), cv=cv)
print("Cross validation scores are: ", sorted(R_cv))
cv_mean = round(np.array(R_cv).mean(), 2)
cv_std = round(np.array(R_cv).std(), 2)
print(f"Cross validation R^2 mean: {cv_mean}")
print(f"Cross validation R^2 std: {cv_std}")
Cross validation scores are:  [0.5294677566332617, 0.5391552185905704, 0.543278926472197, 0.5447281441026584, 0.5562541669133134, 0.5568586582805555, 0.5637788474374361, 0.5667912877726746, 0.5785468569997612, 0.5802442586120041, 0.5857832371271379, 0.5879801994412324, 0.5927537962070584, 0.5950396182036672, 0.6039177107289421, 0.6045825009349381, 0.6110967747533367, 0.6154970734372279, 0.6200274887865274, 0.624422779651163, 0.625771804024557, 0.6313835954119891, 0.6320135439052579, 0.6376161937003118, 0.6472793023895735]
Cross validation R^2 mean: 0.59
Cross validation R^2 std: 0.03

Train the final model

For training the final model, we train on all the available data.

model.fit(features.values, labels.values.ravel())
RandomForestRegressor(random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.

Model Evaluation

SHAP Feature Importance

explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(features)
shap_values
array([[ 1.42131634e+02,  2.45774057e+01, -1.08135322e+03, ...,
        -1.91553668e+03, -9.60443652e+02, -3.38104962e+03],
       [-9.46731453e+02,  1.39580566e+01, -5.65539891e+02, ...,
         1.05882950e+03,  3.22172503e+02, -2.18554002e+03],
       [-2.80953619e+00,  2.03494523e+01, -6.08893603e+02, ...,
         9.55855509e+02,  2.30219438e+02, -5.20196566e+03],
       ...,
       [-3.49639987e+02,  4.52311481e+01, -4.94156091e+02, ...,
         1.44365982e+03,  5.92012617e+02,  2.26132845e+03],
       [-3.03319414e+02,  1.16861106e+01, -9.92229066e+02, ...,
         9.93172172e+01,  6.01848516e+02, -6.65320602e+03],
       [-2.58408637e+02,  2.68403741e+01, -2.89553307e+02, ...,
        -5.02644705e+03, -1.78694282e+03, -7.63883647e+03]])
shap.summary_plot(shap_values, features, feature_names=features.columns, plot_type="bar")

shap.summary_plot(shap_values, features.values, feature_names=features.columns)
No data for colormapping provided via 'c'. Parameters 'vmin', 'vmax' will be ignored

Save Model

model_save_path = "./model_ph.pkl"
with open(model_save_path, "wb") as file:
    pickle.dump(model, file)