KAPtechies commited on
Commit
01c9c42
·
verified ·
1 Parent(s): 84cb523

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -29
app.py CHANGED
@@ -1,42 +1,63 @@
1
  import gradio as gr
2
- import numpy as np
3
  import pandas as pd
4
- from tensorflow.keras.models import load_model
5
- import tensorflow.keras.losses
 
6
  from sklearn.preprocessing import MinMaxScaler
 
7
 
 
 
8
 
9
- # Explicitly define the loss function
10
- custom_objects = {"mse": tensorflow.keras.losses.MeanSquaredError()}
11
-
12
- # Load the trained LSTM model with custom_objects
13
- model = load_model("climate_model.h5", custom_objects=custom_objects)
14
- # Ensure this file is uploaded
15
 
16
- # Load dataset to get scaler reference
17
- df = pd.read_csv("TEMP_ANNUAL_SEASONAL_MEAN.csv")
18
- df['ANNUAL'] = pd.to_numeric(df['ANNUAL'], errors='coerce') # Ensure correct type
19
- data = df[['ANNUAL']].dropna()
20
 
21
- # Normalize using MinMaxScaler
22
  scaler = MinMaxScaler()
23
  data_scaled = scaler.fit_transform(data)
24
 
25
- # Function to predict future temperature
 
 
 
26
  def predict_temperature(year):
27
- last_10_years = data_scaled[-10:].reshape(1, 10, 1) # Last 10 years as input
28
- prediction = model.predict(last_10_years)
29
- predicted_temp = scaler.inverse_transform(prediction)[0][0] # Convert back to original scale
30
- return f"Predicted Temperature for {year}: {predicted_temp:.2f}°C"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  # Gradio Interface
33
- iface = gr.Interface(
34
- fn=predict_temperature,
35
- inputs=gr.Number(label="Enter Year"),
36
- outputs=gr.Textbox(label="Predicted Temperature"),
37
- title="Climate Prediction",
38
- description="Enter a year to predict the average annual temperature."
39
- )
40
-
41
- # Launch Gradio App
42
- iface.launch()
 
1
  import gradio as gr
 
2
  import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
  from sklearn.preprocessing import MinMaxScaler
7
+ from tensorflow.keras.models import load_model
8
 
9
+ # Load dataset
10
+ df = pd.read_csv("TEMP_ANNUAL_SEASONAL_MEAN.csv")
11
 
12
+ # Convert 'YEAR' to datetime and set as index
13
+ df.columns = df.columns.str.upper()
14
+ df['YEAR'] = pd.to_datetime(df['YEAR'], format='%Y')
15
+ df.set_index('YEAR', inplace=True)
 
 
16
 
17
+ # Select relevant temperature column
18
+ temp_col = 'ANNUAL'
19
+ df[temp_col] = pd.to_numeric(df[temp_col], errors='coerce') # Handle errors
20
+ data = df[[temp_col]].dropna()
21
 
22
+ # Normalize the data
23
  scaler = MinMaxScaler()
24
  data_scaled = scaler.fit_transform(data)
25
 
26
+ # Load trained model
27
+ model = load_model("climate_model.h5")
28
+
29
+ # Prediction function
30
  def predict_temperature(year):
31
+ year = int(year)
32
+
33
+ # Generate input for LSTM
34
+ sequence_length = 10
35
+ last_seq = data_scaled[-sequence_length:].reshape(1, sequence_length, 1)
36
+
37
+ # Predict
38
+ prediction_scaled = model.predict(last_seq)
39
+ predicted_temp = scaler.inverse_transform(prediction_scaled)[0][0]
40
+
41
+ # Generate graph
42
+ fig, ax = plt.subplots(figsize=(10, 5))
43
+ ax.plot(df.index[-20:], df[temp_col][-20:], label="Actual", color='blue')
44
+ ax.axvline(pd.Timestamp(year, 1, 1), color='red', linestyle='dashed', label="Predicted Year")
45
+ ax.scatter(pd.Timestamp(year, 1, 1), predicted_temp, color='red', marker='o', label=f"Predicted: {predicted_temp:.2f}°C")
46
+ ax.set_xlabel("Year")
47
+ ax.set_ylabel("Temperature (°C)")
48
+ ax.set_title("Actual vs Predicted Annual Mean Temperature in India")
49
+ ax.legend()
50
+
51
+ return predicted_temp, fig # Return numeric output and graph
52
 
53
  # Gradio Interface
54
+ with gr.Blocks() as demo:
55
+ gr.Markdown("## Climate Change Temperature Prediction")
56
+ year_input = gr.Number(label="Enter Year (e.g., 2027)", value=2027)
57
+ predict_button = gr.Button("Predict")
58
+ output_temp = gr.Number(label="Predicted Temperature (°C)")
59
+ output_plot = gr.Plot()
60
+
61
+ predict_button.click(predict_temperature, inputs=[year_input], outputs=[output_temp, output_plot])
62
+
63
+ demo.launch()