-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmartaip.py
More file actions
178 lines (148 loc) Β· 6.88 KB
/
smartaip.py
File metadata and controls
178 lines (148 loc) Β· 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import geopandas as gpd
from shapely.geometry import Point
# ML & Evaluation
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, IsolationForest
from sklearn.linear_model import LogisticRegression
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix
# Streamlit Page Configuration
st.set_page_config(page_title="Smart Meter Fraud Detection", layout="wide")
# π Title
st.title("π Smart Meter Fraud Detection & Analysis")
# π Sidebar - Upload Dataset
st.sidebar.header("Upload Dataset")
uploaded_file = st.sidebar.file_uploader("Upload CSV", type=["csv"])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
# Convert Timestamp to DateTime format
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
# Extract Time Features
df['Hour'] = df['Timestamp'].dt.hour
df['Day'] = df['Timestamp'].dt.day
df['Month'] = df['Timestamp'].dt.month
df['DayOfWeek'] = df['Timestamp'].dt.dayofweek
# Select Features & Target
features = ['Hour', 'Day', 'Month', 'DayOfWeek', 'Energy Consumption (kWh)', 'Voltage (kV)', 'Frequency (Hz)', 'Power Factor']
X = df[features]
y = df['Fraud']
# Train-Test Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# π Sidebar - Select Model
st.sidebar.header("Select Machine Learning Model")
model_choice = st.sidebar.selectbox(
"Choose Model",
["Random Forest", "Isolation Forest", "Logistic Regression", "XGBoost"]
)
# Model Initialization
models = {
"Random Forest": RandomForestClassifier(n_estimators=100, random_state=42),
"Isolation Forest": IsolationForest(contamination=0.1, random_state=42),
"Logistic Regression": LogisticRegression(max_iter=500),
"XGBoost": XGBClassifier(use_label_encoder=False, eval_metric='logloss')
}
# Train & Evaluate Model
if st.sidebar.button("Train Model"):
model = models[model_choice]
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# Compute Evaluation Metrics
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average="macro")
recall = recall_score(y_test, y_pred, average="macro")
f1 = f1_score(y_test, y_pred, average="macro")
# **Fix for IsolationForest: Use decision_function instead of predict_proba**
if model_choice == "Isolation Forest":
roc_auc = roc_auc_score(y_test, model.decision_function(X_test))
else:
roc_auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
# π Display Performance Metrics
st.subheader("π Model Performance")
st.write(f"**Model:** {model_choice}")
st.write(f"**Accuracy:** {accuracy:.4f}")
st.write(f"**Precision:** {precision:.4f}")
st.write(f"**Recall:** {recall:.4f}")
st.write(f"**F1 Score:** {f1:.4f}")
st.write(f"**ROC-AUC:** {roc_auc:.4f}")
# π Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
fig, ax = plt.subplots(figsize=(5, 3))
sns.heatmap(cm, annot=True, fmt='d', cmap="Blues", ax=ax)
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title(f"Confusion Matrix - {model_choice}")
st.pyplot(fig)
# π Fraud Risk Mapping
if st.checkbox("Show Fraud Risk Map"):
st.subheader("π Fraud Risk Mapping (Geospatial Analysis)")
# Filter Fraud Cases
fraud_data = df[df['Fraud'] == 1]
# Convert to GeoDataFrame
geometry = [Point(xy) for xy in zip(fraud_data['Longitude'], fraud_data['Latitude'])]
gdf = gpd.GeoDataFrame(fraud_data, geometry=geometry)
# **Fix for GeoPandas: Use a manually downloaded map**
sa_map = gpd.read_file("zaf_adm_sadb_ocha_20201109_SHP/zaf_admbnda_adm1_sadb_ocha_20201109.shp") # Download from Natural Earth
# Plot High-Risk Fraud Areas
fig, ax = plt.subplots(figsize=(8, 6))
sa_map.plot(ax=ax, color='lightgrey')
gdf.plot(ax=ax, marker='o', color='red', markersize=5)
plt.title("π High-Risk Fraud Areas in South Africa")
st.pyplot(fig)
# π Fraudulent Consumption Trend Analysis
if st.checkbox("Show Consumption Trend Analysis"):
st.subheader("π Fraudulent vs Normal Consumption Trend")
fig, ax = plt.subplots(figsize=(10, 5))
sns.lineplot(data=df[df['Fraud'] == 1], x="Hour", y="Energy Consumption (kWh)", ci=None, label="Fraudulent", ax=ax)
sns.lineplot(data=df[df['Fraud'] == 0], x="Hour", y="Energy Consumption (kWh)", ci=None, label="Normal", ax=ax)
plt.xlabel("Hour of the Day")
plt.ylabel("Energy Consumption (kWh)")
plt.title("π Energy Consumption Trends")
plt.legend()
st.pyplot(fig)
# π Model Comparison
if st.checkbox("Show Model Performance Comparison"):
st.subheader("π Model Performance Comparison")
# Compare Models
performance = []
for name, model in models.items():
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average="macro")
recall = recall_score(y_test, y_pred, average="macro")
f1 = f1_score(y_test, y_pred, average="macro")
# **Fix for IsolationForest: Use decision_function**
if name == "Isolation Forest":
roc_auc = roc_auc_score(y_test, model.decision_function(X_test))
else:
roc_auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
performance.append({
"Model": name,
"Accuracy": accuracy,
"Precision": precision,
"Recall": recall,
"F1-Score": f1,
"ROC-AUC": roc_auc
})
# Convert to DataFrame
performance_df = pd.DataFrame(performance)
st.write(performance_df)
# π Plot Performance Trends
fig, ax = plt.subplots(figsize=(10, 5))
for metric in ["Accuracy", "Precision", "Recall", "F1-Score", "ROC-AUC"]:
ax.plot(performance_df["Model"], performance_df[metric], marker='o', label=metric)
plt.xlabel("Model")
plt.ylabel("Score")
plt.title("π Model Performance Trends")
plt.legend()
plt.xticks(rotation=15)
plt.grid()
st.pyplot(fig)
# Footer
st.sidebar.markdown("π¨βπ» **Authors:** Simanga Mchunu, Nkosinathi Nhlapo, Kagiso Leboka, Bongani Baloyi")
st.sidebar.markdown("π
**Project:** Smart Meter Fraud Detection")