Model Training and Evaluation (Cambodia)

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

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 = "cambodia"
ookla_year = 2019
nightlights_year = 2014
dhs_household_dta_path = settings.DATA_DIR/"dhs/kh/KHHR73DT/KHHR73FL.DTA"
dhs_geographic_shp_path = settings.DATA_DIR/"dhs/kh/KHGE71FL/KHGE71FL.shp"
dhs_gdf = generate_dhs_cluster_level_data(
    dhs_household_dta_path, 
    dhs_geographic_shp_path, 
    col_rename_config="kh",
    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 -7443.192308 KH201400000001 KH 2014.0 CB NULL NULL NULL NULL ... 1.0 banteay mean chey CEN R 13.518676 103.028394 9999.0 11.0 WGS84 POLYGON ((103.01729 13.52947, 103.03949 13.529...
1 2 2622.678571 KH201400000002 KH 2014.0 CB NULL NULL NULL NULL ... 1.0 banteay mean chey CEN R 13.398398 102.953852 9999.0 23.0 WGS84 POLYGON ((102.94276 13.40919, 102.96495 13.409...
2 3 22167.920000 KH201400000003 KH 2014.0 CB NULL NULL NULL NULL ... 1.0 banteay mean chey CEN R 13.503451 102.996001 9999.0 13.0 WGS84 POLYGON ((102.98490 13.51424, 103.00710 13.514...
3 4 32241.826087 KH201400000004 KH 2014.0 CB NULL NULL NULL NULL ... 1.0 banteay mean chey CEN U 13.549399 103.071416 9999.0 14.0 WGS84 POLYGON ((103.06032 13.56019, 103.08252 13.560...
4 5 154111.500000 KH201400000005 KH 2014.0 CB NULL NULL NULL NULL ... 1.0 banteay mean chey CEN U 13.538865 103.028993 9999.0 15.0 WGS84 POLYGON ((103.01789 13.54966, 103.04009 13.549...

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:00:53.085 | INFO     | povertymapping.nightlights:get_eog_access_token:48 - Saving access_token to ~/.eog_creds/eog_access_token
2023-01-31 14:00:53.086 | 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, str(nightlights_year)) 
2023-01-31 14:00:53.415 | INFO     | povertymapping.osm:download_osm_country_data:187 - OSM Data: Cached data available for cambodia at /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/osm/cambodia? True
2023-01-31 14:00:53.421 | DEBUG    | povertymapping.osm:load_pois:149 - OSM POIs for cambodia 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/cambodia/gis_osm_pois_free_1.shp
2023-01-31 14:01:00.722 | INFO     | povertymapping.osm:download_osm_country_data:187 - OSM Data: Cached data available for cambodia at /home/jc_tm/project_repos/unicef-ai4d-poverty-mapping/notebooks/2023-01-17-initial-model-ph-mm-tl-kh/../../data/data_cache/osm/cambodia? True
2023-01-31 14:01:00.723 | DEBUG    | povertymapping.osm:load_roads:168 - OSM Roads for cambodia 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/cambodia/gis_osm_roads_free_1.shp
2023-01-31 14:01:31.359 | DEBUG    | povertymapping.ookla:load_type_year_data:68 - Contents of data cache: []
2023-01-31 14:01:31.365 | 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/37f570ebc130cb44f9dba877fbda74e2.csv? True
2023-01-31 14:01:31.368 | DEBUG    | povertymapping.ookla:load_type_year_data:88 - Processed Ookla data for aoi, fixed 2019 (key: 37f570ebc130cb44f9dba877fbda74e2) found in filesystem. Loading in cache.
2023-01-31 14:01:32.434 | DEBUG    | povertymapping.ookla:load_type_year_data:68 - Contents of data cache: ['37f570ebc130cb44f9dba877fbda74e2']
2023-01-31 14:01:32.437 | 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/1128a917060f7bb88c0a6260ed457091.csv? True
2023-01-31 14:01:32.440 | DEBUG    | povertymapping.ookla:load_type_year_data:88 - Processed Ookla data for aoi, mobile 2019 (key: 1128a917060f7bb88c0a6260ed457091) found in filesystem. Loading in cache.
2023-01-31 14:01:33.358 | INFO     | povertymapping.nightlights:get_clipped_raster:414 - Retrieving clipped raster file /home/jc_tm/.geowrangler/nightlights/clip/4791e78094ba7e323fd5814b3f094a84.tif
CPU times: user 48 s, sys: 1.64 s, total: 49.7 s
Wall time: 50.6 s

Inspect the combined target country data

country_data.info()
<class 'geopandas.geodataframe.GeoDataFrame'>
Int64Index: 611 entries, 0 to 610
Data columns (total 83 columns):
 #   Column                             Non-Null Count  Dtype   
---  ------                             --------------  -----   
 0   DHSCLUST                           611 non-null    int64   
 1   Wealth Index                       611 non-null    float64 
 2   DHSID                              611 non-null    object  
 3   DHSCC                              611 non-null    object  
 4   DHSYEAR                            611 non-null    float64 
 5   CCFIPS                             611 non-null    object  
 6   ADM1FIPS                           611 non-null    object  
 7   ADM1FIPSNA                         611 non-null    object  
 8   ADM1SALBNA                         611 non-null    object  
 9   ADM1SALBCO                         611 non-null    object  
 10  ADM1DHS                            611 non-null    float64 
 11  ADM1NAME                           611 non-null    object  
 12  DHSREGCO                           611 non-null    float64 
 13  DHSREGNA                           611 non-null    object  
 14  SOURCE                             611 non-null    object  
 15  URBAN_RURA                         611 non-null    object  
 16  LATNUM                             611 non-null    float64 
 17  LONGNUM                            611 non-null    float64 
 18  ALT_GPS                            611 non-null    float64 
 19  ALT_DEM                            611 non-null    float64 
 20  DATUM                              611 non-null    object  
 21  geometry                           611 non-null    geometry
 22  poi_count                          611 non-null    float64 
 23  atm_count                          611 non-null    float64 
 24  atm_nearest                        611 non-null    float64 
 25  bank_count                         611 non-null    float64 
 26  bank_nearest                       611 non-null    float64 
 27  bus_station_count                  611 non-null    float64 
 28  bus_station_nearest                611 non-null    float64 
 29  cafe_count                         611 non-null    float64 
 30  cafe_nearest                       611 non-null    float64 
 31  charging_station_count             611 non-null    float64 
 32  charging_station_nearest           611 non-null    float64 
 33  courthouse_count                   611 non-null    float64 
 34  courthouse_nearest                 611 non-null    float64 
 35  dentist_count                      611 non-null    float64 
 36  dentist_nearest                    611 non-null    float64 
 37  fast_food_count                    611 non-null    float64 
 38  fast_food_nearest                  611 non-null    float64 
 39  fire_station_count                 611 non-null    float64 
 40  fire_station_nearest               611 non-null    float64 
 41  food_court_count                   611 non-null    float64 
 42  food_court_nearest                 611 non-null    float64 
 43  fuel_count                         611 non-null    float64 
 44  fuel_nearest                       611 non-null    float64 
 45  hospital_count                     611 non-null    float64 
 46  hospital_nearest                   611 non-null    float64 
 47  library_count                      611 non-null    float64 
 48  library_nearest                    611 non-null    float64 
 49  marketplace_count                  611 non-null    float64 
 50  marketplace_nearest                611 non-null    float64 
 51  pharmacy_count                     611 non-null    float64 
 52  pharmacy_nearest                   611 non-null    float64 
 53  police_count                       611 non-null    float64 
 54  police_nearest                     611 non-null    float64 
 55  post_box_count                     611 non-null    float64 
 56  post_box_nearest                   611 non-null    float64 
 57  post_office_count                  611 non-null    float64 
 58  post_office_nearest                611 non-null    float64 
 59  restaurant_count                   611 non-null    float64 
 60  restaurant_nearest                 611 non-null    float64 
 61  social_facility_count              611 non-null    float64 
 62  social_facility_nearest            611 non-null    float64 
 63  supermarket_count                  611 non-null    float64 
 64  supermarket_nearest                611 non-null    float64 
 65  townhall_count                     611 non-null    float64 
 66  townhall_nearest                   611 non-null    float64 
 67  road_count                         611 non-null    float64 
 68  fixed_2019_mean_avg_d_kbps_mean    352 non-null    float64 
 69  fixed_2019_mean_avg_u_kbps_mean    352 non-null    float64 
 70  fixed_2019_mean_avg_lat_ms_mean    352 non-null    float64 
 71  fixed_2019_mean_num_tests_mean     352 non-null    float64 
 72  fixed_2019_mean_num_devices_mean   352 non-null    float64 
 73  mobile_2019_mean_avg_d_kbps_mean   449 non-null    float64 
 74  mobile_2019_mean_avg_u_kbps_mean   449 non-null    float64 
 75  mobile_2019_mean_avg_lat_ms_mean   449 non-null    float64 
 76  mobile_2019_mean_num_tests_mean    449 non-null    float64 
 77  mobile_2019_mean_num_devices_mean  449 non-null    float64 
 78  avg_rad_min                        611 non-null    float64 
 79  avg_rad_max                        611 non-null    float64 
 80  avg_rad_mean                       611 non-null    float64 
 81  avg_rad_std                        611 non-null    float64 
 82  avg_rad_median                     611 non-null    float64 
dtypes: float64(69), geometry(1), int64(1), object(12)
memory usage: 417.1+ 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 -7443.192308 KH201400000001 KH 2014.0 CB NULL NULL NULL NULL ... 400.517056 241.495925 1.642255 0.039165 0.031646 -0.057352 0.180403 0.021809 0.051515 0.000679
1 2 2622.678571 KH201400000002 KH 2014.0 CB NULL NULL NULL NULL ... NaN NaN NaN NaN NaN -0.058168 0.001848 -0.032420 0.016342 -0.035959
2 3 22167.920000 KH201400000003 KH 2014.0 CB NULL NULL NULL NULL ... 125.877798 148.723480 3.085707 0.070522 0.044572 -0.051005 0.034302 -0.014772 0.022527 -0.020030
3 4 32241.826087 KH201400000004 KH 2014.0 CB NULL NULL NULL NULL ... 119.104521 118.095280 4.132570 0.091835 0.061222 -0.043586 0.018604 -0.011368 0.016522 -0.010315
4 5 154111.500000 KH201400000005 KH 2014.0 CB NULL NULL NULL NULL ... 690.512786 455.932491 3.028787 0.192019 0.104213 -0.046168 0.641859 0.168993 0.181978 0.110213

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

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: ", 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.76611678 0.56366457 0.64054418 0.76618483 0.75246315 0.71716145
 0.65715568 0.70557958 0.64619356 0.79230307 0.74961658 0.73708033
 0.72618977 0.70777305 0.68184612 0.69430202 0.80162189 0.67652439
 0.66584225 0.7161133  0.65444036 0.64169101 0.7622332  0.74771696
 0.751735  ]
Cross validation R^2 mean: 0.71
Cross validation R^2 std: 0.06

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.51703186e+03, -2.99785351e+01,  2.06103228e+02, ...,
        -4.09378640e+03,  9.52566708e+02, -2.45878638e+04],
       [-1.26502355e+03, -3.33673184e+01, -1.12980593e+03, ...,
        -2.84363617e+03, -5.20995418e+02, -2.27357345e+04],
       [-1.05137166e+03, -3.39866575e+01,  6.50542716e+01, ...,
        -3.64638895e+03,  4.99895969e+02, -2.45155106e+04],
       ...,
       [-1.21486755e+03, -3.31721066e+01,  9.12608259e+03, ...,
        -5.31760559e+03, -1.86396874e+03, -2.52148312e+04],
       [-1.32038284e+03, -3.76122246e+01, -1.18354291e+03, ...,
        -3.19505368e+03,  1.23009854e+03, -3.04844195e+04],
       [-1.31895487e+03, -3.29175830e+01, -1.43539823e+03, ...,
        -6.26021778e+03, -3.43578347e+03, -3.51183508e+04]])
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_kh.pkl"
with open(model_save_path, "wb") as file:
    pickle.dump(model, file)