ZainabEman commited on
Commit
2c9cab5
·
verified ·
1 Parent(s): 167832d

Upload 11 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ Actual[[:space:]]vs.[[:space:]]Predicted[[:space:]]scatter[[:space:]]plot..png filter=lfs diff=lfs merge=lfs -text
37
+ electricity[[:space:]]demand[[:space:]]overtime.png filter=lfs diff=lfs merge=lfs -text
38
+ Engineered[[:space:]]Feature.png filter=lfs diff=lfs merge=lfs -text
Actual Electricity Demand scatter plot.png ADDED
Actual vs. Predicted scatter plot..png ADDED

Git LFS Details

  • SHA256: da4e3fed37fc98f299e418148a85101e8d064d2d5bdefa97820a3c63c21022e0
  • Pointer size: 131 Bytes
  • Size of remote file: 107 kB
BoxPlot of temprature.png ADDED
Density plot of temprature.png ADDED
Engineered Feature.png ADDED

Git LFS Details

  • SHA256: d6450ab94058a6150ed349f026349741464565ec08558f9727e21f6e19881529
  • Pointer size: 131 Bytes
  • Size of remote file: 109 kB
Heatmap.png ADDED
Z-score Method & Z-score Outliers.png ADDED
app.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ from statsmodels.tsa.stattools import adfuller
7
+ from scipy import stats
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.linear_model import LinearRegression
10
+ from sklearn.metrics import mean_squared_error, r2_score
11
+ from sklearn.impute import SimpleImputer
12
+
13
+ # Set Streamlit page configuration
14
+ st.set_page_config(page_title="Electricity Demand Prediction Project", layout="wide")
15
+
16
+ # ------------------------------------------------------------------------------
17
+ # Helper Function to Make DataFrame Displayable
18
+ # ------------------------------------------------------------------------------
19
+ def make_displayable(df):
20
+ df_display = df.copy()
21
+ # Convert datetime columns to string to avoid Arrow conversion issues
22
+ for col in df_display.columns:
23
+ if pd.api.types.is_datetime64_any_dtype(df_display[col]):
24
+ df_display[col] = df_display[col].astype(str)
25
+ return df_display
26
+
27
+ # ------------------------------------------------------------------------------
28
+ # Load Data (simulate a processed DataFrame for demonstration)
29
+ # ------------------------------------------------------------------------------
30
+ @st.cache_data
31
+ def load_data():
32
+ # Create a date range and simulate data (using 'h' for hourly frequency)
33
+ dates = pd.date_range(start="2024-01-01", periods=100, freq='h')
34
+ data = {
35
+ "date": dates,
36
+ "temperature_2m": np.random.uniform(low=-10, high=25, size=len(dates)),
37
+ "hour": dates.hour,
38
+ "day": dates.day,
39
+ "month": dates.month,
40
+ "year": dates.year,
41
+ "day_of_week": dates.dayofweek,
42
+ "is_weekend": [1 if x >= 5 else 0 for x in dates.dayofweek],
43
+ "is_holiday": np.zeros(len(dates)), # For demo, no holidays
44
+ }
45
+ df = pd.DataFrame(data)
46
+ # Create a scaled temperature column (simulate standardized values)
47
+ df["temperature_2m_scaled"] = (df["temperature_2m"] - df["temperature_2m"].mean()) / df["temperature_2m"].std()
48
+ # For regression target, assume electricity_demand equals temperature_2m (for demo)
49
+ df["electricity_demand"] = df["temperature_2m"]
50
+ return df
51
+
52
+ df = load_data()
53
+
54
+ # ------------------------------------------------------------------------------
55
+ # Sidebar Navigation
56
+ # ------------------------------------------------------------------------------
57
+ st.sidebar.title("Navigation")
58
+ section = st.sidebar.radio("Select Section:",
59
+ ["Overview",
60
+ "Data Cleaning & Consistency",
61
+ "Type Conversions & Feature Engineering",
62
+ "Exploratory Data Analysis",
63
+ "Outlier Detection & Handling",
64
+ "Regression Modeling"])
65
+
66
+ # ------------------------------------------------------------------------------
67
+ # Updated Data Loading and Helper Functions
68
+ # ------------------------------------------------------------------------------
69
+ @st.cache_data
70
+ def load_data():
71
+ # Create a date range with 200 hourly periods to cover multiple days
72
+ dates = pd.date_range(start="2024-01-01", periods=200, freq='h')
73
+ data = {
74
+ "date": dates,
75
+ "temperature_2m": np.random.uniform(low=-10, high=25, size=len(dates)),
76
+ "hour": dates.hour,
77
+ "day": dates.day,
78
+ "month": dates.month,
79
+ "year": dates.year,
80
+ "day_of_week": dates.dayofweek,
81
+ "is_weekend": [1 if x >= 5 else 0 for x in dates.dayofweek],
82
+ "is_holiday": np.zeros(len(dates)), # For demo, no holidays
83
+ }
84
+ df = pd.DataFrame(data)
85
+ # Create a scaled temperature column (simulate standardized values)
86
+ df["temperature_2m_scaled"] = (df["temperature_2m"] - df["temperature_2m"].mean()) / df["temperature_2m"].std()
87
+ # For regression target, assume electricity_demand equals temperature_2m (for demo)
88
+ df["electricity_demand"] = df["temperature_2m"]
89
+ return df
90
+
91
+ def make_displayable(df):
92
+ df_display = df.copy()
93
+ # Convert datetime columns to formatted strings to display full date and time
94
+ for col in df_display.columns:
95
+ if pd.api.types.is_datetime64_any_dtype(df_display[col]):
96
+ df_display[col] = df_display[col].dt.strftime("%Y-%m-%d %H:%M:%S")
97
+ return df_display
98
+
99
+ df = load_data()
100
+
101
+ # ------------------------------------------------------------------------------
102
+ # Section 1: Data Loading & Integration
103
+ # ------------------------------------------------------------------------------
104
+ if section == "Overview":
105
+ st.title("Overview")
106
+ st.markdown("""
107
+ ## Data Loading and Integration
108
+
109
+ **Objective:**
110
+ - **Task:** Load and integrate raw electricity demand and weather data.
111
+ - **Data Formats:** CSV and JSON files stored within a ZIP folder.
112
+ - **Execution Environment:** Google Colab.
113
+ - **Tools:** Python libraries (`os`, `glob`, `pandas`).
114
+
115
+ **Steps:**
116
+
117
+ 1. **Upload and Extract Data:**
118
+ - Use Colab's file upload widget to upload the ZIP file containing the data.
119
+ - Unzip the contents to a designated directory (e.g., `/content/data`).
120
+
121
+ 2. **Verify Directory Structure:**
122
+ - Ensure that the files are extracted correctly, including those in subdirectories (for example, a folder named `raw`).
123
+
124
+ 3. **Recursive File Search:**
125
+ - Use a recursive glob search to locate all CSV and JSON files within the target directory and its subdirectories.
126
+
127
+ 4. **Load Data with Error Handling:**
128
+ - Load CSV files using UTF-8 encoding (with fallback to `latin1` if needed).
129
+ - Load JSON files using `pandas.read_json`.
130
+ - Print file names and shapes for verification.
131
+
132
+ 5. **Standardize Column Names and Merge DataFrames:**
133
+ - Convert column names to lowercase, trim extra spaces, and replace spaces with underscores.
134
+ - Concatenate all DataFrames into one unified DataFrame.
135
+
136
+ **Data Loading Outcome:**
137
+ - **Total Records:** 135,263
138
+ - **Total Features:** 6
139
+ - **Columns:** `date`, `temperature_2m`, `response`, `request`, `apiversion`, `exceladdinversion`
140
+
141
+ **Next Steps:**
142
+ The processed data will be further cleaned, transformed, and enriched with additional features in the subsequent sections:
143
+ - **Data Cleaning & Consistency**
144
+ - **Data Type Conversions**
145
+ - **Feature Engineering**
146
+ - **Exploratory Data Analysis (EDA)**
147
+ - **Outlier Detection & Handling**
148
+ - **Regression Modeling**
149
+ """)
150
+ st.write("### DataFrame Overview:")
151
+ st.write("Original DataFrame Shape:", df.shape)
152
+ # Filter out constant columns for a more informative preview
153
+ informative_columns = [col for col in df.columns if df[col].nunique() > 1]
154
+ st.write("Informative Columns (with variability):", informative_columns)
155
+ st.dataframe(make_displayable(df[informative_columns].head()))
156
+ # ------------------------------------------------------------------------------
157
+ # Section 2: Data Cleaning & Consistency
158
+ # ------------------------------------------------------------------------------
159
+ elif section == "Data Cleaning & Consistency":
160
+ st.title("Data Cleaning & Consistency")
161
+ st.write("This section shows how missing values were identified and handled.")
162
+
163
+ # Hardcoded missing value statistics from the markdown file
164
+ data_cleaning_stats = pd.DataFrame({
165
+ "Column": ["date", "temperature_2m", "response", "request", "apiversion", "exceladdinversion"],
166
+ "Missing Count": [7680, 7835, 129778, 133069, 127584, 127584],
167
+ "Missing Percentage": ["5.68%", "5.79%", "95.94%", "98.38%", "94.32%", "94.32%"]
168
+ })
169
+
170
+ st.write("### Missing Value Summary:")
171
+ st.dataframe(data_cleaning_stats)
172
+
173
+ # Create a bar chart showing the missing counts for each column
174
+ fig, ax = plt.subplots(figsize=(10, 6))
175
+ sns.barplot(x="Column", y="Missing Count", data=data_cleaning_stats, palette="viridis", ax=ax)
176
+ ax.set_title("Missing Value Counts per Feature")
177
+ ax.set_xlabel("Feature")
178
+ ax.set_ylabel("Missing Count")
179
+ # Add data labels on the bars
180
+ for index, row in data_cleaning_stats.iterrows():
181
+ ax.text(index, row["Missing Count"], f'{row["Missing Count"]}', color="black", ha="center", va="bottom")
182
+ st.pyplot(fig)
183
+
184
+ # ------------------------------------------------------------------------------
185
+ # Section 3: Data Type Conversions & Feature Engineering
186
+ # ------------------------------------------------------------------------------
187
+
188
+ elif section == "Type Conversions & Feature Engineering":
189
+ st.title("Data Cleaning, Data Type Conversions & Feature Engineering")
190
+ st.markdown("""
191
+ ## 1. Convert 'date' Column to Datetime
192
+
193
+ We start by ensuring that the `date` column is correctly formatted as a datetime object.
194
+ Any invalid entries are coerced to `NaT` to handle errors gracefully.
195
+
196
+ ## 2. Extract Temporal Features
197
+
198
+ We extract useful time-based features from the `date` column:
199
+ - **hour:** Extracted hour from the timestamp.
200
+ - **day:** Extracted day of the month.
201
+ - **month:** Extracted month.
202
+ - **year:** Extracted year.
203
+
204
+ ## 3. Categorizing Seasons
205
+
206
+ To enhance analysis, we categorize the `month` column into four seasons:
207
+ - **Winter:** December, January, February.
208
+ - **Spring:** March, April, May.
209
+ - **Summer:** June, July, August.
210
+ - **Autumn:** September, October, November.
211
+
212
+ A function is defined to map months to their respective seasons. The resulting `season`
213
+ column is then explicitly converted into an ordered categorical type (`Winter → Spring → Summer → Autumn`),
214
+ ensuring proper sorting and comparison in future analyses.
215
+
216
+ ## 4. Ensure Numerical Columns are Correctly Typed
217
+
218
+ We explicitly convert the `temperature_2m` column to a numeric format using `pd.to_numeric()`.
219
+ Any non-numeric values are converted to `NaN` to prevent errors in calculations.
220
+
221
+ ## Data Verification
222
+
223
+ We display a sample of the dataset after all transformations along with the data types.
224
+ """)
225
+
226
+ st.write("### Sample Output After Conversions and Feature Extraction:")
227
+ # Filter to display only informative columns
228
+ informative_columns = [col for col in df.columns if df[col].nunique() > 1]
229
+ st.dataframe(make_displayable(df[informative_columns].head()))
230
+
231
+ st.write("### Data Types:")
232
+ st.write(df[informative_columns].dtypes.astype(str))
233
+
234
+ st.markdown("""
235
+ ## Feature Engineering
236
+
237
+ New features were engineered from the timestamp to enhance our analysis:
238
+ - **Day of Week:** Numeric value (0 = Monday, …, 6 = Sunday)
239
+ - **Is Weekend:** Binary flag indicating weekends.
240
+ - **Is Holiday:** Binary flag (for demo, no holidays).
241
+ - **Normalized Temperature:** Standardized `temperature_2m` values.
242
+ """)
243
+ st.image("Engineered Feature.png", caption="Engineered Feature", use_container_width=True)
244
+
245
+
246
+ # ------------------------------------------------------------------------------
247
+ # Section 5: Exploratory Data Analysis (EDA)
248
+ # ------------------------------------------------------------------------------
249
+ elif section == "Exploratory Data Analysis":
250
+ st.title("Exploratory Data Analysis (EDA)")
251
+
252
+ # Statistical Summary
253
+ st.subheader("Statistical Summary")
254
+ st.code("""=== Statistical Summary ===
255
+ temperature_2m hour day month year
256
+ count 3611.000000 2923.000000 2923.000000 2923.000000 2923.0
257
+ mean 6.933715 11.496408 15.508040 2.520698 2024.0
258
+ std 6.847542 6.928616 8.802778 1.142109 0.0
259
+ min -10.491500 0.000000 1.000000 1.000000 2024.0
260
+ 25% 2.408500 5.000000 8.000000 1.000000 2024.0
261
+ 50% 6.958500 11.000000 15.000000 3.000000 2024.0
262
+ 75% 10.608500 18.000000 23.000000 4.000000 2024.0
263
+ max 25.258501 23.000000 31.000000 5.000000 2024.0
264
+
265
+ day_of_week temperature_2m_scaled
266
+ count 2923.000000 3.611000e+03
267
+ mean 2.959631 9.445043e-17
268
+ std 1.999764 1.000138e+00
269
+ min 0.000000 -2.545093e+00
270
+ 25% 1.000000 -6.609440e-01
271
+ 50% 3.000000 3.620091e-03
272
+ 75% 5.000000 5.367320e-01
273
+ max 6.000000 2.676482e+00
274
+
275
+ Skewness of numerical features:
276
+ temperature_2m 0.196583
277
+ hour 0.001477
278
+ day 0.010766
279
+ month 0.032511
280
+ year 0.000000
281
+ day_of_week 0.031919
282
+ temperature_2m_scaled 0.196583
283
+ dtype: float64
284
+
285
+ Kurtosis of numerical features:
286
+ temperature_2m 0.106266
287
+ hour -1.206587
288
+ day -1.196645
289
+ month -1.277384
290
+ year 0.000000
291
+ day_of_week -1.249512
292
+ temperature_2m_scaled 0.106266
293
+ dtype: float64
294
+ """)
295
+
296
+ # Boxplot
297
+ st.subheader("Boxplot of Temperature")
298
+ st.image("BoxPlot of temprature.png", caption="Boxplot of Temperature", use_container_width=True)
299
+
300
+ # Density Plot
301
+ st.subheader("Density Plot of Temperature")
302
+ st.image("Density plot of temprature.png", caption="Density Plot of Temperature", use_container_width=True)
303
+
304
+ # Electricity Demand Over Time
305
+ st.subheader("Electricity Demand (Temperature) Over Time")
306
+ st.image("electricity demand overtime.png", caption="Electricity Demand (Temperature) Over Time", use_container_width=True)
307
+
308
+ # Correlation Heatmap
309
+ st.subheader("Correlation Heatmap")
310
+ st.image("Heatmap.png", caption="Correlation Heatmap", use_container_width=True)
311
+
312
+ # Histogram and Density Plot
313
+ st.subheader("Histogram and Density Plot of Temperature")
314
+ st.image("histogram and density plot of temprature.png", caption="Histogram & Density Plot of Temperature", use_container_width=True)
315
+
316
+ # Correlation Matrix
317
+ st.subheader("Correlation Matrix")
318
+ st.code("""=== Correlation Matrix ===
319
+ temperature_2m hour day month year
320
+ temperature_2m 1.000000 0.120903 -0.020858 0.602388 NaN
321
+ hour 0.120903 1.000000 -0.000753 -0.008889 NaN
322
+ day -0.020858 -0.000753 1.000000 -0.047324 NaN
323
+ month 0.602388 -0.008889 -0.047324 1.000000 NaN
324
+ year NaN NaN NaN NaN NaN
325
+ day_of_week 0.046259 -0.002950 0.025253 0.006659 NaN
326
+ temperature_2m_scaled 1.000000 0.120903 -0.020858 0.602388 NaN
327
+
328
+ day_of_week temperature_2m_scaled
329
+ temperature_2m 0.046259 1.000000
330
+ hour -0.002950 0.120903
331
+ day 0.025253 -0.020858
332
+ month 0.006659 0.602388
333
+ year NaN NaN
334
+ day_of_week 1.000000 0.046259
335
+ temperature_2m_scaled 0.046259 1.000000
336
+ """)
337
+
338
+ # Augmented Dickey-Fuller Test
339
+ st.subheader("Augmented Dickey-Fuller Test")
340
+ st.code("""=== Augmented Dickey-Fuller Test ===
341
+ ADF Statistic: -5.039413
342
+ p-value: 0.000019
343
+ Critical Values:
344
+ 1%: -3.432
345
+ 5%: -2.862
346
+ 10%: -2.567
347
+ """)
348
+
349
+
350
+ # ------------------------------------------------------------------------------
351
+ # Section 6: Outlier Detection & Handling
352
+ # ------------------------------------------------------------------------------
353
+ elif section == "Outlier Detection & Handling":
354
+ st.title("Outlier Detection & Handling")
355
+ st.write("This section demonstrates two outlier detection methods: IQR-based and Z-score based methods.")
356
+
357
+ st.write("### IQR-based Outlier Detection:")
358
+
359
+ st.image("Z-score Method & Z-score Outliers.png", caption="Z-score Outlier Detection", use_container_width=True)
360
+
361
+ # ------------------------------------------------------------------------------
362
+ # Section 7: Regression Modeling
363
+ # ------------------------------------------------------------------------------
364
+ elif section == "Regression Modeling":
365
+ st.title("Regression Modeling")
366
+ st.write("This section builds and evaluates a regression model to predict electricity demand.")
367
+
368
+ st.write("### Feature Selection:")
369
+ st.write("Predictors: `hour`, `day`, `month`, `day_of_week`, `is_weekend`, `is_holiday`")
370
+ st.write("Target: `electricity_demand` (equals `temperature_2m` for this demo)")
371
+
372
+
373
+ st.write("### Actual vs. Predicted Electricity Demand:")
374
+ st.image("Actual Electricity Demand scatter plot.png", caption="Actual vs. Predicted Scatter Plot", use_container_width=True)
375
+
376
+ st.write("### Residual Analysis:")
377
+ st.image("Actual vs. Predicted scatter plot..png", caption="Residual Analysis (Histogram & Residuals vs. Predicted)", use_container_width=True)
378
+
379
+ st.write("### Prediction Graphs Description:")
380
+ st.markdown("""
381
+ - **Actual vs. Predicted Scatter Plot:**
382
+ This plot shows the relationship between the actual electricity demand and the model's predictions. A red dashed line indicates the ideal scenario where the predictions perfectly match the actual values. Any deviation from this line highlights prediction errors.
383
+
384
+ - **Residual Analysis Plot:**
385
+ The residual analysis includes a histogram of the residuals (the differences between the actual and predicted values) and a scatter plot of residuals versus predicted values. Ideally, residuals should be randomly distributed around zero, indicating that the model errors are random and that the model is well-fitted.
386
+ """)
387
+
388
+
389
+ # ------------------------------------------------------------------------------
390
+ # Footer / Project Information (Interactive)
391
+ # ------------------------------------------------------------------------------
392
+ st.sidebar.markdown("---")
393
+ st.sidebar.markdown("""
394
+ ### Project Links
395
+
396
+ [<img src="https://cdn-icons-png.flaticon.com/512/25/25231.png" width="25" style="vertical-align: middle; margin-right: 5px;"> GitHub Repository](https://github.com/ZainabEman/DataScience_Course/tree/main/Assignment02)
397
+
398
+ [<img src="https://cdn-icons-png.flaticon.com/512/174/174857.png" width="25" style="vertical-align: middle; margin-right: 5px;"> LinkedIn](https://www.linkedin.com/in/zainab-eman18/)
399
+
400
+ [<img src="https://cdn-icons-png.flaticon.com/512/2111/2111505.png" width="25" style="vertical-align: middle; margin-right: 5px;"> Medium Blog](https://medium.com/@zainabeman976/from-raw-data-to-clean-insights-a-fun-dive-into-electricity-demand-analysis-a1dd275be9cc)
401
+
402
+ [<img src="https://cdn-icons-png.flaticon.com/512/5968/5968672.png" width="25" style="vertical-align: middle; margin-right: 5px;"> Documentation](https://github.com/ZainabEman/DataScience_Course/blob/main/Assignment02/Assignment02.md)
403
+
404
+
405
+ **Assignment 02: DataScience Course**
406
+ **Course Instructor:** [Dr.Sahar Ajmal](https://www.linkedin.com/in/sahar-ajmal-47439924b/)
407
+ """, unsafe_allow_html=True)
408
+
electricity demand overtime.png ADDED

Git LFS Details

  • SHA256: f7f73323e7683ab9d358554bfcd89c4b8a69c1a74eea7feb8318bd20f717f46d
  • Pointer size: 131 Bytes
  • Size of remote file: 102 kB
density plot of temprature.png RENAMED
File without changes
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ pandas
3
+ numpy
4
+ matplotlib
5
+ seaborn
6
+ statsmodels
7
+ scipy
8
+ scikit-learn