Harsh-7300 commited on
Commit
1451046
·
verified ·
1 Parent(s): dac0d51

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -59
app.py CHANGED
@@ -1,72 +1,96 @@
1
- import streamlit as st
2
  import numpy as np
3
- from keras.models import load_model
4
- from keras.losses import MeanSquaredError
5
- import joblib
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Define MSE function explicitly to be used as a custom object
8
- def mse(y_true, y_pred):
9
- return MeanSquaredError()(y_true, y_pred)
10
 
11
- # Load the trained model with the custom 'mse' loss function
12
- try:
13
- model = load_model("solar_irradiance_model.h5", custom_objects={"mse": mse})
14
- st.sidebar.success("Model loaded successfully!")
15
- except Exception as e:
16
- st.sidebar.error(f"Error loading model: {e}")
17
- st.stop()
18
 
19
- # Load the encoder and scaler (ensure they are saved as .pkl files during training)
20
- encoder = joblib.load("encoder.pkl") # Path to your encoder file
21
- scaler = joblib.load("scaler.pkl") # Path to your scaler file
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature):
24
- # Encode the categorical features (Month and Hour)
25
  encoded_month_hour = encoder.transform([[month, hour]])
26
-
27
  # Scale the numerical features
28
  scaled_features = scaler.transform([[latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature]])
29
-
30
- # Concatenate encoded categorical and scaled numerical features
31
  processed_features = np.concatenate((encoded_month_hour, scaled_features), axis=1)
32
-
33
- # Reshape the features to match the model input shape (1, 1, num_features)
34
  reshaped_features = np.reshape(processed_features, (1, 1, processed_features.shape[1]))
35
-
36
- # Predict solar irradiance using the trained model
37
- predicted_irradiance = model.predict(reshaped_features)
38
-
39
- # Return the predicted irradiance (ensuring it's non-negative)
40
  return max(predicted_irradiance[0][0], 0.0)
41
 
42
- # Set up the Streamlit frontend
43
- st.title("Solar Irradiance Prediction")
44
-
45
- # Example Input Data (adjust for your actual inputs)
46
- st.header("Enter Input Features")
47
- num_features = 9 # Since you have 9 features in total
48
-
49
- example_input = []
50
- for i in range(num_features):
51
- value = st.number_input(f"Feature {i+1}", value=0.0, format="%.2f")
52
- example_input.append(value)
53
-
54
- # Convert the input into the required format for prediction
55
- month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature = example_input
56
-
57
- # Predict button
58
- if st.button("Predict"):
59
- try:
60
- prediction = predict_irradiance(month=month, hour=hour, latitude=latitude, longitude=longitude,
61
- panel_capacity=panel_capacity, panel_efficiency=panel_efficiency,
62
- wind_speed=wind_speed, cloud_cover=cloud_cover, temperature=temperature)
63
- st.success(f"Predicted Solar Irradiance: {prediction:.2f} W/m²")
64
- except Exception as e:
65
- st.error(f"Error during prediction: {e}")
66
-
67
- # Sidebar information
68
- st.sidebar.title("About the Model")
69
- st.sidebar.markdown("""
70
- This model predicts solar irradiance based on the input features.
71
- Ensure all required features are filled in before clicking **Predict**.
72
- """)
 
 
1
  import numpy as np
2
+ import pandas as pd
3
+ from sklearn.preprocessing import OneHotEncoder, StandardScaler
4
+ from keras.models import Sequential, load_model
5
+ from keras.layers import Dense, LSTM
6
+ import matplotlib.pyplot as plt
7
+ import warnings
8
+ warnings.filterwarnings("ignore", category=UserWarning)
9
+ # Set the random seed
10
+ np.random.seed(42)
11
+
12
+ # Load the data
13
+ data = pd.read_csv('/content/Solar_Irradiance.csv')
14
+ data['Latitude'] = data['Latitude'].str.rstrip('°').astype(float)
15
+ data['Longitude'] = data['Longitude'].str.rstrip('°').astype(float)
16
+
17
+ # Extract features and target
18
+ features = data[['Month', 'Hour', 'Latitude', 'Longitude', 'Panel_Capacity(W)', 'Panel_Efficiency', 'Wind_Speed(km/h)', 'Cloud_Cover(%)', 'temperature (°f)']]
19
+ target = data['Irradiance(W/m^2)']
20
+ from sklearn.preprocessing import OneHotEncoder
21
+
22
+ # Initialize the OneHotEncoder with the correct parameter
23
+ encoder = OneHotEncoder(sparse_output=False, categories='auto')
24
 
25
+ # Example usage
26
+ categorical_features = features[['Month', 'Hour']]
27
+ encoded_categorical_features = encoder.fit_transform(categorical_features)
28
 
 
 
 
 
 
 
 
29
 
30
+ # Get the feature names after encoding
31
+ encoded_feature_names = encoder.get_feature_names_out(['Month', 'Hour'])
 
32
 
33
+ # Create a DataFrame with the encoded categorical features
34
+ encoded_categorical_features_df = pd.DataFrame(encoded_categorical_features, columns=encoded_feature_names)
35
+
36
+ # Scale the numerical features
37
+ scaler = StandardScaler()
38
+ scaled_numerical_features = scaler.fit_transform(features[['Latitude', 'Longitude', 'Panel_Capacity(W)', 'Panel_Efficiency', 'Wind_Speed(km/h)', 'Cloud_Cover(%)', 'temperature (°f)']])
39
+
40
+ # Combine encoded categorical and scaled numerical features
41
+ processed_features = np.concatenate((encoded_categorical_features_df, scaled_numerical_features), axis=1)
42
+
43
+ # Reshape the features to match the LSTM input shape
44
+ reshaped_features = np.reshape(processed_features, (processed_features.shape[0], 1, processed_features.shape[1]))
45
+ # Load the saved model
46
+ # ipython-input-10-d7dffa1aa475
47
+ # Load the saved model
48
+ from keras.models import load_model
49
+ from keras.losses import mean_squared_error # Import the MSE loss function
50
+
51
+ # Load the model with custom_objects
52
+ loaded_model = load_model('solar_irradiance_model.h5', custom_objects={'mse': mean_squared_error})
53
+
54
+ # ... (rest of the code remains the same)
55
+
56
+ # Function to predict the irradiance for a given month, hour, and other features
57
  def predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature):
58
+ # Encode the month and hour
59
  encoded_month_hour = encoder.transform([[month, hour]])
 
60
  # Scale the numerical features
61
  scaled_features = scaler.transform([[latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature]])
62
+ # Combine encoded categorical and scaled numerical features
 
63
  processed_features = np.concatenate((encoded_month_hour, scaled_features), axis=1)
64
+ # Reshape the features to match the LSTM input shape
 
65
  reshaped_features = np.reshape(processed_features, (1, 1, processed_features.shape[1]))
66
+ # Predict the irradiance
67
+ predicted_irradiance = loaded_model.predict(reshaped_features)
 
 
 
68
  return max(predicted_irradiance[0][0], 0.0)
69
 
70
+ # Function to get the actual irradiance for a given month
71
+ def get_actual_irradiance(month):
72
+ return data[data['Month'] == month]['Irradiance(W/m^2)'].values
73
+
74
+ # Example usage: Predict the irradiance for July, hour 12 with additional features
75
+ month = 'January'
76
+ hour = 12
77
+ predicted_irradiance = predict_irradiance(month, hour, 28.570633, 77.327215, 500, 0.15, 6.43988, 17.7, 55)
78
+ print(f'Predicted irradiance for {month}, hour {hour}: {predicted_irradiance}')
79
+
80
+ # Plot Actual vs. Predicted Irradiance for a specific month
81
+ month = 'January'
82
+ actual_irradiance = get_actual_irradiance(month)
83
+ predicted_irradiances = []
84
+
85
+ for hour in range(24):
86
+ irradiance = predict_irradiance(month, hour, 28.570633, 77.327215, 500, 0.15, 6.43988, 17.7, 55)
87
+ predicted_irradiances.append(irradiance)
88
+
89
+ plt.figure(figsize=(12, 6))
90
+ plt.plot(range(24), actual_irradiance, label='Actual Irradiance')
91
+ plt.plot(range(24), predicted_irradiances, label='Predicted Irradiance')
92
+ plt.xlabel('Hour')
93
+ plt.ylabel('Irradiance (W/m^2)')
94
+ plt.title(f'Actual vs. Predicted Irradiance for {month}')
95
+ plt.legend()
96
+ plt.show()