Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,59 +1,35 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
|
|
|
|
|
|
| 4 |
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
| 5 |
from keras.models import load_model
|
| 6 |
-
|
| 7 |
-
from keras.layers import LSTM
|
| 8 |
-
import keras
|
| 9 |
-
from keras import backend as K
|
| 10 |
-
|
| 11 |
-
@keras.saving.register_keras_serializable()
|
| 12 |
-
def custom_mse(y_true, y_pred):
|
| 13 |
-
return K.mean(K.square(y_pred - y_true))
|
| 14 |
-
|
| 15 |
-
def custom_lstm(*args, **kwargs):
|
| 16 |
-
kwargs.pop('time_major', None) # Remove the unsupported argument
|
| 17 |
-
return LSTM(*args, **kwargs)
|
| 18 |
-
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
# Load the trained model
|
| 23 |
-
try:
|
| 24 |
-
loaded_model = load_model('solar_irradiance_model.h5', custom_objects={'LSTM': custom_lstm})
|
| 25 |
-
except ValueError as e:
|
| 26 |
-
st.error(f"Error loading model: {e}")
|
| 27 |
-
|
| 28 |
-
# Load the dataset
|
| 29 |
-
data = pd.read_csv('Solar_Irradiance.csv')
|
| 30 |
data['Latitude'] = data['Latitude'].str.rstrip('°').astype(float)
|
| 31 |
data['Longitude'] = data['Longitude'].str.rstrip('°').astype(float)
|
| 32 |
|
| 33 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
encoder = OneHotEncoder(sparse=False, categories='auto')
|
| 35 |
-
categorical_features =
|
| 36 |
encoder.fit(categorical_features)
|
| 37 |
-
|
| 38 |
-
# Standard scaler setup
|
| 39 |
scaler = StandardScaler()
|
| 40 |
-
|
| 41 |
-
scaler.fit(numerical_features)
|
| 42 |
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
-
encoded_month_hour = encoder.transform([[month, hour]])
|
| 46 |
-
scaled_features = scaler.transform([[latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature]])
|
| 47 |
-
processed_features = np.concatenate((encoded_month_hour, scaled_features), axis=1)
|
| 48 |
-
reshaped_features = np.reshape(processed_features, (1, 1, processed_features.shape[1]))
|
| 49 |
-
predicted_irradiance = loaded_model.predict(reshaped_features)
|
| 50 |
-
return max(predicted_irradiance[0][0], 0.0)
|
| 51 |
|
| 52 |
-
# Streamlit app
|
| 53 |
-
st.title("Solar Irradiance Prediction
|
| 54 |
st.sidebar.header("Input Parameters")
|
| 55 |
|
| 56 |
-
# User inputs
|
| 57 |
month = st.sidebar.selectbox("Month", data['Month'].unique())
|
| 58 |
hour = st.sidebar.slider("Hour", 0, 23, 12)
|
| 59 |
latitude = st.sidebar.number_input("Latitude", value=28.570633)
|
|
@@ -64,21 +40,116 @@ wind_speed = st.sidebar.number_input("Wind Speed (km/h)", value=6.43988)
|
|
| 64 |
cloud_cover = st.sidebar.number_input("Cloud Cover (%)", value=17.7)
|
| 65 |
temperature = st.sidebar.number_input("Temperature (°F)", value=55.0)
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
import pandas as pd
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
| 6 |
from keras.models import load_model
|
| 7 |
+
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
# Load the data
|
| 10 |
+
data = pd.read_csv('solar_irradiance.csv')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
data['Latitude'] = data['Latitude'].str.rstrip('°').astype(float)
|
| 12 |
data['Longitude'] = data['Longitude'].str.rstrip('°').astype(float)
|
| 13 |
|
| 14 |
+
# Extract features and target
|
| 15 |
+
features = data[['Month', 'Hour', 'Latitude', 'Longitude', 'Panel_Capacity(W)', 'Panel_Efficiency', 'Wind_Speed(km/h)', 'Cloud_Cover(%)', 'temperature (°f)']]
|
| 16 |
+
target = data['Irradiance(W/m^2)']
|
| 17 |
+
|
| 18 |
+
# Set up the encoder and scaler
|
| 19 |
encoder = OneHotEncoder(sparse=False, categories='auto')
|
| 20 |
+
categorical_features = features[['Month', 'Hour']]
|
| 21 |
encoder.fit(categorical_features)
|
|
|
|
|
|
|
| 22 |
scaler = StandardScaler()
|
| 23 |
+
scaler.fit(features[['Latitude', 'Longitude', 'Panel_Capacity(W)', 'Panel_Efficiency', 'Wind_Speed(km/h)', 'Cloud_Cover(%)', 'temperature (°f)']])
|
|
|
|
| 24 |
|
| 25 |
+
# Load the saved model
|
| 26 |
+
loaded_model = load_model('solar_irradiance_model.h5')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
# Streamlit app setup
|
| 29 |
+
st.title("Solar Irradiance Prediction")
|
| 30 |
st.sidebar.header("Input Parameters")
|
| 31 |
|
| 32 |
+
# User inputs from sidebar
|
| 33 |
month = st.sidebar.selectbox("Month", data['Month'].unique())
|
| 34 |
hour = st.sidebar.slider("Hour", 0, 23, 12)
|
| 35 |
latitude = st.sidebar.number_input("Latitude", value=28.570633)
|
|
|
|
| 40 |
cloud_cover = st.sidebar.number_input("Cloud Cover (%)", value=17.7)
|
| 41 |
temperature = st.sidebar.number_input("Temperature (°F)", value=55.0)
|
| 42 |
|
| 43 |
+
# Function to predict irradiance
|
| 44 |
+
def predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature):
|
| 45 |
+
encoded_month_hour = encoder.transform([[month, hour]])
|
| 46 |
+
scaled_features = scaler.transform([[latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature]])
|
| 47 |
+
processed_features = np.concatenate((encoded_month_hour, scaled_features), axis=1)
|
| 48 |
+
reshaped_features = np.reshape(processed_features, (1, 1, processed_features.shape[1]))
|
| 49 |
+
predicted_irradiance = loaded_model.predict(reshaped_features)
|
| 50 |
+
return max(predicted_irradiance[0][0], 0.0)
|
| 51 |
+
|
| 52 |
+
# Display the predicted irradiance
|
| 53 |
+
predicted_irradiance = predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature)
|
| 54 |
+
st.write(f"Predicted irradiance for {month}, hour {hour}: {predicted_irradiance:.2f} W/m^2")
|
| 55 |
+
|
| 56 |
+
# Plot actual vs. predicted irradiance
|
| 57 |
+
def plot_actual_vs_predicted(month):
|
| 58 |
+
actual_irradiance = data[data['Month'] == month]['Irradiance(W/m^2)'].values
|
| 59 |
+
predicted_irradiances = []
|
| 60 |
+
|
| 61 |
+
for hour in range(24):
|
| 62 |
+
irradiance = predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature)
|
| 63 |
+
predicted_irradiances.append(irradiance)
|
| 64 |
+
|
| 65 |
+
plt.figure(figsize=(12, 6))
|
| 66 |
+
plt.plot(range(24), actual_irradiance, label='Actual Irradiance', color='blue')
|
| 67 |
+
plt.plot(range(24), predicted_irradiances, label='Predicted Irradiance', color='red')
|
| 68 |
+
plt.xlabel('Hour')
|
| 69 |
+
plt.ylabel('Irradiance (W/m^2)')
|
| 70 |
+
plt.title(f'Actual vs. Predicted Irradiance for {month}')
|
| 71 |
+
plt.legend()
|
| 72 |
+
st.pyplot(plt)
|
| 73 |
+
|
| 74 |
+
# Display the plot
|
| 75 |
+
plot_actual_vs_predicted(month)
|
| 76 |
+
|
| 77 |
+
# Function to calculate and display evaluation metrics
|
| 78 |
+
def display_evaluation_metrics():
|
| 79 |
+
metrics_df = pd.DataFrame(columns=['Month', 'MSE', 'RMSE', 'MAE', 'R-squared'])
|
| 80 |
+
|
| 81 |
+
for month in data['Month'].unique():
|
| 82 |
+
actual_irradiance = get_actual_irradiance(month)
|
| 83 |
+
predicted_irradiance = []
|
| 84 |
+
|
| 85 |
+
for hour in range(24):
|
| 86 |
+
irradiance = predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature)
|
| 87 |
+
predicted_irradiance.append(irradiance)
|
| 88 |
+
|
| 89 |
+
mse = mean_squared_error(actual_irradiance, predicted_irradiance)
|
| 90 |
+
rmse = np.sqrt(mse)
|
| 91 |
+
mae = mean_absolute_error(actual_irradiance, predicted_irradiance)
|
| 92 |
+
r2 = r2_score(actual_irradiance, predicted_irradiance)
|
| 93 |
+
|
| 94 |
+
metrics_df = metrics_df.append({'Month': month, 'MSE': mse, 'RMSE': rmse, 'MAE': mae, 'R-squared': r2}, ignore_index=True)
|
| 95 |
+
|
| 96 |
+
st.write("Evaluation Metrics for Each Month")
|
| 97 |
+
st.dataframe(metrics_df)
|
| 98 |
+
|
| 99 |
+
# Display evaluation metrics
|
| 100 |
+
display_evaluation_metrics()
|
| 101 |
+
|
| 102 |
+
# Function to plot actual vs. predicted irradiance scatter plot
|
| 103 |
+
def plot_irradiance_scatter(month):
|
| 104 |
+
actual_irradiance = get_actual_irradiance(month)
|
| 105 |
+
predicted_irradiances = []
|
| 106 |
+
|
| 107 |
+
for hour in range(24):
|
| 108 |
+
irradiance = predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature)
|
| 109 |
+
predicted_irradiances.append(irradiance)
|
| 110 |
+
|
| 111 |
+
plt.figure(figsize=(8, 6))
|
| 112 |
+
plt.scatter(range(24), actual_irradiance, label='Actual Irradiance', color='blue')
|
| 113 |
+
plt.scatter(range(24), predicted_irradiances, label='Predicted Irradiance', color='red')
|
| 114 |
+
plt.xlabel('Hour')
|
| 115 |
+
plt.ylabel('Irradiance (W/m^2)')
|
| 116 |
+
plt.title(f'Actual vs. Predicted Irradiance for {month}')
|
| 117 |
+
plt.legend()
|
| 118 |
+
st.pyplot(plt)
|
| 119 |
+
|
| 120 |
+
# Example usage: scatter plot for selected month
|
| 121 |
+
plot_irradiance_scatter(month)
|
| 122 |
+
|
| 123 |
+
# Function to plot hour vs. irradiance for all months
|
| 124 |
+
def plot_hour_vs_irradiance():
|
| 125 |
+
months = data['Month'].unique()
|
| 126 |
+
hour_range = range(24)
|
| 127 |
+
|
| 128 |
+
predicted_irradiances = np.zeros((len(months), 24))
|
| 129 |
+
actual_irradiances = np.zeros((len(months), 24))
|
| 130 |
+
|
| 131 |
+
for i, month in enumerate(months):
|
| 132 |
+
for hour in hour_range:
|
| 133 |
+
if hour in range(6) or hour in range(18, 24):
|
| 134 |
+
irradiance = 0 # Set predicted irradiance to 0
|
| 135 |
+
else:
|
| 136 |
+
irradiance = predict_irradiance(month, hour, latitude, longitude, panel_capacity, panel_efficiency, wind_speed, cloud_cover, temperature)
|
| 137 |
+
predicted_irradiances[i][hour] = irradiance
|
| 138 |
+
actual_irradiances[i][hour] = get_actual_irradiance(month)[hour]
|
| 139 |
+
|
| 140 |
+
bar_width = 0.35
|
| 141 |
+
index = np.arange(len(hour_range))
|
| 142 |
+
|
| 143 |
+
plt.figure(figsize=(12, 6))
|
| 144 |
+
plt.bar(index, predicted_irradiances.mean(axis=0), bar_width, label='Predicted Irradiance')
|
| 145 |
+
plt.bar(index + bar_width, actual_irradiances.mean(axis=0), bar_width, label='Actual Irradiance')
|
| 146 |
+
|
| 147 |
+
plt.xlabel('Hour')
|
| 148 |
+
plt.ylabel('Irradiance (W/m^2)')
|
| 149 |
+
plt.title('Hour vs. Irradiance (Average for All Months)')
|
| 150 |
+
plt.xticks(index + bar_width/2, hour_range)
|
| 151 |
+
plt.legend()
|
| 152 |
+
st.pyplot(plt)
|
| 153 |
+
|
| 154 |
+
# Plot hour vs. irradiance for all months
|
| 155 |
+
plot_hour_vs_irradiance()
|