hareshchander commited on
Commit
e9f5e41
·
verified ·
1 Parent(s): 8b44398

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -36
app.py CHANGED
@@ -1,70 +1,92 @@
1
  import streamlit as st
2
- import pandas as pd
3
  import torch
4
  import torch.nn as nn
 
5
  import joblib
6
  import plotly.express as px
7
  import os
8
 
9
- # Define the PyTorch model architecture (must match the one used during training)
10
- class SmartGridModel(nn.Module):
11
- def __init__(self, input_size, hidden_size=64, output_size=1):
12
- super(SmartGridModel, self).__init__()
 
 
13
  self.fc1 = nn.Linear(input_size, hidden_size)
14
  self.relu = nn.ReLU()
15
  self.fc2 = nn.Linear(hidden_size, output_size)
 
16
 
17
  def forward(self, x):
18
- return self.fc2(self.relu(self.fc1(x)))
 
 
 
19
 
20
- # Load model and scaler with Streamlit caching
 
 
21
  @st.cache_resource
22
  def load_model_and_scaler():
23
- # Ensure both files exist
24
- if not os.path.exists("model.pth") or not os.path.exists("scaler.pkl"):
25
- raise FileNotFoundError("Missing 'model.pth' or 'scaler.pkl'. Please upload them.")
26
 
27
- model = SmartGridModel(input_size=5)
28
- model.load_state_dict(torch.load("model.pth", map_location=torch.device("cpu")))
29
  model.eval()
30
 
31
  scaler = joblib.load("scaler.pkl")
32
  return model, scaler
33
 
34
- # Predict function
35
- def predict(data, model, scaler):
36
- input_data = scaler.transform(data)
37
- input_tensor = torch.tensor(input_data, dtype=torch.float32)
 
 
 
 
 
 
 
 
38
  with torch.no_grad():
39
- predictions = model(input_tensor).numpy()
40
- return predictions
41
 
 
 
 
 
42
  # Streamlit UI
 
 
43
  st.title("🔌 Smart Grid Line Outage Detection")
44
- st.markdown("Upload smart grid data and get outage predictions using a PyTorch model.")
45
 
46
- uploaded_file = st.file_uploader("📁 Upload a CSV file", type=["csv"])
47
 
48
  if uploaded_file:
49
- df = pd.read_csv(uploaded_file)
50
-
51
- # Ensure required columns exist
52
- required_cols = ['voltage', 'frequency', 'load', 'solar_gen', 'wind_gen']
53
- if not all(col in df.columns for col in required_cols):
54
- st.error(f"CSV must contain columns: {required_cols}")
55
- else:
56
- st.success("✅ File uploaded and validated.")
57
- st.write("Preview of uploaded data:")
58
  st.dataframe(df.head())
59
 
60
  model, scaler = load_model_and_scaler()
 
61
 
62
- predictions = predict(df[required_cols], model, scaler)
63
- df["Outage Probability"] = predictions
 
64
 
65
- st.write("📊 Prediction Results:")
66
- st.dataframe(df)
 
 
 
67
 
68
- # Visualization
69
- fig = px.line(df, y="Outage Probability", title="Line Outage Probability Over Time")
70
- st.plotly_chart(fig)
 
 
1
  import streamlit as st
 
2
  import torch
3
  import torch.nn as nn
4
+ import pandas as pd
5
  import joblib
6
  import plotly.express as px
7
  import os
8
 
9
+ # -----------------------------
10
+ # Model Definition
11
+ # -----------------------------
12
+ class SimpleNN(nn.Module):
13
+ def __init__(self, input_size, hidden_size, output_size):
14
+ super(SimpleNN, self).__init__()
15
  self.fc1 = nn.Linear(input_size, hidden_size)
16
  self.relu = nn.ReLU()
17
  self.fc2 = nn.Linear(hidden_size, output_size)
18
+ self.softmax = nn.Softmax(dim=1)
19
 
20
  def forward(self, x):
21
+ out = self.fc1(x)
22
+ out = self.relu(out)
23
+ out = self.fc2(out)
24
+ return self.softmax(out)
25
 
26
+ # -----------------------------
27
+ # Load Model and Scaler
28
+ # -----------------------------
29
  @st.cache_resource
30
  def load_model_and_scaler():
31
+ input_size = 6
32
+ hidden_size = 32
33
+ output_size = 2
34
 
35
+ model = SimpleNN(input_size, hidden_size, output_size)
36
+ model.load_state_dict(torch.load("model.pth", map_location=torch.device('cpu')))
37
  model.eval()
38
 
39
  scaler = joblib.load("scaler.pkl")
40
  return model, scaler
41
 
42
+ # -----------------------------
43
+ # Prediction Function
44
+ # -----------------------------
45
+ def make_prediction(data, model, scaler):
46
+ expected_columns = ['Voltage', 'Current', 'Frequency', 'Load', 'Power_Factor', 'Temperature']
47
+ if not all(col in data.columns for col in expected_columns):
48
+ missing_cols = list(set(expected_columns) - set(data.columns))
49
+ st.error(f"Missing columns: {missing_cols}")
50
+ return None
51
+
52
+ X = scaler.transform(data[expected_columns])
53
+ inputs = torch.tensor(X, dtype=torch.float32)
54
  with torch.no_grad():
55
+ outputs = model(inputs)
56
+ predicted = torch.argmax(outputs, dim=1).numpy()
57
 
58
+ data['Outage_Prediction'] = ['No Outage' if p == 0 else 'Line Outage' for p in predicted]
59
+ return data
60
+
61
+ # -----------------------------
62
  # Streamlit UI
63
+ # -----------------------------
64
+ st.set_page_config(page_title="Smart Grid Outage Predictor", layout="centered")
65
  st.title("🔌 Smart Grid Line Outage Detection")
66
+ st.write("Upload smart grid sensor data to detect possible line outages using a PyTorch model.")
67
 
68
+ uploaded_file = st.file_uploader("📂 Upload your smart grid CSV file", type=["csv"])
69
 
70
  if uploaded_file:
71
+ try:
72
+ df = pd.read_csv(uploaded_file)
73
+ st.subheader("📊 Uploaded Data")
 
 
 
 
 
 
74
  st.dataframe(df.head())
75
 
76
  model, scaler = load_model_and_scaler()
77
+ result_df = make_prediction(df, model, scaler)
78
 
79
+ if result_df is not None:
80
+ st.subheader("✅ Outage Predictions")
81
+ st.dataframe(result_df)
82
 
83
+ st.subheader("📈 Voltage vs Current")
84
+ fig = px.scatter(result_df, x='Voltage', y='Current', color='Outage_Prediction',
85
+ title="Voltage vs Current with Prediction Labels",
86
+ labels={'Voltage': 'Voltage (V)', 'Current': 'Current (A)'})
87
+ st.plotly_chart(fig)
88
 
89
+ except Exception as e:
90
+ st.error(f"⚠️ Error: {e}")
91
+ else:
92
+ st.info("Awaiting CSV file with these columns: Voltage, Current, Frequency, Load, Power_Factor, Temperature")