Define the Stacking Regressor with advanced models
stacking_regressor = StackingRegressor(
estimators=base_estimators,
final_estimator=meta_model,
passthrough=False,
n_jobs=4, # Limited for memory efficiency
cv=3 # Reduced folds for memory efficiency in final estimator
)
Create a pipeline with StandardScaler and Stacking Regressor
pipeline = Pipeline([
('scaler', StandardScaler()), # For linear meta-model (Ridge)
('stack', stacking_regressor)
])
Define BayesSearchCV for advanced hyperparameter optimization
bayes_search = BayesSearchCV(
estimator=pipeline,
search_spaces=param_spaces,
n_iter=40, # Number of iterations for the search
cv=group_kfold.split(X, y, groups=groups),
scoring='r2',
n_jobs=4, # Limit for stability and memory usage
verbose=1,
random_state=42,
pre_dispatch='2*n_jobs', # Memory-efficient dispatch
error_score='raise'
)
Fit BayesSearchCV with sample weights
fit_params = {'stack__sample_weight': sample_weights} if sample_weights is not None else {}
bayes_search.fit(X, y, **fit_params)
print("BayesSearchCV completed with Spatial GroupKFold and Feature Scaling.")
required_columns = ['Northness', 'Eastness', 'Hour']
missing_columns = [col for col in required_columns if col not in grid_gdf.columns]
if missing_columns:
raise KeyError(f"The following required columns are missing in grid_gdf: {missing_columns}")
else:
print("All required columns are present in grid_gdf.")
Include MODIS_LST in grid_gdf (Already included)
Prepare data for regression prediction
Include land cover dummy variables and new temporal/interactions
for col in land_cover_dummies_stations.columns:
if col not in grid_gdf.columns:
grid_gdf[col] = 0
Please effectively fix this error here and send updated part of the code:
Traceback (most recent call last):
File "c:\Users\Lenovo\Downloads\pythonStationsData\xgboost_interpolation_gaussian.py", line 2477, in
smoothed_temperature, transform = plot_stations_with_boundary_and_interpolation(
File "c:\Users\Lenovo\Downloads\pythonStationsData\xgboost_interpolation_gaussian.py", line 1362, in plot_stations_with_boundary_and_interpolation
x = grid_gdf.at[idx, 'X']
File "C:\Users\Lenovo\Documents\conda\envs\temp_env\lib\site-packages\pandas\core\indexing.py", line 2575, in getitem
return super().getitem(key)
File "C:\Users\Lenovo\Documents\conda\envs\temp_env\lib\site-packages\pandas\core\indexing.py", line 2527, in getitem
return self.obj._get_value(*key, takeable=self._takeable)
File "C:\Users\Lenovo\Documents\conda\envs\temp_env\lib\site-packages\pandas\core\frame.py", line 4221, in _get_value
row = self.index.get_loc(index)
File "C:\Users\Lenovo\Documents\conda\envs\temp_env\lib\site-packages\pandas\core\indexes\base.py", line 3812, in get_loc
raise KeyError(key) from err
KeyError: 1547
The KeyError: 1547 occurs because the index 1547 does not exist in your grid_gdf DataFrame. This typically happens when the DataFrame's index is not sequential (i.e., not starting from 0 and incrementing by 1 for each row). To fix this error, you can reset the index of grid_gdf to ensure it is sequential.
Here are two approaches to resolve the issue:
Reset the DataFrame Index:
Before entering the loop where you're accessing grid_gdf.at[idx, 'X'], reset the index of grid_gdf to ensure it's sequential. This can be done using the reset_index method with drop=True to discard the old index.
Use .iloc Instead of .at:
Alternatively, you can use the .iloc accessor, which accesses rows based on their integer position, ensuring that you don't rely on the DataFrame's index.
Below, I'll provide the updated code snippet incorporating both approaches. You can choose either method based on your preference.
Approach 1: Resetting the DataFrame Index
Add the reset_index method before the loop to ensure the index is sequential.
python
from tqdm import tqdm
import numpy as np
from scipy.ndimage import gaussian_filter
# ... [previous code remains unchanged] ...
# Apply confidence metrics
grid_gdf['Prediction_Confidence'] = 1 - (grid_gdf['GPR_Variance'] / grid_gdf['GPR_Variance'].max())
# 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
)
# **Fix for KeyError: Reset the DataFrame index**
grid_gdf.reset_index(drop=True, inplace=True)
# Running Model Progress Bar with updated grid_gdf index
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)
# Compute Aspect and Slope in Radians for grid_gdf
grid_gdf['Aspect_rad'] = np.radians(grid_gdf['Aspect'])
grid_gdf['Slope_rad'] = np.radians(grid_gdf['Slope'])
# Compute Northness and Eastness for grid_gdf
grid_gdf['Northness'] = np.cos(grid_gdf['Aspect_rad']) * np.sin(grid_gdf['Slope_rad'])
grid_gdf['Eastness'] = np.sin(grid_gdf['Aspect_rad']) * np.sin(grid_gdf['Slope_rad'])
# Assign Hour to grid_gdf
grid_gdf['Hour'] = hour
# Verify that required columns exist in grid_gdf
required_columns = ['Northness', 'Eastness', 'Hour']
missing_columns = [col for col in required_columns if col not in grid_gdf.columns]
if missing_columns:
raise KeyError(f"The following required columns are missing in grid_gdf: {missing_columns}")
else:
print("All required columns are present in grid_gdf.")
# Include MODIS_LST in grid_gdf (Already included)
# Prepare data for regression prediction
# Include land cover dummy variables and new temporal/interactions
for col in land_cover_dummies_stations.columns:
if col not in grid_gdf.columns:
grid_gdf[col] = 0
# Add Sinusoidal Encoding for Hour-of-Day
grid_gdf['sin_hour'] = np.sin(2 * np.pi * grid_gdf['Hour'] / 24)
grid_gdf['cos_hour'] = np.cos(2 * np.pi * grid_gdf['Hour'] / 24)
# Create Interaction Terms between Elevation and Temporal Features
grid_gdf['Elevation_sin_hour'] = grid_gdf['Elevation'] * grid_gdf['sin_hour']
grid_gdf['Elevation_cos_hour'] = grid_gdf['Elevation'] * grid_gdf['cos_hour']
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)
# ... [rest of your code remains unchanged] ...
Approach 2: Using .iloc Instead of .at
If you prefer not to reset the index of grid_gdf, you can modify the loop to use .iloc, which accesses rows based on their integer position.
python
Explanation of the Fix
Resetting the Index:
Why? When you reset the index of grid_gdf, you ensure that the DataFrame has a sequential index starting from 0. This allows you to safely use .at[idx, 'X'] without encountering a KeyError.
How? Using grid_gdf.reset_index(drop=True, inplace=True) modifies the DataFrame in place, dropping the old index and replacing it with a new sequential one.
Using .iloc Instead of .at:
Why? The .iloc accessor accesses rows based on their integer position rather than the DataFrame's index. This avoids errors related to non-sequential or missing indices.
How? Replace grid_gdf.at[idx, 'X'] with grid_gdf.iloc[idx]['X'] and similarly for other columns like 'Y'.
Additional Error Handling (Optional):
In Approach 2, within the loop, you can add a try-except block to handle any unexpected IndexError gracefully. This ensures that your program doesn't crash if an out-of-bounds index is encountered.
Choosing the Right Approach:
Approach 1 is straightforward and ensures that your DataFrame indices are sequential, making it safe to use .at[idx, 'column'].
Approach 2 is useful if you prefer to keep the original DataFrame indices intact for other operations but need to access rows based on their position.
Final Recommendations
Consistency: Ensure that throughout your code, you consistently access DataFrame rows either by their index or position. Mixing both can lead to confusion and potential errors.
Performance Considerations: Resetting the index can be more efficient if you have large DataFrames and are performing many row-wise operations based on position.
Error Handling: Always include error handling mechanisms when dealing with data access to make your code more robust and easier to debug.
Implementing one of the above approaches should resolve the KeyError you're encountering. Choose the method that best fits the structure and requirements of your overall codebase.
Not yet included in a published release.
from tqdm import tqdm
import numpy as np
from scipy.ndimage import gaussian_filter
# ... [previous code remains unchanged] ...
# 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
)
# Running Model Progress Bar with updated access method
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)
# Compute Aspect and Slope in Radians for grid_gdf
grid_gdf['Aspect_rad'] = np.radians(grid_gdf['Aspect'])
grid_gdf['Slope_rad'] = np.radians(grid_gdf['Slope'])
# Compute Northness and Eastness for grid_gdf
grid_gdf['Northness'] = np.cos(grid_gdf['Aspect_rad']) * np.sin(grid_gdf['Slope_rad'])
grid_gdf['Eastness'] = np.sin(grid_gdf['Aspect_rad']) * np.sin(grid_gdf['Slope_rad'])
# Assign Hour to grid_gdf
grid_gdf['Hour'] = hour
# Verify that required columns exist in grid_gdf
required_columns = ['Northness', 'Eastness', 'Hour']
missing_columns = [col for col in required_columns if col not in grid_gdf.columns]
if missing_columns:
raise KeyError(f"The following required columns are missing in grid_gdf: {missing_columns}")
else:
print("All required columns are present in grid_gdf.")
# Include MODIS_LST in grid_gdf (Already included)
# Prepare data for regression prediction
# Include land cover dummy variables and new temporal/interactions
for col in land_cover_dummies_stations.columns:
if col not in grid_gdf.columns:
grid_gdf[col] = 0
# Add Sinusoidal Encoding for Hour-of-Day
grid_gdf['sin_hour'] = np.sin(2 * np.pi * grid_gdf['Hour'] / 24)
grid_gdf['cos_hour'] = np.cos(2 * np.pi * grid_gdf['Hour'] / 24)
# Create Interaction Terms between Elevation and Temporal Features
grid_gdf['Elevation_sin_hour'] = grid_gdf['Elevation'] * grid_gdf['sin_hour']
grid_gdf['Elevation_cos_hour'] = grid_gdf['Elevation'] * grid_gdf['cos_hour']
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)
# **Fix for KeyError: Use .iloc instead of .at**
# Prepare grid features as before
# ... [rest of your code before the loop remains unchanged] ...
# Example loop where the error occurred
for idx in range(len(grid_gdf)):
try:
x = grid_gdf.iloc[idx]['X']
y = grid_gdf.iloc[idx]['Y']
# Continue with the rest of your processing
# ...
except IndexError as e:
print(f"IndexError at position {idx}: {e}")
# Handle the error or skip
continue
# ... [rest of your code remains unchanged] ...