import geopandas as gpd
import matplotlib.pyplot as plt
from geopy.geocoders import Nominatim
import requests
from bs4 import BeautifulSoup
import re
from tqdm import tqdm
from shapely.geometry import Point, box
import json
import pandas as pd
import numpy as np
import rasterio
import warnings
from scipy.spatial import cKDTree
from rasterio.transform import from_origin
from rasterio.features import rasterize
from rasterio.warp import reproject, Resampling
import os
import rasterio.mask
import matplotlib.colors as mcolors
import matplotlib.patheffects as patheffects
from pykrige.uk import UniversalKriging
from xgboost import XGBRegressor # Integrated XGBoost
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, StackingRegressor
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import GridSearchCV, cross_validate, cross_val_score
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, median_absolute_error, explained_variance_score
from sklearn.pipeline import Pipeline
from datetime import datetime
from scipy.ndimage import gaussian_filter, distance_transform_edt
import pytz
import glob
import math
import joblib # For model saving/loading
for row in table_rows:
columns = row.find_all('td')
if len(columns) > 1:
station = columns[0].get_text(strip=True)
temperature = columns[1].get_text(strip=True)
if temperature != "-":
stations.append(station) # Keep original station names
temperatures.append(temperature)
response = requests.get(url, params=params)
if response.status_code != 200:
print(f"Error fetching Netatmo data: {response.status_code}")
return [], [], []
data = json.loads(response.text)
stations = []
temperatures = []
coordinates = []
List of cities to exclude
excluded_cities = ["Płońsk", "Łochów"]
for station in data.get('body', []):
place = station.get('place', {})
location = place.get('location')
if location:
lon, lat = location
if is_in_masovian(lat, lon):
city = place.get('city', 'Unknown')
if city in excluded_cities:
# Skip this station
continue
for module, module_data in station.get('measures', {}).items():
if 'temperature' in module_data.get('type', []):
res = module_data.get('res', {})
if res:
latest_timestamp = max(res.keys())
temperature = res[latest_timestamp][0]
stations.append(city)
temperatures.append(temperature)
coordinates.append((lat, lon))
break
for item in data:
statName = item.get('statName')
temp = item.get('temp')
if statName and temp and statName.upper() in target_stations:
stations.append(statName)
temperatures.append(temp)
station_ids.append(item.get('statId', 'Unknown'))
for netatmo_point, netatmo_temp in zip(netatmo_points, netatmo_temperatures):
distance, index = trax_tree.query(netatmo_point)
if distance > distance_threshold:
netatmo_filtered_coords.append(tuple(netatmo_point))
netatmo_filtered_temperatures.append(netatmo_temp)
modis_day_files = sorted(glob.glob(os.path.join(modis_day_folder, '*.tif')))
modis_day_arrays = []
modis_day_transform = None
for modis_file in modis_day_files:
with rasterio.open(modis_file) as src:
data = src.read(1)
Replace fill values with np.nan
fill_value = src.nodata
if fill_value is None:
If nodata is not set, check for common fill values
data = np.where((data == -9999) | (data <= -1e20), np.nan, data)
else:
data = np.where(data == fill_value, np.nan, data)
modis_day_arrays.append(data)
if modis_day_transform is None:
modis_day_transform = src.transform
if modis_day_arrays:
modis_day_stack = np.stack(modis_day_arrays)
modis_day_data = np.nanmean(modis_day_stack, axis=0)
else:
modis_day_data = None
Read and stack MODIS night data
modis_night_files = sorted(glob.glob(os.path.join(modis_night_folder, '*.tif')))
modis_night_arrays = []
modis_night_transform = None
for modis_file in modis_night_files:
with rasterio.open(modis_file) as src:
data = src.read(1)
# Replace fill values with np.nan
fill_value = src.nodata
if fill_value is None:
data = np.where((data == -9999) | (data <= -1e20), np.nan, data)
else:
data = np.where(data == fill_value, np.nan, data)
modis_night_arrays.append(data)
if modis_night_transform is None:
modis_night_transform = src.transform
if modis_night_arrays:
modis_night_stack = np.stack(modis_night_arrays)
modis_night_data = np.nanmean(modis_night_stack, axis=0)
else:
modis_night_data = None
Define a function to compute the cooling effect of water bodies based on the hour of the day
def compute_water_body_cooling_effect(hour):
"""
Computes the cooling effect of water bodies based on the hour of the day.
Cooling effect varies between -1°C during the day to -4°C at night.
"""
Normalize hour to range 0 to 24
hour = hour % 24
Use a cosine function to model the cooling effect
Peak cooling at midnight (hour=0), minimal cooling at noon (hour=12)
for station, temperature in zip(trax_stations, trax_temperatures):
cleaned_station = cleaned_station_dict[station]
# Exclude certain stations during daytime
# if is_daytime and cleaned_station in exclude_trax_stations_daytime_cleaned:
# continue # Skip this station
cleaned_temperature = clean_temperature(temperature)
if cleaned_station in trax_coords and cleaned_temperature is not None:
lat, lon = trax_coords[cleaned_station]
trax_filtered_stations.append(cleaned_station)
trax_filtered_temperatures.append(cleaned_temperature)
trax_geometries.append(Point(lon, lat))
for station, temperature, coord in zip(netatmo_stations, netatmo_temperatures, netatmo_coords):
if isinstance(temperature, (int, float)) and coord is not None:
netatmo_filtered_coords.append(coord)
netatmo_filtered_temperatures.append(temperature)
netatmo_filtered_stations.append(station)
if len(netatmo_filtered_coords) > 0:
netatmo_geometries = [Point(lon, lat) for lat, lon in netatmo_filtered_coords]
netatmo_gdf = gpd.GeoDataFrame({
'Station': netatmo_filtered_stations,
'Temperature': netatmo_filtered_temperatures,
'Source': 'Netatmo'
}, geometry=netatmo_geometries, crs="EPSG:4326")
else:
netatmo_gdf = gpd.GeoDataFrame(columns=['Station', 'Temperature', 'Source', 'geometry'], crs="EPSG:4326")
for station, temperature in zip(imgw_stations, imgw_temperatures):
cleaned_temperature = clean_temperature(temperature)
if station in imgw_coords and cleaned_temperature is not None:
lat, lon = imgw_coords[station]
imgw_filtered_stations.append(station)
imgw_filtered_temperatures.append(cleaned_temperature)
imgw_geometries.append(Point(lon, lat))
1: 'Urban', # Continuous urban fabric
2: 'Urban', # Discontinuous urban fabric
3: 'Industrial', # Industrial or commercial units
4: 'Infrastructure', # Road and rail networks and associated land
5: 'Port', # Port areas (if applicable)
6: 'Airport', # Airports
Mining and extraction areas
7: 'Mine', # Mineral extraction sites
8: 'Dump', # Dump sites
9: 'Construction', # Construction sites
Urban green areas
10: 'Green Urban', # Green urban areas
11: 'Sport Leisure', # Sport and leisure facilities
Agricultural areas
12: 'Arable Land', # Non-irrigated arable land
16: 'Orchards', # Fruit trees and berry plantations
18: 'Pastures', # Pastures
20: 'Complex Cultivation', # Complex cultivation patterns
21: 'Agro-Forest Mix', # Land principally occupied by agriculture, with significant areas of natural vegetation
Ensure that both datasets have the same dummy columns
missing_cols = set(land_cover_dummies_stations.columns) - set(land_cover_dummies_grid.columns)
for col in missing_cols:
grid_gdf[col] = 0
missing_cols = set(land_cover_dummies_grid.columns) - set(land_cover_dummies_stations.columns)
for col in missing_cols:
stations_gdf[col] = 0
Convert negative scores to positive where necessary
cv_metrics = {}
for key in scoring_metrics.keys():
if key in ['MAE', 'MSE', 'RMSE', 'Median_Err']:
# Convert negative to positive
cv_metrics[key] = -cv_results[f'test_{key}']
else:
# Keep as is (R² and Explained Variance)
cv_metrics[key] = cv_results[f'test_{key}']
Calculate mean and standard deviation for each metric
metric_summary = {}
for metric, values in cv_metrics.items():
mean_val = np.mean(values)
std_val = np.std(values)
metric_summary[metric] = (mean_val, std_val)
Print detailed performance metrics
print("\nDetailed Cross-Validation Performance Metrics:")
print("---------------------------------------------")
for metric, (mean, std) in metric_summary.items():
print(f"{metric}: {mean:.3f} ± {std:.3f}")
print("---------------------------------------------")
Get feature importances from the stacking regressor
Note: In stacking, we cannot directly get feature importances from the meta-model for the original features.
However, we can extract importances from the base estimators if they provide them.
feature_importances = {}
for (name, ), fitted_estimator in zip(
best_pipeline.named_steps['stack'].estimators,
best_pipeline.named_steps['stack'].estimators):
if hasattr(fitted_estimator, 'feature_importances_'):
feature_importances[name] = fitted_estimator.feature_importances_
Print feature importances for base estimators
print("\nFeature importances from base estimators in the Stacking Regressor:")
for name, importances in feature_importances.items():
feature_names = X.columns
importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importances})
importance_df = importance_df.sort_values('Importance', ascending=False)
print(f"\n{name} Feature Importances:")
print(importance_df)
Create grid dataframe
Already converted to grid_gdf earlier
Running Model Progress Bar
with tqdm(total=100, desc='Running Model', unit='%', ncols=80) as pbar:
# Retrieve elevations from DEM
grid_gdf['Elevation'] = get_elevation_at_points(
grid_gdf.geometry,
dem_data=dem_data,
dem_transform=dem_transform
)
pbar.update(12)
# Retrieve tree cover density from forest cover raster
grid_gdf['Tree_Cover'] = get_raster_value_at_points(
grid_gdf.geometry,
raster_data=forest_data,
raster_transform=forest_transform
)
pbar.update(12)
# Calculate distance to water bodies for grid points
grid_gdf['Distance_to_Water'] = get_raster_value_at_points(
grid_gdf.geometry,
raster_data=distance_to_water_array,
raster_transform=water_transform
)
pbar.update(12)
# Retrieve water body data at grid points
grid_gdf['Water_Body'] = get_water_body_at_points(
grid_gdf.geometry,
water_data=water_data,
water_transform=water_transform
)
pbar.update(12)
# Retrieve population density at grid points
grid_gdf['Population_Density'] = get_raster_value_at_points(
grid_gdf.geometry,
raster_data=pop_density_data,
raster_transform=pop_density_transform
)
pbar.update(8)
# Retrieve human settlement data at grid points
grid_gdf['Built_Up'] = get_raster_value_at_points(
grid_gdf.geometry,
raster_data=human_settlement_data,
raster_transform=human_settlement_transform
)
pbar.update(8)
# Handle missing values
grid_gdf = grid_gdf.dropna(subset=['Elevation', 'Tree_Cover', 'Distance_to_Water', 'Population_Density', 'Built_Up'])
pbar.update(6)
# Include MODIS_LST in grid_gdf (Already included)
# Prepare data for regression prediction
# Include land cover dummy variables
for col in land_cover_dummies_stations.columns:
if col not in grid_gdf.columns:
grid_gdf[col] = 0
X_grid = grid_gdf[feature_columns]
# Handle infinite values in X_grid
X_grid = X_grid.replace([np.inf, -np.inf], np.nan)
# Handle NaNs in X_grid
X_grid = X_grid.fillna(method='ffill').fillna(method='bfill')
# Ensure that all values are finite
# Predict using the trained stacking regressor
predictions = best_pipeline.predict(X_grid)
grid_gdf['Predicted_Temperature'] = predictions
pbar.update(10)
# Calculate residuals at station locations
stations_gdf['Predicted_Temperature'] = best_pipeline.predict(X)
stations_gdf['Residual'] = stations_gdf['Temperature'] - stations_gdf['Predicted_Temperature']
# Force residuals to zero at IMGW stations
stations_gdf.loc[stations_gdf['Source'] == 'IMGW', 'Residual'] = 0
# Adjust anomalously large residuals to reduce their impact
lower_percentile = np.percentile(stations_gdf['Residual'], 5)
upper_percentile = np.percentile(stations_gdf['Residual'], 95)
# Cap the residuals
stations_gdf['Adjusted_Residual'] = stations_gdf['Residual'].clip(lower=lower_percentile, upper=upper_percentile)
# Remove duplicates by prioritizing IMGW data
data = stations_gdf.copy()
# Sort by priority (higher priority first)
data = data.sort_values('Priority', ascending=False)
# Group by coordinates and keep the first record in each group (highest priority)
data = data.groupby(['X', 'Y'], as_index=False).first()
# After performing Universal Kriging:
# Perform Universal Kriging using Adjusted Residual
uk = UniversalKriging(
x=data['X'].values,
y=data['Y'].values,
z=data['Adjusted_Residual'].values,
variogram_model='spherical',
nlags=40, # Increased number of lags
verbose=False
)
z, ss = uk.execute(
'points',
grid_gdf['X'].values,
grid_gdf['Y'].values
)
grid_gdf['Residual'] = z
grid_gdf['Kriging_Variance'] = ss
# Handle NaNs in residuals by filling them with zero
grid_gdf['Residual'].fillna(0, inplace=True)
# Set residuals over water bodies to zero
grid_gdf.loc[grid_gdf['Water_Body'] == 1, 'Residual'] = 0
# Final temperature estimation
grid_gdf['Temperature'] = grid_gdf['Predicted_Temperature'] + grid_gdf['Residual']
# Save a copy of the temperature before ECOSTRESS adjustments
grid_gdf['Temperature_No_ECOSTRESS'] = grid_gdf['Temperature'].copy()
# Topographic Cooling Effect
max_cooling_effect = 3.0 # Maximum cooling effect in degrees Celsius
# Normalize elevation to range from 0 to 1
elevation_min = grid_gdf['Elevation'].min()
elevation_max = grid_gdf['Elevation'].max()
grid_gdf['Normalized_Elevation'] = (grid_gdf['Elevation'] - elevation_min) / (elevation_max - elevation_min)
# Compute the topographic cooling effect
grid_gdf['Topographic_Cooling'] = grid_gdf['Normalized_Elevation'] * max_cooling_effect * (1 - is_daytime)
# Ensure topographic cooling is not applied over water bodies
grid_gdf.loc[grid_gdf['Water_Body'] == 1, 'Topographic_Cooling'] = 0
# Apply the topographic cooling effect to the temperature
grid_gdf['Temperature'] -= grid_gdf['Topographic_Cooling']
# ECOSTRESS Adjustments
# Retrieve ECOSTRESS LST values at grid points (no changes here)
grid_gdf['ECOSTRESS_LST'] = get_raster_value_at_points(
grid_gdf.geometry,
raster_data=ecostress_data,
raster_transform=ecostress_transform
)
# Handle NaNs in ECOSTRESS_LST by filling with MODIS_LST values or the mean value (no changes here)
grid_gdf['ECOSTRESS_LST'] = grid_gdf.apply(
lambda row: row['ECOSTRESS_LST'] if not np.isnan(row['ECOSTRESS_LST']) else row['MODIS_LST'], axis=1
)
grid_gdf['ECOSTRESS_LST'].fillna(grid_gdf['ECOSTRESS_LST'].mean(), inplace=True)
# Compute ECOSTRESS anomalies (deviation from mean) (no changes here)
ecostress_mean = grid_gdf['ECOSTRESS_LST'].mean()
grid_gdf['ECOSTRESS_Anomaly'] = grid_gdf['ECOSTRESS_LST'] - ecostress_mean
# Normalize anomalies to range [-1, 1] (no changes here)
ecostress_anomaly_min = grid_gdf['ECOSTRESS_Anomaly'].min()
ecostress_anomaly_max = grid_gdf['ECOSTRESS_Anomaly'].max()
grid_gdf['ECOSTRESS_Anomaly_Normalized'] = (
(grid_gdf['ECOSTRESS_Anomaly'] - ecostress_anomaly_min) / (ecostress_anomaly_max - ecostress_anomaly_min) * 2 - 1
)
# **Invert the weighting function to reduce impact at night**
# Compute day_weight: maximum at noon (hour=12), minimal at midnight (hour=0)
day_weight = 0.5 * (math.cos(((hour % 24) / 24) * 2 * math.pi) + 1) # Ranges from 0 at midnight to 0.5 at noon
# **Apply anomalies with the day_weight**
amplification_factor = 1.0 # Adjust as needed
# Before applying the adjustment, ensure ECOSTRESS data is valid
valid_ecostress_mask = ~grid_gdf['ECOSTRESS_Anomaly_Normalized'].isnull()
# Apply adjustments only where ECOSTRESS data is valid
adjustment = np.zeros_like(grid_gdf['Temperature'])
adjustment[valid_ecostress_mask] = grid_gdf.loc[valid_ecostress_mask, 'ECOSTRESS_Anomaly_Normalized'] * amplification_factor * day_weight
# Prevent ECOSTRESS adjustments on water bodies (no changes here)
adjustment[grid_gdf['Water_Body'] == 1] = 0
# Limit maximum adjustment to avoid over-adjusting (no changes here)
max_adjustment = 5.0 # degrees Celsius
adjustment = adjustment.clip(-max_adjustment, max_adjustment)
# Apply adjustments to the interpolated temperatures (no changes here)
grid_gdf['Temperature'] += adjustment
# Apply the variable cooling effect to water bodies based on time of day
cooling_effect = compute_water_body_cooling_effect(hour)
# Apply the cooling effect to grid cells identified as water bodies
grid_gdf.loc[grid_gdf['Water_Body'] == 1, 'Temperature'] += cooling_effect
pbar.update(20) # Update the progress bar to complete
# Create 2D arrays of temperatures
grid_temperature_with_ecostress = np.full((nrows, ncols), np.nan)
grid_temperature_with_ecostress[grid_gdf['row_idx'], grid_gdf['col_idx']] = grid_gdf['Temperature'].values
# Mask the grid_temperature with the Masovian boundary
masovian_shape = [masovian_boundary.geometry.unary_union]
mask = rasterize(
masovian_shape,
out_shape=(nrows, ncols),
transform=transform,
fill=0,
all_touched=True,
default_value=1,
dtype='uint8'
)
temperature_with_ecostress = grid_temperature_with_ecostress
temperature_with_ecostress_masked = np.ma.masked_where(mask == 0, temperature_with_ecostress)
# Also create grid_variance array (we'll skip smoothing variance for simplicity)
grid_variance = np.full((nrows, ncols), np.nan)
grid_variance[grid_gdf['row_idx'], grid_gdf['col_idx']] = grid_gdf['Kriging_Variance']
grid_variance = np.ma.array(grid_variance, mask=mask == 0)
# Compute Standard Deviation from Variance
grid_std_dev = np.sqrt(grid_variance)
grid_std_dev = np.ma.array(grid_std_dev, mask=mask == 0)
# Extract temperatures over water bodies
water_temperatures = grid_gdf.loc[grid_gdf['Water_Body'] == 1, 'Temperature']
land_temperatures = grid_gdf.loc[grid_gdf['Water_Body'] == 0, 'Temperature']
# Compare average temperatures
avg_water_temp = water_temperatures.mean()
avg_land_temp = land_temperatures.mean()
print(f"Average Water Temperature: {avg_water_temp:.2f}°C")
print(f"Average Land Temperature: {avg_land_temp:.2f}°C")
print(f"Temperature Difference (Land - Water): {(avg_land_temp - avg_water_temp):.2f}°C")
# Read the custom color scale from the CSV file
color_scale_df = pd.read_csv('input/color_scale.csv')
color_scale_df = color_scale_df.sort_values('value')
values = color_scale_df['value'].values
hex_colors = color_scale_df['color'].values
# Ensure colors start with '#'
hex_colors = [color if color.startswith('#') else f"#{color}" for color in hex_colors]
# Create a custom colormap
# Normalize the values to 0..1
vmin = values.min()
vmax = values.max()
normalized_values = (values - vmin) / (vmax - vmin)
# Create a list of tuples (position, color)
color_tuples = list(zip(normalized_values, hex_colors))
# Create a LinearSegmentedColormap
cmap = mcolors.LinearSegmentedColormap.from_list('custom_cmap', color_tuples)
# Set the normalization
norm = mcolors.Normalize(vmin=vmin, vmax=vmax)
with rasterio.open('input/masovian_dem.tif') as dem_src:
# Reproject Masovian boundary to DEM CRS if necessary
if masovian_boundary.crs != dem_src.crs:
masovian_boundary_dem_crs = masovian_boundary.to_crs(dem_src.crs)
else:
masovian_boundary_dem_crs = masovian_boundary
# Clip the DEM to the Masovian boundary
dem_plot_data, dem_plot_transform = rasterio.mask.mask(
dem_src, masovian_boundary_dem_crs.geometry, crop=True, filled=True, nodata=np.nan
)
# Read the first band (assuming single-band DEM)
dem_plot_data = dem_plot_data[0] # Since mask returns data as (bands, rows, cols)
# Handle NaNs in the DEM data
dem_plot_data = np.nan_to_num(dem_plot_data, nan=np.nanmin(dem_plot_data))
# Calculate the extent of the clipped DEM for plotting
dem_left, dem_top = dem_plot_transform * (0, 0)
dem_right, dem_bottom = dem_plot_transform * (dem_plot_data.shape[1], dem_plot_data.shape[0])
dem_extent = [dem_left, dem_right, dem_bottom, dem_top]
# Create hillshade using DEM
hs = hillshade(dem_plot_data, azimuth=315, angle_altitude=45)
# Define extent for plotting
def get_extent(transform, array):
x_min = transform.c
y_max = transform.f
x_max = x_min + transform.a * array.shape[1]
y_min = y_max + transform.e * array.shape[0]
return [x_min, x_max, y_min, y_max]
extent = get_extent(transform, temperature_with_ecostress)
dem_extent = get_extent(dem_transform, dem_plot_data)
# Read water data and get CRS
water_data, water_transform, water_crs = read_and_clip_water_bodies(masovian_boundary)
# Create an empty array to hold the resampled water data
water_resampled = np.empty((nrows, ncols), dtype=water_data.dtype)
# Define bounding box coordinates
xmin, ymin, xmax, ymax = 20.188477, 51.017203, 22.061646, 51.821759
water_mask = np.where(water_resampled > 0, 1, 0)
# Compute the indices for the bounding box
from rasterio.transform import rowcol
# Convert coordinates to row and column indices in the temperature grid
row_ul, col_ul = rowcol(transform, xmin, ymax)
row_lr, col_lr = rowcol(transform, xmax, ymin)
# Ensure indices are within valid ranges
row_ul = max(0, min(nrows - 1, row_ul))
row_lr = max(0, min(nrows - 1, row_lr))
col_ul = max(0, min(ncols - 1, col_ul))
col_lr = max(0, min(ncols - 1, col_lr))
# Ensure row_ul <= row_lr and col_ul <= col_lr
if row_ul > row_lr:
row_ul, row_lr = row_lr, row_ul
if col_ul > col_lr:
col_ul, col_lr = col_lr, col_ul
# Extract the subset arrays
temperature_subset = temperature_with_ecostress[row_ul:row_lr+1, col_ul:col_lr+1]
hs_subset = hs[row_ul:row_lr+1, col_ul:col_lr+1]
water_mask_subset = water_mask[row_ul:row_lr+1, col_ul:col_lr+1]
mask_subset = mask[row_ul:row_lr+1, col_ul:col_lr+1]
# Apply the Masovian mask to the subsets
temperature_subset = np.ma.array(temperature_subset, mask=mask_subset == 0)
hs_subset = np.ma.array(hs_subset, mask=mask_subset == 0)
water_mask_subset = np.ma.array(water_mask_subset, mask=mask_subset == 0)
# Compute new transform for the subset
grid_spacing_x = transform.a # Positive grid spacing in x direction
grid_spacing_y = transform.e # Negative grid spacing in y direction
new_x_min = transform.c + col_ul * grid_spacing_x
new_y_max = transform.f + row_ul * grid_spacing_y # grid_spacing_y is negative
new_transform = from_origin(new_x_min, new_y_max, grid_spacing_x, -grid_spacing_y)
# Compute the new extent
extent_subset = get_extent(new_transform, temperature_subset)
# Filter stations within the bounding box
bbox_polygon = box(xmin, ymin, xmax, ymax)
stations_in_bbox = stations_gdf[stations_gdf.geometry.within(bbox_polygon)]
# Clip the Masovian boundary to the bounding box
masovian_boundary_clipped = masovian_boundary.clip(bbox_polygon)
# Plotting Temperature Map with Contours
# Calculate the aspect ratio of the bounding box
width = xmax - xmin
height = ymax - ymin
aspect_ratio = width / height
# Set the figure size based on the aspect ratio
desired_height_inches = 10 # You can adjust this value as desired
desired_width_inches = desired_height_inches * aspect_ratio
# Plotting Temperature Map with ECOSTRESS Adjustments
fig1, ax1 = plt.subplots(figsize=(15, 15))
# Plot the interpolated temperature grid with ECOSTRESS adjustments
img1 = ax1.imshow(temperature_with_ecostress_masked, extent=extent, origin='upper',
cmap=cmap, norm=norm, alpha=1, interpolation='nearest')
# Plot Masovian Voivodeship boundary with a light, dark stroke
masovian_boundary.boundary.plot(ax=ax1, edgecolor='#333333', linewidth=1.5)
# Plot stations
stations_gdf.plot(ax=ax1, color='black', marker='s', markersize=5)
# Remove axes for a minimalistic look
ax1.axis('off')
# Draw a light, dark stroke around the plot extent
from matplotlib.patches import Rectangle
rect = Rectangle(
(extent[0], extent[2]), # Lower-left corner (x0, y0)
extent[1] - extent[0], # Width
extent[3] - extent[2], # Height
linewidth=1.5,
edgecolor='#333333',
facecolor='none',
transform=ax1.transData
)
ax1.add_patch(rect)
# Introduce a subtle background gradient
from matplotlib.colors import LinearSegmentedColormap
background_cmap = LinearSegmentedColormap.from_list(
'background_gradient', ['#ffffff', '#f0f0f0'], N=256)
ax1.imshow(
np.linspace(0, 1, 256).reshape(1, -1),
cmap=background_cmap,
extent=(extent[0], extent[1], extent[2], extent[3]),
aspect='auto',
alpha=0.2,
zorder=-1 # Place it below other elements
)
# Adjust font properties for a modern look
plt.rcParams.update({
'font.size': 14, # Base font size
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
'text.color': '#333333'
})
# Enlarge and reposition the product name (Title)
fig1.text(
0.5, 0.94, # Adjusted y-position for better placement
"High-Resolution Mesoscale Temperature Analysis",
fontsize=28, # Increased font size
fontweight='bold',
ha='center',
va='top',
fontname='DejaVu Sans',
color='#333333'
)
# Move the model name/resolution text closer to the product name text
fig1.text(
0.5, 0.91, # Adjusted y-position to move it closer
"Model: HRMTA v1.1 (Preview) | Resolution: 250 m",
fontsize=18, # Increased font size
ha='center',
va='top',
fontname='DejaVu Sans',
color='#666666'
)
# Adjust colorbar position and style
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size="3%", pad=0.1)
cbar1 = fig1.colorbar(img1, cax=cax)
ticks = np.arange(np.floor(vmin / 5) * 5, np.ceil(vmax / 5) * 5 + 1, 5)
cbar1.set_ticks(ticks)
cbar1.set_ticklabels(ticks.astype(int))
cbar1.ax.tick_params(labelsize=14)
# Enhance colorbar aesthetics
cbar1.outline.set_visible(False)
cbar1.ax.yaxis.set_tick_params(width=0.5)
cbar1.ax.tick_params(labelsize=14, colors='#333333')
# Move the logo to the bottom right corner, directly below the colorbar
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
# Read the logo image
logo_path = 'input/logo.png'
logo_img = mpimg.imread(logo_path)
# Adjust the size of the logo
logo_zoom = 0.25
imagebox = OffsetImage(logo_img, zoom=logo_zoom)
# Get the position of the colorbar axes
cbar_bbox = cax.get_position()
cbar_x0 = cbar_bbox.x0 # Left
cbar_x1 = cbar_bbox.x1 # Right
# Calculate the x position for the logo (centered below the colorbar)
logo_x = (cbar_x0 + cbar_x1) / 2
# Set the y position as low as possible, but ensure the logo is fully visible
logo_y = 0.02 # Adjust this value if necessary
ab = AnnotationBbox(
imagebox,
xy=(logo_x, logo_y),
xycoords='figure fraction',
frameon=False,
box_alignment=(0.5, 0), # Centered horizontally, aligned at bottom
)
fig1.add_artist(ab)
# Adjust the bottom margin to ensure the logo is not cut off
plt.subplots_adjust(left=0.05, right=0.95, top=0.88, bottom=0.05)
# Ensure the temperature grid and water mask are aligned
if temperature_with_ecostress.shape != water_mask.shape:
raise ValueError("Temperature grid and water mask dimensions do not match.")
# Create a masked array for land temperatures by excluding water bodies
temperature_land = temperature_with_ecostress.copy()
# If temperature_with_ecostress is not already a masked array, convert it
if not isinstance(temperature_land, np.ma.MaskedArray):
temperature_land = np.ma.array(temperature_land)
# Update the mask to include water bodies
temperature_land.mask = temperature_land.mask | (water_mask == 1)
# Calculate minimum temperature over land only
min_temp = temperature_land.min()
max_temp = temperature_land.max()
# Get the indices of the min and max temperatures
# For min_temp, use the land-only masked array
min_indices_flat = np.ma.argmin(temperature_land)
max_indices_flat = np.ma.argmax(temperature_land)
min_indices = np.unravel_index(min_indices_flat, temperature_land.shape)
max_indices = np.unravel_index(max_indices_flat, temperature_land.shape)
# Convert grid indices to geographic coordinates using the new_transform
min_lon_full, min_lat_full = rasterio.transform.xy(transform, min_indices[0], min_indices[1])
max_lon_full, max_lat_full = rasterio.transform.xy(transform, max_indices[0], max_indices[1])
# Plot the temperature values on the map (without markers)
# Use white text with a thick black stroke for better visibility
text_kwargs = dict(
fontsize=18, # Increased font size for clarity
fontname='Arial',
ha='center',
va='center',
color='white',
transform=ax1.transData,
path_effects=[patheffects.withStroke(linewidth=3, foreground='black')]
)
# Format temperature values with one decimal point and add text labels
ax1.text(min_lon_full, min_lat_full, f"{min_temp:.1f}", **text_kwargs)
ax1.text(max_lon_full, max_lat_full, f"{max_temp:.1f}", **text_kwargs)
# Save and show the plot
plt.savefig('output/temperature_analysis_modern.png', dpi=300)
plt.show()
print("Updated temperature analysis plot created successfully.")
# Calculate the aspect ratio of the bounding box
width = xmax - xmin
height = ymax - ymin
aspect_ratio = width / height
# Set the maximum desired width
max_width_inches = 15 # Adjust this value as desired
# Calculate the figure height based on the aspect ratio and maximum width
desired_width_inches = min(max_width_inches, aspect_ratio * desired_height_inches)
desired_height_inches = desired_width_inches / aspect_ratio
# Ensure the height doesn't exceed a certain value
desired_height_inches = min(desired_height_inches, 10) # Adjust as needed
fig2, ax2 = plt.subplots(figsize=(desired_width_inches, desired_height_inches))
# Proceed with previous plotting code, using adjusted fig2 and ax2
# Use the subset data and extent with applied mask
img2 = ax2.imshow(temperature_subset, extent=extent_subset, origin='upper',
cmap=cmap, norm=norm, alpha=1, interpolation='nearest')
# Plot Masovian boundary
masovian_boundary_clipped.boundary.plot(ax=ax2, edgecolor='#333333', linewidth=1.5)
# Plot stations within the bounding box
stations_in_bbox.plot(ax=ax2, color='black', marker='s', markersize=5)
# Remove axes for a minimalistic look
ax2.axis('off')
# Introduce a subtle background gradient using the subset extent
ax2.imshow(
np.linspace(0, 1, 256).reshape(1, -1),
cmap=background_cmap,
extent=extent_subset,
aspect='auto',
alpha=0.2,
zorder=-1 # Place it below other elements
)
# Adjust font properties for a modern look
plt.rcParams.update({
'font.size': 14,
'font.family': 'sans-serif',
'font.sans-serif': ['Arial', 'Helvetica', 'DejaVu Sans'],
'text.color': '#333333'
})
# Enlarge and reposition the product name (Title)
fig2.text(
0.5, 0.995, # Moved up towards the top edge
"High-Resolution Mesoscale Temperature Analysis",
fontsize=12,
fontweight='bold',
ha='center',
va='top',
fontname='DejaVu Sans',
color='#333333'
)
# Move the model name/resolution text closer to the product name text
fig2.text(
0.5, 0.970, # Moved up slightly below the title
"Model: HRMTA v1.1 (Preview) | Resolution: 250 m",
fontsize=9,
ha='center',
va='top',
fontname='DejaVu Sans',
color='#666666'
)
# Add data source attribution at the bottom left corner
fig2.text(
0.01, 0.02,
"Data source: IMGW-PIB (processed)",
fontsize=12,
ha='left',
va='bottom',
fontname='DejaVu Sans',
color='#333333'
)
# Adjust colorbar position and style
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax2)
cax2 = divider.append_axes("right", size="3%", pad=0.1)
cbar2 = fig2.colorbar(img2, cax=cax2)
cbar2.set_ticks(ticks)
cbar2.set_ticklabels(ticks.astype(int))
# Import FontProperties and load the font
from matplotlib.font_manager import FontProperties
# Replace 'input/RobotoCondensed-Regular.ttf' with the actual path to your font file
roboto_font_path = 'input/RobotoCondensed-Regular.ttf'
roboto_condensed = FontProperties(fname=roboto_font_path)
# Apply font properties to the colorbar tick labels
for label in cbar2.ax.yaxis.get_ticklabels():
label.set_fontproperties(roboto_condensed)
cbar2.ax.tick_params(labelsize=14)
# Enhance colorbar aesthetics
cbar2.outline.set_visible(False)
cbar2.ax.yaxis.set_tick_params(width=0.5)
cbar2.ax.tick_params(labelsize=14, colors='#333333')
# Move the logo to the bottom right corner, directly below the colorbar
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
# Read the logo image again for the second plot
logo_img2 = mpimg.imread(logo_path)
# Adjust the size of the logo
imagebox2 = OffsetImage(logo_img2, zoom=logo_zoom)
# Get the position of the colorbar axes
cbar_bbox2 = cax2.get_position()
logo_x2 = (cbar_bbox2.x0 + cbar_bbox2.x1) / 2
logo_y2 = 0.02 # Adjust this value if necessary
ab2 = AnnotationBbox(
imagebox2,
xy=(logo_x2, logo_y2),
xycoords='figure fraction',
frameon=False,
box_alignment=(0.5, 0),
)
fig2.add_artist(ab2)
# Adjust the bottom margin to ensure the logo and data attribution text are not cut off
plt.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.06)
# Ensure the temperature grid and water mask are aligned
if temperature_with_ecostress.shape != water_mask.shape:
raise ValueError("Temperature grid and water mask dimensions do not match.")
# Using the temperature_subset array which is already clipped to the Masovian boundary
min_temp_subset = temperature_subset.min()
max_temp_subset = temperature_subset.max()
# (Optional) Print or store these values for future usage
print(f"Subset Minimum Temperature: {min_temp_subset:.2f}°C")
print(f"Subset Maximum Temperature: {max_temp_subset:.2f}°C")
# Add contours to the plot using the subset data
# Corrected variable names to use 'min_temp_subset' and 'max_temp_subset'
min_temp_c = np.floor(min_temp_subset)
max_temp_c = np.ceil(max_temp_subset)
# Handle cases where min_temp_c or max_temp_c might be NaN
if np.isnan(min_temp_c) or np.isnan(max_temp_c):
print("Warning: Temperature data is invalid or missing.")
contour_levels = []
else:
contour_levels = np.arange(min_temp_c, max_temp_c + 1, 1)
# Proceed only if contour_levels is not empty
if len(contour_levels) > 0:
contours = ax2.contour(
temperature_subset, levels=contour_levels, colors='black', linewidths=0.5,
extent=extent_subset, origin='upper'
)
contour_labels = ax2.clabel(
contours, inline=False, fontsize=8, fmt='%d', colors='white',
inline_spacing=4, manual=False
)
for txt in contour_labels:
txt.set_path_effects([
patheffects.Stroke(linewidth=3, foreground='black'),
patheffects.Normal()
])
else:
print("Contours cannot be plotted due to invalid temperature data.")
# Now add the min/max temperature labels after the contours and contour labels
text_kwargs = dict(
fontsize=18,
fontname='Arial',
ha='center',
va='center',
color='white',
transform=ax2.transData,
path_effects=[patheffects.withStroke(linewidth=3, foreground='black')]
)
# Reverse geocode min and max temperature locations to find nearest village
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="geoapiExercises")
try:
min_location = geolocator.reverse((min_lat_full, min_lon_full), language='en')
min_address = min_location.raw.get('address', {})
min_village = min_address.get('village',
min_address.get('town',
min_address.get('city', 'Unknown Location')))
except Exception as e:
print(f"Error reverse geocoding min location: {e}")
min_village = 'Unknown Location'
try:
max_location = geolocator.reverse((max_lat_full, max_lon_full), language='en')
max_address = max_location.raw.get('address', {})
max_village = max_address.get('village',
max_address.get('town',
max_address.get('city', 'Unknown Location')))
except Exception as e:
print(f"Error reverse geocoding max location: {e}")
max_village = 'Unknown Location'
# Create label texts
min_label_text = f"MIN\n {min_temp_subset:.1f}°C: {min_village}"
max_label_text = f"MAX\n {max_temp_subset:.1f}°C: {max_village}"
# Define font properties
from matplotlib.font_manager import FontProperties
roboto_font_path = 'input/RobotoCondensed-Regular.ttf'
roboto_condensed = FontProperties(fname=roboto_font_path)
# Add text labels to the figure
fig1.text(0.01, 0.95, min_label_text, ha='left', va='top', fontsize=14, fontproperties=roboto_condensed)
fig1.text(0.99, 0.95, max_label_text, ha='right', va='top', fontsize=14, fontproperties=roboto_condensed)
# Save and show the plot
plt.savefig('output/temperature_analysis_with_contours2.png', dpi=300)
plt.show()
print("Temperature analysis plot with contours created successfully.")
Save the trained model for future use
joblib.dump(best_pipeline, 'output/best_stacking_pipeline.joblib')
print("\nTrained Stacking model saved successfully.")
if dem_data is not None and dem_transform is not None:
elevations = []
for point in geometry:
x, y = point.x, point.y
try:
row, col = rowcol(dem_transform, x, y)
row = int(row)
col = int(col)
elevation = dem_data[row, col]
elevations.append(elevation)
except (IndexError, ValueError):
elevations.append(np.nan)
return elevations
else:
raise ValueError("Provide dem_data and dem_transform.")
def get_interpolated_temperature_at_two_points(lat1, lon1, lat2, lon2, temperature_grid, transform):
"""
Given two latitude and longitude pairs, return the interpolated temperature values at those points.
Parameters:
lat1, lon1: Latitude and longitude of the first point.
lat2, lon2: Latitude and longitude of the second point.
temperature_grid: The interpolated temperature grid (2D numpy array).
transform: Affine transform for the grid.
Returns:
A tuple containing interpolated temperature values at the two points,
or None for a point if it's outside the grid or has invalid data.
"""
import numpy as np
from rasterio.transform import rowcol
temps = []
for lat, lon in [(lat1, lon1), (lat2, lon2)]:
try:
# Convert geographic coordinates to raster indices
row, col = rowcol(transform, lon, lat) # Note: rasterio uses (x, y), so (lon, lat)
row = int(row)
col = int(col)
# Retrieve the value from the temperature grid
value = temperature_grid[row, col]
# Check if the value is valid
if np.ma.is_masked(value) or np.isnan(value):
# Value is masked or NaN, meaning outside the interpolated area
temps.append(None)
else:
temps.append(value.item())
except (IndexError, ValueError):
# Point is outside the grid
temps.append(None)
return tuple(temps)
def get_raster_value_at_points(geometry, raster_data=None, raster_transform=None):
from rasterio.transform import rowcol
if raster_data is not None and raster_transform is not None:
values = []
for point in geometry:
x, y = point.x, point.y
try:
row, col = rowcol(raster_transform, x, y)
row = int(row)
col = int(col)
if (0 <= row < raster_data.shape[0]) and (0 <= col < raster_data.shape[1]):
value = raster_data[row, col]
# Check for NaN in raster data
if np.isnan(value):
values.append(np.nan)
else:
values.append(value)
else:
values.append(np.nan)
except (IndexError, ValueError):
values.append(np.nan)
return values
else:
raise ValueError("Provide raster_data and raster_transform.")
def get_raster_value_at_point(x, y, raster_data=None, raster_transform=None):
from rasterio.transform import rowcol
if raster_data is not None and raster_transform is not None:
try:
row, col = rowcol(raster_transform, x, y)
row = int(row)
col = int(col)
if (0 <= row < raster_data.shape[0]) and (0 <= col < raster_data.shape[1]):
value = raster_data[row, col]
if np.isnan(value):
return np.nan
else:
return value
else:
return np.nan
except (IndexError, ValueError):
return np.nan
else:
raise ValueError("Provide raster_data and raster_transform.")
def get_water_body_at_points(geometry, water_data=None, water_transform=None):
from rasterio.transform import rowcol
if water_data is not None and water_transform is not None:
water_bodies = []
for point in geometry:
x, y = point.x, point.y
try:
row, col = rowcol(water_transform, x, y)
row = int(row)
col = int(col)
if (0 <= row < water_data.shape[0]) and (0 <= col < water_data.shape[1]):
value = water_data[row, col]
# Adjust the condition based on your raster's water encoding
# For binary raster where 1 = water, 0 = land
water_bodies.append(1 if value else 0)
else:
water_bodies.append(0)
except (IndexError, ValueError):
water_bodies.append(0)
return water_bodies
else:
raise ValueError("Provide water_data and water_transform.")
def read_and_clip_dem(masovian_boundary):
dem_path = 'input/masovian_dem.tif'
with rasterio.open(dem_path) as src:
dem_data = src.read(1, masked=True)
dem_transform = src.transform
return dem_data, dem_transform
def read_and_clip_water_bodies(masovian_boundary):
water_path = 'input/water_bodies.tif'
with rasterio.open(water_path) as src:
water_crs = src.crs # Get the CRS of the water raster
# Ensure the Masovian boundary is in the same CRS as the water raster
if masovian_boundary.crs != src.crs:
masovian_boundary = masovian_boundary.to_crs(src.crs)
# Perform the clipping
clipped_water, water_transform = rasterio.mask.mask(
src, masovian_boundary.geometry, crop=True, filled=True, nodata=0
)
# Read the first band (assuming single-band raster)
water_data = clipped_water[0]
# Handle NoData values by setting them to 0 (assuming 0 represents no water)
water_data = np.where(water_data == src.nodata, 0, water_data)
return water_data, water_transform, water_crs
def read_and_clip_ecostress(masovian_boundary):
ecostress_path = 'input/raw_ecostress.tif'
with rasterio.open(ecostress_path) as src:
def read_and_clip_population_density(masovian_boundary):
"""
Read and clip LandScan HD Population Density Data.
File: input/landscan_hd.tif
CRS: EPSG:4326
Value Range: 0 to 922 (raster format)
"""
pop_density_path = 'input/landscan_hd.tif'
with rasterio.open(pop_density_path) as src:
def read_and_clip_human_settlement(masovian_boundary):
"""
Read and clip GHS_BUILT_S Human Settlement Dataset.
File: input/human_settlement.tif
CRS: EPSG:4326
Value Range: 0 to 4819 (raster format)
Note: Set the NoData value to 0.
"""
human_settlement_path = 'input/human_settlement.tif'
with rasterio.open(human_settlement_path) as src:
if interpolated_temp1 is not None and interpolated_temp2 is not None:
print(f"\nRadom [{test_lat1}, {test_lon1}]: {interpolated_temp1:.2f}°C")
print(f"Mazowszany [{test_lat2}, {test_lon2}]: {interpolated_temp2:.2f}°C")
else:
print(f"\nOne or both coordinates are outside the interpolated grid or have no data.")
Objective: Analyze my current machine learning model and suggest enhancements to significantly boost its accuracy for operational use, specifically for Twitter posts.
Current Model Overview
Model Type: Stacking Regressor
Fitting Details: 5 folds for each of 256 candidates, totaling 1280 fits.
Best Parameters Found:
Gradient Boosting (GB):
Learning Rate: 0.01
Max Depth: 5
N Estimators: 100
Random Forest (RF):
Max Depth: 10
N Estimators: 200
XGBoost (XGB):
Learning Rate: 0.05
Max Depth: 6
N Estimators: 200
Model Performance Metrics
Mean Absolute Error (MAE): 0.944 ± 0.052
Mean Squared Error (MSE): 1.622 ± 0.394
Root Mean Squared Error (RMSE): 1.265 ± 0.147
R² Score: -0.129 ± 0.121
Median Error: 0.754 ± 0.071
Explained Variance: 0.099 ± 0.088
Feature Importances from Base Estimators
Random Forest Feature Importances:
Feature Importance
X 0.277004
Y 0.156585
Population Density 0.142478
MODIS LST 0.110408
Built Up 0.104949
Distance to Water 0.085824
Elevation 0.079116
Other Features ...
Gradient Boosting Feature Importances:
Feature Importance
X 0.329181
Y 0.195815
Population Density ...
XGBoost Feature Importances:
Feature Importance
Population Density ...
X ...
Request for Analysis and Suggestions
Detailed Code Analysis:
Analyze the entire codebase and its functions.
Explain how the model works, focusing on every detail.
Suggestions for Improvement:
Recommend strategies to enhance model accuracy significantly.
Consider techniques such as feature engineering, hyperparameter tuning, or advanced algorithms.
Operational Use Case:
Provide insights on how to adapt the model for everyday operational usage, particularly for analyzing Twitter posts.
Detailed Code Analysis
Your codebase comprises numerous functions tailored for geospatial data processing, temperature data interpolation, and machine learning model training and evaluation. Below is a comprehensive breakdown of the code, its functionalities, and how different components interact to achieve the final objective.
1. Imports and Environment Setup
import geopandas as gpd
import matplotlib.pyplot as plt
...
import joblib # For model saving/loading
os.environ['PROJ_LIB'] = r'C:\Users\Lenovo\Documents\conda\envs\temp_env\Library\share\proj'
warnings.filterwarnings("ignore")
Purpose: Cleans temperature strings by removing directional arrows and whitespace, then converts them to float.
Functionality:
Removes characters like arrows ('↓', '↑') and spaces using regex.
Attempts to convert the cleaned string to a float.
Returns None if conversion fails (e.g., malformed data).
remove_nearby_duplicates
def remove_nearby_duplicates(trax_coords, trax_temperatures, netatmo_coords, netatmo_temperatures, distance_threshold=0.01):
trax_points = np.array([(lon, lat) for station, (lat, lon) in trax_coords.items()])
netatmo_points = np.array([(lon, lat) for lat, lon in netatmo_coords])
trax_tree = cKDTree(trax_points)
netatmo_filtered_coords = []
netatmo_filtered_temperatures = []
for netatmo_point, netatmo_temp in zip(netatmo_points, netatmo_temperatures):
distance, index = trax_tree.query(netatmo_point)
if distance > distance_threshold:
netatmo_filtered_coords.append(tuple(netatmo_point))
netatmo_filtered_temperatures.append(netatmo_temp)
return netatmo_filtered_coords, netatmo_filtered_temperatures
Purpose: Removes Netatmo stations that are too close to Traxelektronik stations to eliminate duplicate or redundant data points.
Functionality:
Constructs KD-Trees for efficient spatial proximity queries.
Iterates over Netatmo points to check their distance from the nearest Traxelektronik point.
Filters out Netatmo points within the distance_threshold.
6. Temperature Interpolation and Plotting Functions
hillshade
def hillshade(array, azimuth=315, angle_altitude=45):
# Convert angles to radians
azimuth_rad = np.radians(azimuth)
altitude_rad = np.radians(angle_altitude)
# Calculate gradients in x and y directions
x, y = np.gradient(array)
# Calculate the slope and aspect
slope = np.pi/2.0 - np.arctan(np.sqrt(x*x + y*y))
aspect = np.arctan2(-x, y)
# Calculate shaded relief
shaded = np.sin(altitude_rad) * np.sin(slope) + np.cos(altitude_rad) * np.cos(slope) * np.cos(azimuth_rad - aspect)
# Normalize the shaded relief
shaded = (shaded + 1) / 2
shaded = (shaded * 255).astype(np.uint8)
return shaded
Purpose: Generates a hillshade (shaded relief) from a digital elevation model (DEM) array.
Functionality:
Calculates gradients to determine slope and aspect.
Computes shaded relief based on the specified azimuth and altitude angles.
Normalizes the shaded relief to an 8-bit grayscale image.
read_and_process_modis_data
def read_and_process_modis_data(modis_day_folder, modis_night_folder):
# Read and stack MODIS day data
modis_day_files = sorted(glob.glob(os.path.join(modis_day_folder, '*.tif')))
modis_day_arrays = []
modis_day_transform = None
for modis_file in modis_day_files:
with rasterio.open(modis_file) as src:
data = src.read(1)
fill_value = src.nodata
if fill_value is None:
data = np.where((data == -9999) | (data <= -1e20), np.nan, data)
else:
data = np.where(data == fill_value, np.nan, data)
modis_day_arrays.append(data)
if modis_day_transform is None:
modis_day_transform = src.transform
if modis_day_arrays:
modis_day_stack = np.stack(modis_day_arrays)
modis_day_data = np.nanmean(modis_day_stack, axis=0)
else:
modis_day_data = None
# Read and stack MODIS night data
modis_night_files = sorted(glob.glob(os.path.join(modis_night_folder, '*.tif')))
modis_night_arrays = []
modis_night_transform = None
for modis_file in modis_night_files:
with rasterio.open(modis_file) as src:
data = src.read(1)
fill_value = src.nodata
if fill_value is None:
data = np.where((data == -9999) | (data <= -1e20), np.nan, data)
else:
data = np.where(data == fill_value, np.nan, data)
modis_night_arrays.append(data)
if modis_night_transform is None:
modis_night_transform = src.transform
if modis_night_arrays:
modis_night_stack = np.stack(modis_night_arrays)
modis_night_data = np.nanmean(modis_night_stack, axis=0)
else:
modis_night_data = None
return (modis_day_data, modis_day_transform), (modis_night_data, modis_night_transform)
Purpose: Reads, processes, and averages MODIS day and night temperature data.
Functionality:
Reads all .tif files in the specified day and night folders.
Handles nodata values by replacing them with np.nan.
Stacks multiple raster arrays and computes the mean across them to create a single composite image for day and night.
Trains a stacking regression model to predict temperatures.
Interpolates temperature data across the Masovian boundary.
Generates visualization plots of the temperature distribution.
Functionality:
Data Integration:
Merges data from Traxelektronik, Netatmo, and IMGW sources.
Geocodes station locations and filters based on the Masovian boundary.
Extracts and processes various geospatial features (elevation, tree cover, water bodies, population density, land cover, etc.).
Feature Engineering:
Calculates distance to water bodies using distance transforms.
One-hot encodes land cover categories.
Incorporates MODIS Land Surface Temperature (LST) data.
Model Training:
Prepares feature matrix X and target variable y (temperature).
Handles missing and infinite values.
Utilizes a StackingRegressor with RandomForestRegressor, GradientBoostingRegressor, and XGBRegressor as base estimators, and RidgeCV as the meta-model.
Employs GridSearchCV for hyperparameter tuning with a predefined parameter grid.
Weights samples based on data source to prioritize certain stations.
Model Evaluation:
Evaluates the model using cross-validation with metrics like MAE, MSE, RMSE, R², etc.
Extracts feature importances from base estimators.
Temperature Interpolation:
Applies Universal Kriging to adjust residuals and refine temperature predictions.
Incorporates additional adjustments like topographic cooling and ECOSTRESS data.
Visualization:
Generates high-resolution temperature maps with hillshade overlays.
Plots station locations and temperature contours.
Saves the generated plots as high-quality PNG images.
Outcome:
Returns the interpolated temperature grid () and the associated affine transform () for georeferencing.
7. Helper Functions
get_elevation_at_points
def get_elevation_at_points(geometry, dem_data=None, dem_transform=None):
from rasterio.transform import rowcol
if dem_data is not None and dem_transform is not None:
elevations = []
for point in geometry:
x, y = point.x, point.y
try:
row, col = rowcol(dem_transform, x, y)
row = int(row)
col = int(col)
elevation = dem_data[row, col]
elevations.append(elevation)
except (IndexError, ValueError):
elevations.append(np.nan)
return elevations
else:
raise ValueError("Provide dem_data and dem_transform.")
Purpose: Retrieves elevation values from the DEM at specified geographic points.
Functionality:
Converts geographic coordinates to raster indices.
Extracts elevation values from the DEM array.
Handles out-of-bounds points by assigning np.nan.
get_interpolated_temperature_at_two_points
def get_interpolated_temperature_at_two_points(lat1, lon1, lat2, lon2, temperature_grid, transform):
"""
Given two latitude and longitude pairs, return the interpolated temperature values at those points.
...
"""
import numpy as np
from rasterio.transform import rowcol
temps = []
for lat, lon in [(lat1, lon1), (lat2, lon2)]:
try:
row, col = rowcol(transform, lon, lat)
row = int(row)
col = int(col)
value = temperature_grid[row, col]
if np.ma.is_masked(value) or np.isnan(value):
temps.append(None)
else:
temps.append(value.item())
except (IndexError, ValueError):
temps.append(None)
return tuple(temps)
Purpose: Retrieves interpolated temperature values at two specific geographic coordinates from the temperature grid.
Functionality:
Converts latitude and longitude to raster indices.
Extracts temperature values from the grid.
Handles out-of-bounds or masked values by returning None.
def get_raster_value_at_points(geometry, raster_data=None, raster_transform=None):
from rasterio.transform import rowcol
if raster_data is not None and raster_transform is not None:
values = []
for point in geometry:
x, y = point.x, point.y
try:
row, col = rowcol(raster_transform, x, y)
row = int(row)
col = int(col)
if (0 <= row < raster_data.shape[0]) and (0 <= col < raster_data.shape[1]):
value = raster_data[row, col]
if np.isnan(value):
values.append(np.nan)
else:
values.append(value)
else:
values.append(np.nan)
except (IndexError, ValueError):
values.append(np.nan)
return values
else:
raise ValueError("Provide raster_data and raster_transform.")
Purpose: Fetches raster values (e.g., elevation, tree cover) at multiple geographic points.
Functionality:
Converts point coordinates to raster indices.
Extracts raster values, handling out-of-bounds and NaN values.
get_water_body_at_points
def get_water_body_at_points(geometry, water_data=None, water_transform=None):
from rasterio.transform import rowcol
if water_data is not None and water_transform is not None:
water_bodies = []
for point in geometry:
x, y = point.x, point.y
try:
row, col = rowcol(water_transform, x, y)
row = int(row)
col = int(col)
if (0 <= row < water_data.shape[0]) and (0 <= col < water_data.shape[1]):
value = water_data[row, col]
water_bodies.append(1 if value else 0)
else:
water_bodies.append(0)
except (IndexError, ValueError):
water_bodies.append(0)
return water_bodies
else:
raise ValueError("Provide water_data and water_transform.")
Purpose: Determines whether specific geographic points lie within water bodies based on raster data.
Functionality:
Similar to get_raster_value_at_points but returns binary indicators (1 for water, 0 for land).
read_and_clip_* Functions
Purpose: Each of these functions (read_and_clip_dem, read_and_clip_forest, read_and_clip_water_bodies, read_and_clip_ecostress, read_and_clip_population_density, read_and_clip_human_settlement, read_and_clip_land_cover) reads specific raster datasets, clips them to the Masovian boundary, and handles nodata values appropriately.
Functionality:
Opens the raster file using rasterio.
Uses rasterio.mask.mask to clip the raster data to the Masovian boundary.
Processes nodata values by replacing them with np.nan or appropriate defaults.
Returns the clipped raster data and associated transform information.
resample_modis_data
def resample_modis_data(modis_data, modis_transform, dest_shape, dest_transform):
if modis_data is None:
return None
else:
dest_modis_data = np.zeros(dest_shape, dtype=modis_data.dtype)
reproject(
source=modis_data,
destination=dest_modis_data,
src_transform=modis_transform,
src_crs='EPSG:4326',
dst_transform=dest_transform,
dst_crs='EPSG:4326',
resampling=Resampling.nearest # Use nearest to maintain original resolution
)
dest_modis_data = np.where(dest_modis_data == 0, np.nan, dest_modis_data)
return dest_modis_data
Purpose: Resamples MODIS raster data to match a destination grid's shape and transform.
Functionality:
Uses rasterio.warp.reproject for resampling with nearest-neighbor interpolation.
Replaces zero values (assumed to represent no data) with np.nan.
Returns the resampled MODIS data.
8. Main Execution Block
if name == "main":
# Fetching Data Progress Bar
with tqdm(total=100, desc='Fetching Data', unit='%', ncols=80) as pbar:
# Fetch Traxelektronik data
trax_stations, trax_temperatures = fetch_traxelektronik_data()
pbar.update(20)
# Geocode Traxelektronik stations
geolocator = Nominatim(user_agent="geoapi")
trax_coords = {}
for station in tqdm(trax_stations, desc="Geocoding Traxelektronik Stations", unit="station"):
cleaned_station = clean_station_name(station)
coords, was_cleaned = get_coordinates(cleaned_station, geolocator)
if coords:
trax_coords[cleaned_station] = coords # Use cleaned station names as keys
pbar.update(30)
# Fetch Netatmo data
netatmo_stations, netatmo_temperatures, netatmo_coords = fetch_netatmo_data()
pbar.update(20)
# Fetch IMGW data
imgw_stations, imgw_temperatures, imgw_station_ids = fetch_imgw_data()
pbar.update(10)
# Geocode IMGW stations
imgw_coords = {}
for station in tqdm(imgw_stations, desc="Geocoding IMGW Stations", unit="station"):
coords, was_cleaned = get_coordinates(station, geolocator)
if coords:
imgw_coords[station] = coords
pbar.update(20)
# Paths to MODIS data folders
modis_day_folder = 'input/MODIS_day'
modis_night_folder = 'input/MODIS_night'
# Call the function with all required arguments
smoothed_temperature, transform = plot_stations_with_boundary_and_interpolation(
trax_stations, trax_temperatures, trax_coords,
netatmo_stations, netatmo_temperatures, netatmo_coords,
imgw_stations, imgw_temperatures, imgw_coords,
modis_day_folder, modis_night_folder
)
# Coordinates to test
test_lat1 = 51.40232
test_lon1 = 21.14761
test_lat2 = 51.30873
test_lon2 = 21.13436
# Call the modified function
interpolated_temp1, interpolated_temp2 = get_interpolated_temperature_at_two_points(
test_lat1, test_lon1, test_lat2, test_lon2, smoothed_temperature, transform
)
if interpolated_temp1 is not None and interpolated_temp2 is not None:
print(f"\nRadom [{test_lat1}, {test_lon1}]: {interpolated_temp1:.2f}°C")
print(f"Mazowszany [{test_lat2}, {test_lon2}]: {interpolated_temp2:.2f}°C")
else:
print(f"\nOne or both coordinates are outside the interpolated grid or have no data.")
Purpose: Orchestrates the data fetching, processing, model training, interpolation, and visualization.
Functionality:
Utilizes tqdm for progress tracking of data fetching and geocoding.
Fetches temperature data from Traxelektronik, Netatmo, and IMGW sources.
Geocodes the fetched station names to obtain geographic coordinates.
Processes MODIS data for both day and night.
Calls plot_stations_with_boundary_and_interpolation to train the model, interpolate temperatures, and generate plots.
Tests the interpolated temperature grid at two specific coordinates.
9. Model Training and Evaluation
Within plot_stations_with_boundary_and_interpolation, the following steps are crucial for model training and evaluation:
Feature Preparation:
Merges data from different sources into a unified GeoDataFrame (stations_gdf).
Extracts geospatial features such as elevation, tree cover, distance to water, population density, built-up areas, land cover, and MODIS LST.
One-hot encodes categorical land cover variables to convert them into numerical features.
Model Training:
Defines a StackingRegressor with RandomForestRegressor, GradientBoostingRegressor, and XGBRegressor as base estimators, and RidgeCV as the meta-model.
Specifies a hyperparameter grid for GridSearchCV to explore various configurations.
Trains the stacking regressor using 5-fold cross-validation and sample weights (prioritizing certain data sources).
Model Evaluation:
Evaluates the best model using cross-validation with metrics like MAE, MSE, RMSE, R², Median Absolute Error, and Explained Variance.
Extracts and prints feature importances from the base estimators.
Temperature Interpolation:
Applies Universal Kriging to refine residuals based on spatial patterns.
Incorporates topographic cooling and ECOSTRESS LST adjustments to the interpolated temperatures.
Visualization:
Generates high-resolution temperature maps with hillshade overlays and contour lines.
Saves plots as PNG images with enhanced aesthetics (titles, labels, logos).
10. Model Saving and Prediction
# Save the trained model for future use
joblib.dump(best_pipeline, 'output/best_stacking_pipeline.joblib')
print("\nTrained Stacking model saved successfully.")
Purpose: Saves the trained stacking regressor pipeline for future use without retraining.
Functionality:
Uses joblib.dump to serialize and save the best_pipeline object to disk.
Summary of Main Functional Components:
Data Fetching: Retrieves temperature data from multiple sources (Traxelektronik, Netatmo, IMGW).
Geocoding: Converts station names to geographic coordinates, ensuring they lie within the Masovian boundary.
Feature Extraction: Extracts various geospatial features from raster datasets.
Feature Engineering: Processes and augments features (e.g., one-hot encoding land cover).
Model Training: Trains a stacking regressor with hyperparameter tuning.
Model Evaluation: Assesses model performance using multiple metrics and feature importances.
Temperature Interpolation: Applies spatial interpolation techniques to estimate temperatures across the region.
Visualization: Creates detailed and aesthetically enhanced temperature maps.
Model Persistence: Saves the trained model for operational deployment.
Suggestions for Improvement
Your current model exhibits some concerning performance metrics, particularly the negative R² score, which indicates that the model is performing worse than a baseline model that predicts the mean target value. Below are detailed suggestions to enhance your model's accuracy and operational readiness.
1. Data Quality and Preprocessing Enhancements
a. Data Cleaning and Validation
Missing Values:
Ensure that there's a thorough handling of missing data. Even though you've replaced nodata values with np.nan, verify that there are no residual missing values post feature engineering.
Outlier Detection:
Identify and handle outliers in the temperature data and features. Outliers can skew the model performance significantly.
Consistency Across Data Sources:
Ensure that temperature measurements across different sources are consistent in terms of units and measurement times.
b. Feature Normalization and Scaling
Scaling Features:
Features like Elevation, Tree_Cover, Distance_to_Water, etc., might have different scales. Applying scaling techniques (e.g., StandardScaler, MinMaxScaler) can improve model convergence and performance.
Handling Categorical Variables:
While one-hot encoding is appropriate, consider using target encoding or embeddings if categorical variables have many levels or high cardinality.
2. Feature Engineering
a. Additional Relevant Features
Temporal Features:
Incorporate time-based features such as time of day, day of the week, and seasonal indicators. Temperature can vary significantly based on these temporal factors.
Spatial Features:
Calculate spatial statistics like the distance to nearest major city, average temperature in neighboring grid cells, or land use diversity around stations.
Interaction Terms:
Create interaction features between existing variables (e.g., Elevation * Distance_to_Water) to capture non-linear relationships.
b. Dimensionality Reduction
Principal Component Analysis (PCA):
Apply PCA to reduce multicollinearity among features and capture the most variance with fewer components.
Feature Selection:
Utilize feature selection techniques (e.g., Recursive Feature Elimination, LASSO) to identify and retain the most predictive features.
3. Model Architecture Enhancements
a. Algorithm Selection
Advanced Ensemble Methods:
Explore other ensemble methods like LightGBM or CatBoost, which often outperform traditional gradient boosting algorithms in terms of speed and accuracy.
Neural Networks:
Implement neural network architectures, especially if you have a large dataset. Deep learning models can capture complex non-linear relationships.
Gaussian Processes:
For geospatial interpolation, Gaussian Processes can provide probabilistic predictions with uncertainty estimates.
b. Hyperparameter Tuning
Expand Hyperparameter Grid:
Broaden the range of hyperparameters for GridSearchCV or switch to more efficient search methods like RandomizedSearchCV or Bayesian Optimization using libraries such as Optuna.
Cross-Validation Strategy:
Use Stratified K-Folds if your data has inherent stratifications or consider Grouped K-Folds to prevent data leakage from spatial overlaps.
c. Addressing Negative R²
Model Complexity:
The negative R² suggests overfitting or model misconfiguration. Simplify the model by reducing the number of estimators or tree depths.
Regularization:
Apply stronger regularization to prevent overfitting, especially in the meta-model (RidgeCV parameters).
Error Analysis:
Conduct a thorough error analysis to identify patterns in the residuals. Check if the model consistently underperforms in specific regions or under certain conditions.
4. Handling Geospatial Data More Effectively
a. Spatial Autocorrelation
Incorporate Spatial Autocorrelation Metrics:
Features like Moran's I or Geary's C can quantify spatial autocorrelation in your data, aiding in model feature enhancement.
Spatial Lag and Spatial Error Models:
Implement models that account for spatial dependencies directly, ensuring better handling of spatial autocorrelation.
b. Use of Geospatial Machine Learning Libraries
GeoML Libraries:
Utilize geospatial machine learning libraries like Geospark or PySAL to handle spatial data more effectively.
5. Operational Enhancements for Twitter Post Analysis
Assuming your operational use case involves analyzing Twitter posts in relation to temperature data (e.g., sentiment analysis influenced by weather conditions), here are tailored suggestions:
a. Data Integration
Merge Twitter Data with Temperature Data:
Align tweets geographically and temporally with your temperature grid to analyze correlations between weather conditions and tweet sentiments or topics.
b. Feature Expansion
Sentiment Scores:
Compute sentiment scores for tweets and use them as additional features or target variables.
Topic Modeling:
Perform topic modeling on tweets to derive thematic features that might correlate with temperature variations.
c. Real-Time Processing
Streaming Data Pipelines:
Implement real-time data ingestion and processing pipelines (e.g., using Kafka, Apache Spark Streaming) to handle live Twitter data alongside temperature data.
Model Deployment:
Deploy the model using scalable platforms like AWS SageMaker, Google AI Platform, or Azure ML to handle operational loads and real-time predictions.
d. Model Adaptation
Multi-Task Learning:
Develop models that can simultaneously predict temperature and analyze tweet sentiments, leveraging shared features for improved performance.
Ensemble Techniques for Operational Robustness:
Combine multiple models (e.g., separate models for temperature prediction and sentiment analysis) into a cohesive ensemble to enhance overall system reliability.
6. Technical Improvements and Best Practices
a. Code Optimization and Modularity
Modular Code Structure:
Refactor the codebase into modular scripts or classes, separating concerns like data fetching, preprocessing, feature engineering, modeling, and visualization.
Parallel Processing:
Utilize parallel processing for tasks like geocoding to speed up data preparation phases.
b. Reproducibility and Documentation
Version Control:
Use version control systems like Git to track changes and collaborate effectively.
Comprehensive Documentation:
Document functions, parameters, and workflows using docstrings and external documentation tools (e.g., Sphinx, MkDocs).
c. Logging and Monitoring
Implement Logging:
Use Python's logging module to log important events, errors, and warnings, aiding in debugging and monitoring.
Performance Monitoring:
Track model performance over time to identify drifts and ensure sustained accuracy.
d. Data Storage and Management
Efficient Data Storage:
Use efficient data storage formats (e.g., Parquet, HDF5) for large geospatial datasets to speed up data access and processing.
Data Versioning:
Implement data versioning to manage and track different versions of your datasets.
Detailed Explanation of the Current Model
Your model employs a Stacking Regressor approach, combining multiple base estimators to improve predictive performance. Below is an in-depth explanation of how the model operates within your pipeline.
1. Model Architecture
a. Base Estimators
Random Forest Regressor (rf):
Purpose: Handles non-linear relationships and interactions between features.
Parameters:
n_estimators=200: Number of trees in the forest.
max_depth=10: Maximum depth of each tree, controlling overfitting.
Gradient Boosting Regressor (gb):
Purpose: Sequentially builds trees to minimize errors from previous trees.
Parameters:
n_estimators=100: Number of boosting stages.
learning_rate=0.01: Shrinks the contribution of each tree.
max_depth=5: Limits the depth of each tree.
XGBoost Regressor (xgb):
Purpose: Optimized gradient boosting with additional regularization.
Parameters:
n_estimators=200: Number of trees.
learning_rate=0.05: Step size shrinkage.
max_depth=6: Maximum tree depth.
b. Meta-Estimator
RidgeCV:
Purpose: Performs linear regression with L2 regularization.
Function: Aggregates predictions from base estimators to minimize bias and variance.
MAE (Mean Absolute Error): Measures average magnitude of errors.
MSE (Mean Squared Error): Penalizes larger errors more than MAE.
RMSE (Root Mean Squared Error): Square root of MSE, in original units.
R² Score: Proportion of variance explained by the model.
Median Error: Median of absolute errors.
Explained Variance: Measures how much variance is captured by the model.
Observations from Current Metrics:
MAE: Low (0.944 ± 0.052), suggesting predictions are on average within 1°C of actual values.
MSE and RMSE: Indicate that while MAE is low, the squared errors are higher, contributing to a larger RMSE.
Negative R²: Implies that the model performs worse than a baseline that predicts the mean temperature, which is concerning.
4. Feature Importance Extraction
for (name, _), fitted_estimator in zip(
best_pipeline.named_steps['stack'].estimators,
best_pipeline.named_steps['stack'].estimators_):
if hasattr(fitted_estimator, 'feature_importances_'):
feature_importances[name] = fitted_estimator.feature_importances_
Purpose: Extracts feature importances from each base estimator to understand which features contribute most to predictions.
Findings:
Random Forest:
X and Y (geographic coordinates) are the top features.
Suggests spatial location is a dominant predictor.
Gradient Boosting and XGBoost:
Similar trends with spatial coordinates and population density being significant.
Implications:
Heavy reliance on spatial coordinates may indicate potential overfitting or lack of useful feature information beyond location.
Important to ensure that features are contributing meaningfully and not just reflecting spatial biases.
5. Temperature Interpolation and Residual Adjustment
Kriging:
Applies Universal Kriging to interpolate residuals, refining the spatial distribution of temperature estimates.
Additional Adjustments:
Incorporates topographic cooling effects and ECOSTRESS LST adjustments to enhance temperature estimates, especially in areas like water bodies.
6. Visualization
Temperature Maps:
Generates high-resolution maps showcasing interpolated temperatures with hillshade overlays.
Includes station locations and temperature contours for visual validation.
Aesthetic Enhancements:
Utilizes custom color scales, overlays, and logos to produce professional-grade visual outputs.
Recommendations for Enhancing Model Accuracy
Improving the performance of your machine learning model, especially in light of the negative R² score, requires a multifaceted approach focusing on data quality, feature engineering, model architecture, and evaluation strategies.
1. Addressing Negative R² Score
A negative R² indicates that the model performs worse than a simple mean predictor. This can be due to overfitting, insufficient model complexity, or inappropriate feature selection.
a. Re-evaluate Training and Validation Procedures
Train-Test Split:
Ensure that your cross-validation strategy correctly separates training and validation data without leakage. If data points are spatially correlated, consider spatial cross-validation techniques.
Stratification:
If your data is imbalanced (e.g., more hot than cold stations), stratify your splits to maintain representative distributions in each fold.
b. Simplify the Model
Reduce Model Complexity:
Lower the number of estimators or tree depths in base models to prevent overfitting.
Regularization:
Increase regularization parameters in the meta-model (RidgeCV) to penalize large coefficients.
c. Improve Feature Relevance
Remove or Transform Dominant Features:
High importance of spatial coordinates might overshadow other informative features. Consider transforming X and Y into more meaningful spatial features like distance to key landmarks, elevation bands, or clustering indicators.
Feature Interaction:
Create interaction terms that may capture non-linear dependencies, such as Elevation * Distance_to_Water.
d. Expand or Refine Features
Temporal Features:
Incorporate temporal variables if temperature varies over time (e.g., hour of the day, day of the week).
Environmental Features:
Include additional environmental factors like humidity, wind speed, or precipitation if available.
2. Enhancing Feature Engineering
a. Advanced Encoding Techniques
Target Encoding:
For categorical variables with high cardinality, target encoding can capture the impact of categories on the target variable more effectively.
Polynomial Features:
Generate polynomial and interaction features to allow models to capture non-linear relationships more effectively.
b. Dimensionality Reduction
Principal Component Analysis (PCA):
Reduce dimensionality while retaining variance, potentially enhancing model performance and reducing overfitting.
c. Spatial Feature Engineering
Clustering:
Implement clustering algorithms (e.g., K-Means) to identify spatial clusters and use cluster labels as features.
Spatial Lag Features:
Incorporate features representing the average temperature in neighboring grid cells.
3. Model Architecture Improvements
a. Experiment with Different Models
LightGBM or CatBoost:
These gradient boosting frameworks often provide better performance and faster training times compared to traditional boosting models.
Neural Networks:
Consider deep learning models like Convolutional Neural Networks (CNNs) for spatial data, which can capture complex patterns effectively.
b. Ensemble Techniques
Boosting Stacks:
Further stack boosting models or integrate different ensembles to capture diverse patterns.
Bagging:
Implement bagging techniques to reduce variance and enhance model stability.
c. Meta-Model Enhancements
Different Meta-Models:
Experiment with different meta-models like ElasticNet, Lasso, or even higher-capacity models like GradientBoostingRegressor for the stacking setup.
4. Advanced Hyperparameter Tuning
a. Utilize Bayesian Optimization
Libraries: Utilize Optuna or Hyperopt for more efficient hyperparameter searches compared to grid and random searches.
Bayesian Methods:
These methods can prioritize hyperparameter regions that show promise, reducing computational overhead and achieving better performance.
b. Nested Cross-Validation
Purpose: Prevent overfitting in hyperparameter tuning by separating model selection into nested cross-validation, ensuring unbiased performance estimates.
5. Incorporate Spatial Autocorrelation
Spatial Weight Matrices:
Build spatial weight matrices to account for spatial dependencies in regression models.
Geographically Weighted Regression (GWR):
Implement regression models that allow coefficients to vary spatially, capturing local variations in temperature relationships.
6. Operational Enhancements for Analyzing Twitter Posts
Assuming your operational use case involves integrating temperature data with Twitter post analysis (e.g., sentiment analysis influenced by weather conditions), consider the following strategies:
a. Feature Integration
Sentiment Scores:
Merge sentiment analysis scores from Twitter posts with corresponding temperature data to explore correlations.
Event Detection:
Identify weather-related events (e.g., heatwaves) in temperature data and analyze their impact on Twitter activity.
b. Real-Time Data Processing
Streaming Pipelines:
Implement real-time data ingestion and processing pipelines using tools like Apache Kafka or Apache Spark Streaming to handle live Twitter feeds alongside temperature measurements.
c. Multi-Modal Models
Combined Feature Models:
Develop models that simultaneously use textual data from tweets and numerical weather data to predict outcomes like public sentiment or engagement levels.
Deep Learning Approaches:
Utilize architectures that can process both text (e.g., using RNNs or Transformers) and numerical data, capturing complex interdependencies.
d. Deployment and Scalability
Model Serving:
Deploy models using scalable platforms such as AWS SageMaker, Google AI Platform, or Dockerized APIs to handle operational loads efficiently.
Monitoring and Updates:
Implement monitoring systems to track model performance in real-time and automate model retraining or updates as needed.
7. Robust Evaluation Techniques
a. Comprehensive Metrics
Expand Metrics:
In addition to the current metrics, include metrics like Median Absolute Percentage Error (MAPE) or Symmetric Mean Absolute Percentage Error (sMAPE) for a more nuanced evaluation.
b. Visualization of Residuals
Residual Plots:
Plot residuals against predicted values and feature variables to identify patterns indicating model shortcomings.
Spatial Residual Analysis:
Map residuals geographically to detect spatial biases or regions where the model consistently underperforms.
c. Cross-Validation Enhancements
Spatial Cross-Validation:
Use cross-validation techniques that respect spatial dependencies to prevent data leakage, such as Blocked Cross-Validation or Spatial K-Folds.
Conclusion
Your current machine learning pipeline is comprehensive, integrating extensive geospatial data preprocessing, feature engineering, and a sophisticated stacking regressor model. However, the negative R² score indicates critical issues that need addressing to make the model operationally viable.
By enhancing data quality, expanding and refining feature engineering, experimenting with different modeling techniques, and employing advanced hyperparameter tuning strategies, you can significantly improve your model's accuracy and robustness. Additionally, tailoring the model to your specific operational context, such as analyzing Twitter posts in relation to temperature data, will require careful integration of textual and numerical data, real-time processing capabilities, and scalable deployment solutions.
Implementing these recommendations will not only address the current performance shortcomings but also lay a robust foundation for future enhancements and operational success.