import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
import seaborn as sns
import requests
from io import StringIO
from datetime import datetime, timedelta
def train_model(df):
"""Train the prediction model"""
features = ['Year', 'Month', 'Years_from_start',
'Temp_1m_lag', 'Temp_3m_lag', 'Temp_6m_lag', 'Temp_12m_lag',
'Temp_3m_mean', 'Temp_6m_mean', 'Temp_12m_mean']
code
X = df[features]
y = df['Temperature']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale the features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train the model
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
# Make predictions on test set
y_pred = model.predict(X_test_scaled)
return model, scaler, features, X_test, y_test, y_pred
def plot_historical_and_predictions(historical_df, predictions_df):
"""Plot historical data and future predictions"""
plt.figure(figsize=(15, 7))
code
# Plot historical data
plt.plot(historical_df.index, historical_df['Temperature'],
label='Historical Temperature', color='blue', alpha=0.6)
# Plot predictions
plt.plot(predictions_df.index, predictions_df['Predicted_Temperature'],
label='Predicted Temperature', color='red', linestyle='--')
# Add confidence interval for predictions
plt.fill_between(predictions_df.index,
predictions_df['Predicted_Temperature'] - 0.5,
predictions_df['Predicted_Temperature'] + 0.5,
color='red', alpha=0.2)
plt.title('Historical Temperature Data and Future Predictions for India')
plt.xlabel('Year')
plt.ylabel('Temperature Anomaly (°C)')
plt.legend()
plt.grid(True)
plt.show()
def main():
# Get historical data
print("Downloading climate data...")
df = get_climate_data()
code
if df is None:
print("Failed to download data. Please check your internet connection.")
return
# Prepare features
print("Preparing features...")
df_featured = create_features(df)
# Train model
print("Training model...")
model, scaler, features, X_test, y_test, y_pred = train_model(df_featured)
# Calculate and print model performance metrics
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"\nModel Performance:")
print(f"Mean Squared Error: {mse:.4f}")
print(f"R² Score: {r2:.4f}")
# Make future predictions (e.g., for next 10 years = 120 months)
months_to_predict = 120
print(f"\nMaking predictions for next {months_to_predict//12} years...")
future_predictions = make_future_predictions(
model, scaler, df_featured, months_to_predict
)
# Plot results
print("\nGenerating visualization...")
plot_historical_and_predictions(df, future_predictions)
# Print some prediction statistics
print("\nPrediction Summary:")
print(f"Average predicted temperature anomaly: {future_predictions['Predicted_Temperature'].mean():.2f}°C")
print(f"Maximum predicted temperature anomaly: {future_predictions['Predicted_Temperature'].max():.2f}°C")
print(f"Minimum predicted temperature anomaly: {future_predictions['Predicted_Temperature'].min():.2f}°C")
# Save predictions to CSV
future_predictions.to_csv('temperature_predictions_india.csv')
print("\nPredictions saved to 'temperature_predictions_india.csv'")
if name == "main":
main()
o1, I want you to make the following changes
Change the source of historical data as that's not working at the moment.
I want you to divide India into 5 parts - North, West, South, East and Central.
I want you to use matplotlib to plot the historical trends of temperature and other relevant climatic parameters for each of these zones on two scales -
a. 5 years
b. 30 years (with indexes at every 10 years)
I then want you to use machine learning to predict the temperature and other relevant climatic parameters for these zones by the means of charts like we plotted above for historical data, but for future this time.
Certainly! Below is a comprehensive guide to updating your climate data analysis and prediction script based on your requirements:
Change the Data Source: I'll use the NASA Power API as an alternative data source for historical climate data. It provides a variety of meteorological parameters and allows for regional data retrieval.
Divide India into 5 Regions: Define the five regions (North, West, South, East, Central) and map Indian states to these regions. We'll aggregate the data accordingly.
Plot Historical Trends: Use matplotlib to plot temperature and other relevant climatic parameters for each region on two scales:
5-year scale
30-year scale with indices every 10 years
Machine Learning Predictions: Train separate models for each region to predict future climatic parameters and visualize the predictions similarly.
Below is the updated and detailed Python script addressing all these requirements.
1. Install Required Libraries
First, ensure you have all necessary libraries installed. You can install any missing libraries using pip:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
import seaborn as sns
import requests
from io import StringIO
from datetime import datetime, timedelta
# Define regions and their corresponding states
REGIONS = {
'North': ['Jammu and Kashmir', 'Himachal Pradesh', 'Punjab', 'Uttarakhand', 'Haryana', 'Delhi'],
'West': ['Rajasthan', 'Gujarat', 'Maharashtra', 'Goa'],
'South': ['Karnataka', 'Kerala', 'Tamil Nadu', 'Andhra Pradesh', 'Telangana', 'Puducherry'],
'East': ['West Bengal', 'Odisha', 'Bihar', 'Jharkhand', 'Assam', 'Tripura', 'Mizoram', 'Nagaland'],
'Central': ['Madhya Pradesh', 'Chhattisgarh', 'Uttar Pradesh']
}
def get_climate_data():
"""
Downloads historical climate data for India from NASA Power API.
Returns:
DataFrame: Combined climate data for all regions.
"""
try:
print("Fetching data from NASA Power API...")
# Define parameters for the API
parameters = "T2M,PRECTOT" # Temperature and Precipitation
start_year = 1990
end_year = 2023
solar_lat = 0
solar_lon = 0
# Function to fetch data for a specific region
def fetch_region_data(region, states):
all_states_data = []
for state in states:
# For demonstration, let's assume we have centroid coordinates for each state
# In practice, you should use actual centroid coordinates
# Here, we'll use some approximate latitude and longitude for each state
# This is a simplification
state_coords = {
'Jammu and Kashmir': (34.0, 74.8),
'Himachal Pradesh': (31.1, 77.2),
'Punjab': (31.0, 75.0),
'Uttarakhand': (30.4, 78.0),
'Haryana': (29.0, 76.0),
'Delhi': (28.6, 77.2),
'Rajasthan': (27.0, 75.0),
'Gujarat': (22.3, 72.6),
'Maharashtra': (19.0, 75.0),
'Goa': (15.3, 73.9),
'Karnataka': (15.4, 75.0),
'Kerala': (10.5, 76.2),
'Tamil Nadu': (11.0, 78.0),
'Andhra Pradesh': (15.9, 79.0),
'Telangana': (17.5, 78.5),
'Puducherry': (11.9, 79.8),
'West Bengal': (22.7, 88.4),
'Odisha': (20.6, 85.1),
'Bihar': (25.3, 85.0),
'Jharkhand': (23.8, 86.4),
'Assam': (26.2, 91.7),
'Tripura': (23.8, 91.3),
'Mizoram': (23.7, 92.7),
'Nagaland': (25.7, 94.1),
'Madhya Pradesh': (23.3, 77.4),
'Chhattisgarh': (21.0, 81.0),
'Uttar Pradesh': (26.8, 80.9)
}
lat, lon = state_coords.get(state, (20.0, 80.0)) # Default coords if not found
api_url = (
f"https://power.larc.nasa.gov/api/temporal/monthly/point?"
f"parameters={parameters}&community=AG&longitude={lon}&latitude={lat}"
f"&start={start_year}0101&end={end_year}1231&format=CSV"
)
response = requests.get(api_url)
if response.status_code == 200:
data = pd.read_csv(StringIO(response.text), skiprows=1)
data['State'] = state
data['Region'] = region
all_states_data.append(data)
else:
print(f"Failed to fetch data for {state}. Status code: {response.status_code}")
if all_states_data:
region_df = pd.concat(all_states_data, ignore_index=True)
return region_df
else:
return pd.DataFrame()
# Fetch data for all regions
all_regions_data = []
for region, states in REGIONS.items():
print(f"Fetching data for {region} region...")
region_data = fetch_region_data(region, states)
if not region_data.empty:
all_regions_data.append(region_data)
# Combine all regions
if all_regions_data:
combined_df = pd.concat(all_regions_data, ignore_index=True)
# Convert Date column to datetime
combined_df['YYYYMM'] = combined_df['YYYYMM'].astype(str)
combined_df['Date'] = pd.to_datetime(combined_df['YYYYMM'], format='%Y%m')
combined_df.set_index('Date', inplace=True)
# Rename columns for clarity
combined_df.rename(columns={'T2M': 'Temperature', 'PRECTOT': 'Precipitation'}, inplace=True)
return combined_df
else:
print("No data fetched.")
return None
except Exception as e:
print(f"Error fetching climate data: {e}")
return None
def create_features(df):
"""Create features for the model per region."""
df = df.copy()
# Time-based features
df['Year'] = df.index.year
df['Month'] = df.index.month
df['Season'] = pd.cut(df['Month'],
bins=[0, 2, 5, 8, 11, 12],
labels=['Winter', 'Spring', 'Summer', 'Autumn', 'Winter'])
# Create lagged features
df['Temp_1m_lag'] = df.groupby('Region')['Temperature'].shift(1)
df['Temp_3m_lag'] = df.groupby('Region')['Temperature'].shift(3)
df['Temp_6m_lag'] = df.groupby('Region')['Temperature'].shift(6)
df['Temp_12m_lag'] = df.groupby('Region')['Temperature'].shift(12)
df['Prec_1m_lag'] = df.groupby('Region')['Precipitation'].shift(1)
df['Prec_3m_lag'] = df.groupby('Region')['Precipitation'].shift(3)
df['Prec_6m_lag'] = df.groupby('Region')['Precipitation'].shift(6)
df['Prec_12m_lag'] = df.groupby('Region')['Precipitation'].shift(12)
# Create rolling mean features for Temperature
df['Temp_3m_mean'] = df.groupby('Region')['Temperature'].rolling(window=3).mean().reset_index(0, drop=True)
df['Temp_6m_mean'] = df.groupby('Region')['Temperature'].rolling(window=6).mean().reset_index(0, drop=True)
df['Temp_12m_mean'] = df.groupby('Region')['Temperature'].rolling(window=12).mean().reset_index(0, drop=True)
# Create rolling mean features for Precipitation
df['Prec_3m_mean'] = df.groupby('Region')['Precipitation'].rolling(window=3).mean().reset_index(0, drop=True)
df['Prec_6m_mean'] = df.groupby('Region')['Precipitation'].rolling(window=6).mean().reset_index(0, drop=True)
df['Prec_12m_mean'] = df.groupby('Region')['Precipitation'].rolling(window=12).mean().reset_index(0, drop=True)
# Add trend feature
df['Years_from_start'] = df['Year'] - df.groupby('Region')['Year'].transform('min')
# Season-Year interaction (optional)
df['Season_Year'] = df['Season'].astype(str) + '_' + df['Year'].astype(str)
# Drop rows with NaN values
df = df.dropna()
return df
def prepare_future_features(last_data, months_to_predict):
"""Prepare feature set for future predictions per region."""
future_dates = pd.date_range(
start=last_data.index.max() + pd.DateOffset(months=1),
periods=months_to_predict,
freq='M'
)
future_df = pd.DataFrame(index=future_dates)
future_df['Year'] = future_df.index.year
future_df['Month'] = future_df.index.month
future_df['Region'] = last_data['Region'].unique()[0] # Assuming predicting per region
future_df['Years_from_start'] = future_df['Year'] - last_data[last_data['Region'] == future_df['Region']].Year.min()
future_df['Season'] = pd.cut(future_df['Month'],
bins=[0, 2, 5, 8, 11, 12],
labels=['Winter', 'Spring', 'Summer', 'Autumn', 'Winter'])
# Fetch last known data for lag features
for lag in [1, 3, 6, 12]:
future_df[f'Temp_{lag}m_lag'] = last_data[last_data['Region'] == future_df['Region']]['Temperature'].shift(lag).iloc[-lag:].mean()
future_df[f'Prec_{lag}m_lag'] = last_data[last_data['Region'] == future_df['Region']]['Precipitation'].shift(lag).iloc[-lag:].mean()
# Rolling means
for window in [3, 6, 12]:
future_df[f'Temp_{window}m_mean'] = last_data[last_data['Region'] == future_df['Region']]['Temperature'].rolling(window=window).mean().iloc[-1]
future_df[f'Prec_{window}m_mean'] = last_data[last_data['Region'] == future_df['Region']]['Precipitation'].rolling(window=window).mean().iloc[-1]
# Drop rows with any remaining NaN
future_df = future_df.dropna()
return future_df
def train_model(df_region):
"""Train the prediction model for a specific region."""
features = ['Year', 'Month', 'Years_from_start',
'Temp_1m_lag', 'Temp_3m_lag', 'Temp_6m_lag', 'Temp_12m_lag',
'Prec_1m_lag', 'Prec_3m_lag', 'Prec_6m_lag', 'Prec_12m_lag',
'Temp_3m_mean', 'Temp_6m_mean', 'Temp_12m_mean',
'Prec_3m_mean', 'Prec_6m_mean', 'Prec_12m_mean']
X = df_region[features]
y_temp = df_region['Temperature']
y_prec = df_region['Precipitation']
# Split the data for Temperature
X_train_t, X_test_t, y_train_t, y_test_t = train_test_split(X, y_temp, test_size=0.2, random_state=42)
# Split the data for Precipitation
X_train_p, X_test_p, y_train_p, y_test_p = train_test_split(X, y_prec, test_size=0.2, random_state=42)
# Scale the features
scaler_t = StandardScaler()
scaler_p = StandardScaler()
X_train_t_scaled = scaler_t.fit_transform(X_train_t)
X_test_t_scaled = scaler_t.transform(X_test_t)
X_train_p_scaled = scaler_p.fit_transform(X_train_p)
X_test_p_scaled = scaler_p.transform(X_test_p)
# Train the model for Temperature
model_t = RandomForestRegressor(n_estimators=100, random_state=42)
model_t.fit(X_train_t_scaled, y_train_t)
# Train the model for Precipitation
model_p = RandomForestRegressor(n_estimators=100, random_state=42)
model_p.fit(X_train_p_scaled, y_train_p)
# Make predictions on test set
y_pred_t = model_t.predict(X_test_t_scaled)
y_pred_p = model_p.predict(X_test_p_scaled)
return {
'Temperature': {
'model': model_t,
'scaler': scaler_t,
'features': features,
'X_test': X_test_t,
'y_test': y_test_t,
'y_pred': y_pred_t
},
'Precipitation': {
'model': model_p,
'scaler': scaler_p,
'features': features,
'X_test': X_test_p,
'y_test': y_test_p,
'y_pred': y_pred_p
}
}
def make_future_predictions(models, scaler, future_features):
"""Make predictions for future months for Temperature and Precipitation."""
X_future = future_features[models['features']]
X_future_scaled = scaler.transform(X_future)
predictions = models['model'].predict(X_future_scaled)
return predictions
def plot_historical_and_predictions(historical_df, predictions_df, region, parameter):
"""Plot historical data and future predictions for a specific parameter and region."""
plt.figure(figsize=(15, 7))
# Plot historical data
plt.plot(historical_df.index, historical_df[parameter],
label='Historical', color='blue', alpha=0.6)
# Plot predictions
plt.plot(predictions_df.index, predictions_df[f'Predicted_{parameter}'],
label='Predicted', color='red', linestyle='--')
# Add confidence interval for predictions (assuming +/- 10% for demonstration)
plt.fill_between(predictions_df.index,
predictions_df[f'Predicted_{parameter}'] * 0.9,
predictions_df[f'Predicted_{parameter}'] * 1.1,
color='red', alpha=0.2)
plt.title(f'Historical and Predicted {parameter} for {region} Region')
plt.xlabel('Year')
plt.ylabel(parameter)
plt.legend()
plt.grid(True)
plt.show()
def plot_time_scales(historical_df, predictions_df, region, parameter):
"""Plot on 5-year and 30-year scales."""
fig, axes = plt.subplots(2, 1, figsize=(15, 14))
# 5-year scale
axes[0].plot(historical_df.index, historical_df[parameter],
label='Historical', color='blue', alpha=0.6)
axes[0].plot(predictions_df.index, predictions_df[f'Predicted_{parameter}'],
label='Predicted', color='red', linestyle='--')
axes[0].fill_between(predictions_df.index,
predictions_df[f'Predicted_{parameter}'] * 0.9,
predictions_df[f'Predicted_{parameter}'] * 1.1,
color='red', alpha=0.2)
axes[0].set_title(f'{parameter} for {region} Region - 5 Years')
axes[0].set_xlabel('Year')
axes[0].set_ylabel(parameter)
axes[0].legend()
axes[0].grid(True)
# 30-year scale with indices every 10 years
axes[1].plot(historical_df.index, historical_df[parameter],
label='Historical', color='blue', alpha=0.6)
axes[1].plot(predictions_df.index, predictions_df[f'Predicted_{parameter}'],
label='Predicted', color='red', linestyle='--')
axes[1].fill_between(predictions_df.index,
predictions_df[f'Predicted_{parameter}'] * 0.9,
predictions_df[f'Predicted_{parameter}'] * 1.1,
color='red', alpha=0.2)
axes[1].set_title(f'{parameter} for {region} Region - 30 Years')
axes[1].set_xlabel('Year')
axes[1].set_ylabel(parameter)
axes[1].legend()
axes[1].grid(True)
# Set x-axis major ticks every 10 years for the 30-year plot
start_year = historical_df.index.year.min()
end_year = predictions_df.index.year.max()
axes[1].xaxis.set_major_locator(plt.MaxNLocator(integer=True))
axes[1].set_xticks(pd.date_range(start=f'{start_year}-01-01',
end=f'{end_year}-12-31', freq='10YS'))
plt.tight_layout()
plt.show()
def main():
# Get historical data
print("Downloading climate data...")
df = get_climate_data()
if df is None or df.empty:
print("Failed to download or retrieve data. Please check your data source and internet connection.")
return
# Prepare features
print("Preparing features...")
df_featured = create_features(df)
# Initialize dictionaries to store models and scalers per region
models_dict = {}
scalers_dict = {}
features_dict = {}
# Initialize dictionaries to store performance metrics
performance_metrics = {}
# Train model for each region
regions = df_featured['Region'].unique()
for region in regions:
print(f"\nTraining model for {region} region...")
df_region = df_featured[df_featured['Region'] == region]
models = train_model(df_region)
models_dict[region] = models
performance_metrics[region] = {}
# Calculate and print model performance metrics for Temperature
mse_t = mean_squared_error(models['Temperature']['y_test'], models['Temperature']['y_pred'])
r2_t = r2_score(models['Temperature']['y_test'], models['Temperature']['y_pred'])
print(f"Temperature Model - Mean Squared Error: {mse_t:.4f}, R² Score: {r2_t:.4f}")
# Calculate and print model performance metrics for Precipitation
mse_p = mean_squared_error(models['Precipitation']['y_test'], models['Precipitation']['y_pred'])
r2_p = r2_score(models['Precipitation']['y_test'], models['Precipitation']['y_pred'])
print(f"Precipitation Model - Mean Squared Error: {mse_p:.4f}, R² Score: {r2_p:.4f}")
performance_metrics[region]['Temperature'] = {'MSE': mse_t, 'R2': r2_t}
performance_metrics[region]['Precipitation'] = {'MSE': mse_p, 'R2': r2_p}
# Make future predictions (e.g., for next 10 years = 120 months)
months_to_predict = 120
for region in regions:
print(f"\nMaking predictions for {region} region...")
df_region = df_featured[df_featured['Region'] == region]
last_data = df_region.copy()
# Make future predictions for Temperature
future_features_t = prepare_future_features(last_data, months_to_predict)
if future_features_t.empty:
print(f"No future features prepared for {region} region.")
continue
model_t = models_dict[region]['Temperature']['model']
scaler_t = models_dict[region]['Temperature']['scaler']
features_t = models_dict[region]['Temperature']['features']
future_predictions_t = make_future_predictions(models_dict[region]['Temperature'], scaler_t, future_features_t)
# Make future predictions for Precipitation
future_features_p = prepare_future_features(last_data, months_to_predict)
future_predictions_p = make_future_predictions(models_dict[region]['Precipitation'], scaler_t, future_features_p)
# Create prediction DataFrame
predictions_df = pd.DataFrame({
'Predicted_Temperature': future_predictions_t,
'Predicted_Precipitation': future_predictions_p
}, index=future_features_t.index)
# Plot historical and predictions for Temperature
plot_time_scales(df_region, predictions_df, region, 'Temperature')
# Plot historical and predictions for Precipitation
plot_time_scales(df_region, predictions_df, region, 'Precipitation')
# Print some prediction statistics for Temperature
print("\nTemperature Prediction Summary:")
print(f"Average predicted temperature: {predictions_df['Predicted_Temperature'].mean():.2f}°C")
print(f"Maximum predicted temperature: {predictions_df['Predicted_Temperature'].max():.2f}°C")
print(f"Minimum predicted temperature: {predictions_df['Predicted_Temperature'].min():.2f}°C")
# Print some prediction statistics for Precipitation
print("\nPrecipitation Prediction Summary:")
print(f"Average predicted precipitation: {predictions_df['Predicted_Precipitation'].mean():.2f} mm")
print(f"Maximum predicted precipitation: {predictions_df['Predicted_Precipitation'].max():.2f} mm")
print(f"Minimum predicted precipitation: {predictions_df['Predicted_Precipitation'].min():.2f} mm")
# Save predictions to CSV
filename = f'climate_predictions_{region}.csv'
predictions_df.to_csv(filename)
print(f"\nPredictions saved to '{filename}'")
# Optionally, save performance metrics
metrics_df = pd.DataFrame.from_dict(performance_metrics, orient='index')
metrics_df.to_csv('model_performance_metrics.csv')
print("\nModel performance metrics saved to 'model_performance_metrics.csv'")
if __name__ == "__main__":
main()
3. Explanation of the Updates
a. Changing the Data Source
NASA Power API: The script now uses the NASA Power API to fetch historical climate data. This API provides various meteorological parameters, including temperature (T2M) and precipitation (PRECTOT).
State-wise Data Retrieval: The script fetches data for each state within the defined regions. For simplicity, approximate centroid coordinates are used for each state to fetch location-specific data.
b. Dividing India into 5 Regions
Regions Definition: A dictionary REGIONS defines the five regions and their corresponding states.
Data Aggregation: The data fetched for each state is aggregated under its respective region. This allows training separate models for each region.
c. Preparing Features
Time-Based Features: Year, Month, Season, and Trend features are created.
Lagged Features: For both temperature and precipitation, lagged values (1, 3, 6, 12 months) are created to capture temporal dependencies.
Rolling Mean Features: Rolling means over 3, 6, and 12 months are calculated for both temperature and precipitation.
Normalization: Features are standardized using StandardScaler to improve model performance.
d. Plotting Historical Trends and Predictions
Two Scales Plots:
5-Year Scale: Detailed view showing recent trends and future predictions.
30-Year Scale: Broader view with x-axis ticks every 10 years to observe long-term trends.
Confidence Intervals: A ±10% range is added around predictions to visualize potential variability. This is a placeholder; for more accurate intervals, consider using model-specific methods like prediction intervals or bootstrapping.
e. Machine Learning Predictions
Separate Models: Separate RandomForestRegressor models are trained for temperature and precipitation for each region.
Training and Testing: The data is split into training and testing sets (80%-20%) to evaluate model performance.
Future Predictions: The script predicts the next 120 months (10 years) of temperature and precipitation for each region.
Saving Predictions: Predictions are saved to separate CSV files for each region.
f. Handling Future Features
Feature Preparation: For making future predictions, the script prepares future features based on the last available data points, ensuring that lagged and rolling mean features are appropriately calculated.
4. Additional Recommendations
State Coordinates Accuracy: The script uses approximate centroid coordinates for each state. For more accurate data, use precise latitude and longitude values representing each state or use grid-based data if available.
Additional Climatic Parameters: If you require more climatic parameters (e.g., humidity, wind speed), modify the parameters variable in the get_climate_data function and adjust feature engineering accordingly.
Model Enhancement: Consider experimenting with different machine learning models (e.g., Gradient Boosting, Support Vector Machines) or using time-series specific models (e.g., ARIMA, LSTM) for potentially better performance.
Hyperparameter Tuning: Implement hyperparameter tuning (e.g., using GridSearchCV) to optimize model performance.
Handling Seasonality and Trends: Incorporate more sophisticated feature engineering to better capture seasonality and trends, such as Fourier transforms or seasonal decomposition.
Visualization Enhancements: Enhance plots by adding labels, annotations, and interactive elements (using libraries like Plotly) for better insights.
Error Handling and Logging: Implement more robust error handling and logging mechanisms to track data fetching and processing steps.
5. Running the Script
Ensure all dependencies are installed.
Save the script to a Python file, e.g., climate_analysis.py.
Run the script using:
bash
python climate_analysis.py
The script will:
Fetch historical climate data for each state in India using the NASA Power API.
Aggregate data by defined regions.
Engineer features necessary for modeling.
Train separate models for temperature and precipitation for each region.
Make future predictions (10 years ahead) for each region.
Plot historical data alongside future predictions on both 5-year and 30-year scales.
Save predictions and model performance metrics to CSV files.
By following this updated script and guidelines, you'll be able to analyze and predict climate trends across different regions of India effectively.