trohith89 commited on
Commit
c54b001
·
verified ·
1 Parent(s): 7f044dd

Update pages/3_EDA_and_Feature_Engineering.py

Browse files
Files changed (1) hide show
  1. pages/3_EDA_and_Feature_Engineering.py +223 -223
pages/3_EDA_and_Feature_Engineering.py CHANGED
@@ -181,226 +181,226 @@ if df is not None:
181
  - 1: Purchase --> 56.6%''')
182
 
183
  st.write("## **Bivariate and MultivariateAnalysis**")
184
- st.write("### Ploting Each Variable Against Target Variable")
185
- import matplotlib.patches as mpatches
186
- # Exclude the specific columns for histogram plotting
187
- columns_to_exclude = ['ProductID', 'age_bins', 'ProductPriceBucket', 'PurchaseFrequency', 'CustomerAge', 'PurchaseIntent']
188
- df_filtered = df.drop(columns=columns_to_exclude)
189
-
190
- # Set up the subplots grid: 1 row and 3 columns
191
- fig, axs = plt.subplots(1, 3, figsize=(18, 6))
192
- axs = axs.flatten() # Flatten the 2D array of axes to easily index
193
-
194
- # Color palettes to cycle through for each subplot
195
- color_palettes = ['Blues', 'viridis', 'coolwarm']
196
-
197
- # Loop through the first 3 columns and plot each histogram
198
- for i, col in enumerate(df_filtered.columns[:3]): # First 3 columns
199
- axs[i].set_title(f"{col} Distribution")
200
- axs[i].set_xlabel(col)
201
- axs[i].set_ylabel("Count")
202
-
203
- # Create histogram with 'PurchaseIntent' as the hue for color-coding
204
- sns.histplot(data=df, x=col, hue='PurchaseIntent', multiple="stack",
205
- palette=color_palettes[i % len(color_palettes)], bins=20, ax=axs[i])
206
-
207
- # Manually create the custom legend with labels
208
- handles = [mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[0], label="PurchaseIntent = 0"),
209
- mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[1], label="PurchaseIntent = 1")]
210
- axs[i].legend(handles=handles, title="Purchase Intent", loc='upper right')
211
-
212
- # Adjust layout and render plot in Streamlit
213
- plt.tight_layout()
214
- st.pyplot(fig)
215
-
216
- st.markdown('''**Insights :**
217
-
218
- - **Category Distribution** : The distribution of products across categories (Smartphones, Smart Watches, Tablets, Laptops, Headphones) is relatively uniform, with slight variations. This suggests a diverse product catalog.
219
- Purchase Intent: It appears that "Purchase Intent = 1" (meaning intent to purchase is present) is fairly consistent across categories, with no category showing a significantly higher or lower proportion of purchase intent.
220
-
221
- - **Brand Distribution** :The distribution of brands is less uniform. "Other Brands" seems to have the highest representation, followed by Samsung, Sony, HP, and then Apple.
222
- Purchase Intent: Observe if there are any notable differences in the proportion of "Purchase Intent = 1" between different brands. This could indicate if certain brands are more desirable or effective at converting interest into purchases.
223
-
224
- - **Price Distribution**: The price histogram indicates a wide range of product prices, likely spanning from near 0 to 3000 (assuming the x-axis represents price).
225
- Purchase Intent: Examine how purchase intent varies across different price points. Are there price ranges where purchase intent is higher or lower? This could reveal price sensitivity or the effectiveness of pricing strategies.''')
226
-
227
- # Set up the subplots grid: 1 row and 3 columns
228
- fig, axs = plt.subplots(1, 3, figsize=(18, 6))
229
- axs = axs.flatten() # Flatten the 2D array of axes to easily index
230
-
231
- # Color palettes to cycle through for each subplot
232
- color_palettes = ['magma', 'cividis', 'inferno']
233
-
234
- # Loop through the next 3 columns and plot each histogram
235
- for i, col in enumerate(df_filtered.columns[3:6]): # Next 3 columns
236
- axs[i].set_title(f"{col} Distribution")
237
- axs[i].set_xlabel(col)
238
- axs[i].set_ylabel("Count")
239
-
240
- # Create histogram with 'PurchaseIntent' as the hue for color-coding
241
- sns.histplot(data=df, x=col, hue='PurchaseIntent', multiple="stack",
242
- palette=color_palettes[i % len(color_palettes)], bins=20, ax=axs[i])
243
-
244
- # Manually create the custom legend with labels
245
- handles = [mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[0], label="PurchaseIntent = 0"),
246
- mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[1], label="PurchaseIntent = 1")]
247
- axs[i].legend(handles=handles, title="Purchase Intent", loc='upper right')
248
-
249
- # Adjust layout and render plot in Streamlit
250
- plt.tight_layout() # Correct method name here
251
- st.pyplot(fig)
252
-
253
- st.markdown('''**Insights :**
254
-
255
- - **Uneven Distribution:** There's a significant difference in the number of customers in each gender category. The category represented by '1' (likely female) has a much higher count than the category represented by '0' (likely male). This indicates that your customer base is skewed towards one gender.
256
- - **Purchase Intent:** The proportion of "Purchase Intent = 1" (meaning the intent to purchase is present) appears to be relatively similar between the two genders. The purple bars (Purchase Intent = 1) are proportionally similar in height for both genders.''')
257
-
258
- st.write("### PRODUCT VS BRANDS")
259
- # Create the plot
260
- fig, ax = plt.subplots(figsize=(12, 8))
261
- sns.histplot(data=df, x='Category', hue='Brand', multiple="stack", palette='rocket', bins=20, ax=ax)
262
-
263
- # Add title and labels
264
- ax.set_title("Product Category and Brand Distribution")
265
- ax.set_xlabel("Product Category")
266
- ax.set_ylabel("Count")
267
-
268
- # Manually create legend if it's not generated
269
- handles, labels = ax.get_legend_handles_labels()
270
-
271
- if not labels:
272
- # Ensure unique brand names appear in the legend
273
- unique_brands = df['Brand'].unique()
274
- palette = sns.color_palette('rocket', len(unique_brands))
275
-
276
- # Create legend handles with reversed color order
277
- handles = [plt.Rectangle((0, 0), 1, 1, color=palette[i]) for i in range(len(unique_brands))]
278
-
279
- # Reverse both handles and labels
280
- handles = handles[::-1]
281
- labels = unique_brands[::-1]
282
-
283
- # Apply reversed legend
284
- ax.legend(handles, labels, title="Product Brand", loc='upper right')
285
-
286
- # Adjust layout and render plot in Streamlit
287
- plt.tight_layout()
288
- st.pyplot(fig)
289
- st.markdown("#### All products are from all the brands present in the dataset.")
290
-
291
- st.write("### PRODUCT VS PRICE")
292
- # Create the histogram plot
293
- fig = px.histogram(df, x='Price', color='Category', title="Product Category and Price Distribution",
294
- color_discrete_sequence=px.colors.sequential.Blackbody)
295
-
296
- # Render the plot in Streamlit
297
- st.plotly_chart(fig)
298
- st.markdown('''**Insights :**
299
- - **Price Range:** The x-axis shows a price range likely from 0 to 3000 (units unspecified, but presumably currency).
300
-
301
- - **Category Distribution Across Price:** The stacked areas illustrate how the proportion of each product category varies across the price spectrum.
302
- 1. .**Smartphones (Black):** Appear to be concentrated in the lower to mid-price ranges, with fewer smartphones at the higher price points.
303
- 2. **Smart Watches (Red):** Show a relatively consistent distribution across the price range, though perhaps slightly more prevalent in the mid-range.
304
- 3. **Tablets (Yellow):** Seem to be more common in the mid-price range, with fewer tablets at both the low and high ends.
305
- 4. **Laptops (White):** Tend to dominate the higher price ranges, as expected. There are very few laptops at the lower price points.
306
- 5. **Headphones (Light Blue):** Have a fairly even distribution across the price range, although there's a slight increase in the mid-to-high price range.
307
-
308
- - **Overlapping Areas:** The stacked nature of the chart allows you to see the total number of products at each price point by summing the heights of the stacked areas.''')
309
-
310
- st.write("### BRANDS VS PRICE")
311
- # Create the histogram plot
312
- fig = px.histogram(df, x='Price', color='Brand', title="Product Category and Price Distribution",
313
- color_discrete_sequence=px.colors.sequential.Plasma)
314
-
315
- # Render the plot in Streamlit
316
- st.plotly_chart(fig)
317
- st.markdown('''**Insights :**
318
-
319
- - **Price Range:** The x-axis covers a price range, likely from 0 to 3000 (currency unspecified).
320
-
321
- - **Brand Distribution Across Price:** The stacked bars show the count of products from each brand within different price intervals.
322
-
323
- 1. **Apple (Darkest Purple/Blue):** Appears to have a significant presence across most of the price range, though perhaps slightly less so at the very lowest end.
324
-
325
- 2. **HP (Medium Purple):** Also has a fairly broad distribution across price points, with a noticeable presence in the mid-range.
326
-
327
- 3. **Sony (Lighter Purple):** Seems to be more concentrated in the mid-to-high price range.
328
- 4. **Samsung (Lightest Purple/Pink):** Has a presence across the price range, but seems to be more prominent in the mid-range and slightly lower-mid range.
329
- 5. **Other Brands (Darkest Purple/Blue, sometimes hard to distinguish from Apple):** This category seems to have a substantial presence across all price points, particularly at the lower end. This suggests a large variety of less prominent brands catering to different price segments.
330
- - **Overlapping Areas/Stacked Bars:** The stacked nature of the chart shows the total number of products at each price point by adding up the heights of the different brand segments.''')
331
-
332
- st.write("### AGE vs PRODUCT CATEGORY and PRICE")
333
- # Create the histogram plot
334
- fig = px.histogram(df, x='CustomerAge', y='Price', color='Category', title="Customer Age and Product Category Distribution")
335
-
336
- # Render the plot in Streamlit
337
- st.plotly_chart(fig)
338
- st.markdown('''**Insights :**
339
-
340
- - **Category Distribution Across Age:** The stacked bars illustrate how the proportion of each product category contributes to the total orders within each age group.
341
-
342
- 1. **Smartphones (Blue):** Appear to have a fairly consistent demand across all age groups, forming the base of most stacks. This suggests smartphones are a popular category regardless of age.
343
- 2. **Smart Watches (Red):** Show a notable presence, with potentially higher contributions in the younger and middle-age groups. This could indicate that smartwatches are more popular among these demographics.
344
- 3. **Tablets (Green):** Have a somewhat consistent demand across age groups, similar to smartphones but with a smaller overall contribution to total orders.
345
- 4. **Laptops (Purple):** Appear to have a strong presence across all age groups, often rivaling or exceeding smartphones in contribution. This suggests laptops are essential for a wide range of ages.
346
- 5. **Headphones (Orange):** Show a relatively consistent pattern across age groups, with a moderate contribution to total orders.
347
-
348
- - Insights:
349
-
350
- 1. **Age-Related Preferences:** While some categories like smartphones and laptops seem to have broad appeal, there are hints of age-related preferences. For example, smartwatches might be more popular among younger demographics.
351
- 2. **Dominant Categories:** Smartphones and laptops appear to be the most consistently popular categories across most age groups.''')
352
-
353
- st.write("### HEATMAP | CORRELATION MATRIX")
354
- st.write("#### Label Encoding")
355
- import pandas as pd
356
- import seaborn as sns
357
- import matplotlib.pyplot as plt
358
- from sklearn.preprocessing import LabelEncoder
359
- import streamlit as st
360
-
361
- # Create a LabelEncoder instance
362
- label_encoder = LabelEncoder()
363
-
364
- # Fit and transform the 'ProductBrand' column
365
- df['Brand'] = label_encoder.fit_transform(df['Brand'])
366
-
367
- # Get the mapping of labels to numeric values for 'Brand' column
368
- brand_mapping = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
369
-
370
- # Display the mapping in Streamlit
371
- st.write(f"Label Encoding Mapping for Brand: {brand_mapping}")
372
-
373
- # Fit and transform the 'Category' column
374
- df['Category'] = label_encoder.fit_transform(df['Category'])
375
-
376
- # Get the mapping of labels to numeric values for 'Category' column
377
- category_mapping = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
378
-
379
- # Display the mapping in Streamlit
380
- st.write(f"Label Encoding Mapping for Category: {category_mapping}")
381
-
382
- # Calculate correlation matrix (only for numeric columns)
383
- df_numeric = df.select_dtypes(include=['number'])
384
-
385
- # Calculate correlation matrix
386
- corr = df_numeric.corr()
387
-
388
- # Create the heatmap plot
389
- fig, ax = plt.subplots(figsize=(20, 10))
390
- sns.heatmap(corr, annot=True, ax=ax, cmap='coolwarm')
391
-
392
- # Add title
393
- ax.set_title('Correlation Matrix')
394
-
395
- # Adjust layout and render plot in Streamlit
396
- plt.tight_layout()
397
- st.pyplot(fig)
398
-
399
- # Display insights in Streamlit
400
- st.markdown('''**Insights:**
401
-
402
- Correlation is a statistical measure that indicates the strength and direction of the linear relationship between two variables. The correlation coefficient ranges from -1 to 1, with the following interpretations:
403
-
404
- - -1: Perfect negative correlation (as one variable increases, the other decreases)
405
- - 0: No correlation (the variables are independent)
406
- - 1: Perfect positive correlation (as one variable increases, the other increases)''')
 
181
  - 1: Purchase --> 56.6%''')
182
 
183
  st.write("## **Bivariate and MultivariateAnalysis**")
184
+ st.write("### Ploting Each Variable Against Target Variable")
185
+ import matplotlib.patches as mpatches
186
+ # Exclude the specific columns for histogram plotting
187
+ columns_to_exclude = ['ProductID', 'age_bins', 'ProductPriceBucket', 'PurchaseFrequency', 'CustomerAge', 'PurchaseIntent']
188
+ df_filtered = df.drop(columns=columns_to_exclude)
189
+
190
+ # Set up the subplots grid: 1 row and 3 columns
191
+ fig, axs = plt.subplots(1, 3, figsize=(18, 6))
192
+ axs = axs.flatten() # Flatten the 2D array of axes to easily index
193
+
194
+ # Color palettes to cycle through for each subplot
195
+ color_palettes = ['Blues', 'viridis', 'coolwarm']
196
+
197
+ # Loop through the first 3 columns and plot each histogram
198
+ for i, col in enumerate(df_filtered.columns[:3]): # First 3 columns
199
+ axs[i].set_title(f"{col} Distribution")
200
+ axs[i].set_xlabel(col)
201
+ axs[i].set_ylabel("Count")
202
+
203
+ # Create histogram with 'PurchaseIntent' as the hue for color-coding
204
+ sns.histplot(data=df, x=col, hue='PurchaseIntent', multiple="stack",
205
+ palette=color_palettes[i % len(color_palettes)], bins=20, ax=axs[i])
206
+
207
+ # Manually create the custom legend with labels
208
+ handles = [mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[0], label="PurchaseIntent = 0"),
209
+ mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[1], label="PurchaseIntent = 1")]
210
+ axs[i].legend(handles=handles, title="Purchase Intent", loc='upper right')
211
+
212
+ # Adjust layout and render plot in Streamlit
213
+ plt.tight_layout()
214
+ st.pyplot(fig)
215
+
216
+ st.markdown('''**Insights :**
217
+
218
+ - **Category Distribution** : The distribution of products across categories (Smartphones, Smart Watches, Tablets, Laptops, Headphones) is relatively uniform, with slight variations. This suggests a diverse product catalog.
219
+ Purchase Intent: It appears that "Purchase Intent = 1" (meaning intent to purchase is present) is fairly consistent across categories, with no category showing a significantly higher or lower proportion of purchase intent.
220
+
221
+ - **Brand Distribution** :The distribution of brands is less uniform. "Other Brands" seems to have the highest representation, followed by Samsung, Sony, HP, and then Apple.
222
+ Purchase Intent: Observe if there are any notable differences in the proportion of "Purchase Intent = 1" between different brands. This could indicate if certain brands are more desirable or effective at converting interest into purchases.
223
+
224
+ - **Price Distribution**: The price histogram indicates a wide range of product prices, likely spanning from near 0 to 3000 (assuming the x-axis represents price).
225
+ Purchase Intent: Examine how purchase intent varies across different price points. Are there price ranges where purchase intent is higher or lower? This could reveal price sensitivity or the effectiveness of pricing strategies.''')
226
+
227
+ # Set up the subplots grid: 1 row and 3 columns
228
+ fig, axs = plt.subplots(1, 3, figsize=(18, 6))
229
+ axs = axs.flatten() # Flatten the 2D array of axes to easily index
230
+
231
+ # Color palettes to cycle through for each subplot
232
+ color_palettes = ['magma', 'cividis', 'inferno']
233
+
234
+ # Loop through the next 3 columns and plot each histogram
235
+ for i, col in enumerate(df_filtered.columns[3:6]): # Next 3 columns
236
+ axs[i].set_title(f"{col} Distribution")
237
+ axs[i].set_xlabel(col)
238
+ axs[i].set_ylabel("Count")
239
+
240
+ # Create histogram with 'PurchaseIntent' as the hue for color-coding
241
+ sns.histplot(data=df, x=col, hue='PurchaseIntent', multiple="stack",
242
+ palette=color_palettes[i % len(color_palettes)], bins=20, ax=axs[i])
243
+
244
+ # Manually create the custom legend with labels
245
+ handles = [mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[0], label="PurchaseIntent = 0"),
246
+ mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[1], label="PurchaseIntent = 1")]
247
+ axs[i].legend(handles=handles, title="Purchase Intent", loc='upper right')
248
+
249
+ # Adjust layout and render plot in Streamlit
250
+ plt.tight_layout() # Correct method name here
251
+ st.pyplot(fig)
252
+
253
+ st.markdown('''**Insights :**
254
+
255
+ - **Uneven Distribution:** There's a significant difference in the number of customers in each gender category. The category represented by '1' (likely female) has a much higher count than the category represented by '0' (likely male). This indicates that your customer base is skewed towards one gender.
256
+ - **Purchase Intent:** The proportion of "Purchase Intent = 1" (meaning the intent to purchase is present) appears to be relatively similar between the two genders. The purple bars (Purchase Intent = 1) are proportionally similar in height for both genders.''')
257
+
258
+ st.write("### PRODUCT VS BRANDS")
259
+ # Create the plot
260
+ fig, ax = plt.subplots(figsize=(12, 8))
261
+ sns.histplot(data=df, x='Category', hue='Brand', multiple="stack", palette='rocket', bins=20, ax=ax)
262
+
263
+ # Add title and labels
264
+ ax.set_title("Product Category and Brand Distribution")
265
+ ax.set_xlabel("Product Category")
266
+ ax.set_ylabel("Count")
267
+
268
+ # Manually create legend if it's not generated
269
+ handles, labels = ax.get_legend_handles_labels()
270
+
271
+ if not labels:
272
+ # Ensure unique brand names appear in the legend
273
+ unique_brands = df['Brand'].unique()
274
+ palette = sns.color_palette('rocket', len(unique_brands))
275
+
276
+ # Create legend handles with reversed color order
277
+ handles = [plt.Rectangle((0, 0), 1, 1, color=palette[i]) for i in range(len(unique_brands))]
278
+
279
+ # Reverse both handles and labels
280
+ handles = handles[::-1]
281
+ labels = unique_brands[::-1]
282
+
283
+ # Apply reversed legend
284
+ ax.legend(handles, labels, title="Product Brand", loc='upper right')
285
+
286
+ # Adjust layout and render plot in Streamlit
287
+ plt.tight_layout()
288
+ st.pyplot(fig)
289
+ st.markdown("#### All products are from all the brands present in the dataset.")
290
+
291
+ st.write("### PRODUCT VS PRICE")
292
+ # Create the histogram plot
293
+ fig = px.histogram(df, x='Price', color='Category', title="Product Category and Price Distribution",
294
+ color_discrete_sequence=px.colors.sequential.Blackbody)
295
+
296
+ # Render the plot in Streamlit
297
+ st.plotly_chart(fig)
298
+ st.markdown('''**Insights :**
299
+ - **Price Range:** The x-axis shows a price range likely from 0 to 3000 (units unspecified, but presumably currency).
300
+
301
+ - **Category Distribution Across Price:** The stacked areas illustrate how the proportion of each product category varies across the price spectrum.
302
+ 1. .**Smartphones (Black):** Appear to be concentrated in the lower to mid-price ranges, with fewer smartphones at the higher price points.
303
+ 2. **Smart Watches (Red):** Show a relatively consistent distribution across the price range, though perhaps slightly more prevalent in the mid-range.
304
+ 3. **Tablets (Yellow):** Seem to be more common in the mid-price range, with fewer tablets at both the low and high ends.
305
+ 4. **Laptops (White):** Tend to dominate the higher price ranges, as expected. There are very few laptops at the lower price points.
306
+ 5. **Headphones (Light Blue):** Have a fairly even distribution across the price range, although there's a slight increase in the mid-to-high price range.
307
+
308
+ - **Overlapping Areas:** The stacked nature of the chart allows you to see the total number of products at each price point by summing the heights of the stacked areas.''')
309
+
310
+ st.write("### BRANDS VS PRICE")
311
+ # Create the histogram plot
312
+ fig = px.histogram(df, x='Price', color='Brand', title="Product Category and Price Distribution",
313
+ color_discrete_sequence=px.colors.sequential.Plasma)
314
+
315
+ # Render the plot in Streamlit
316
+ st.plotly_chart(fig)
317
+ st.markdown('''**Insights :**
318
+
319
+ - **Price Range:** The x-axis covers a price range, likely from 0 to 3000 (currency unspecified).
320
+
321
+ - **Brand Distribution Across Price:** The stacked bars show the count of products from each brand within different price intervals.
322
+
323
+ 1. **Apple (Darkest Purple/Blue):** Appears to have a significant presence across most of the price range, though perhaps slightly less so at the very lowest end.
324
+
325
+ 2. **HP (Medium Purple):** Also has a fairly broad distribution across price points, with a noticeable presence in the mid-range.
326
+
327
+ 3. **Sony (Lighter Purple):** Seems to be more concentrated in the mid-to-high price range.
328
+ 4. **Samsung (Lightest Purple/Pink):** Has a presence across the price range, but seems to be more prominent in the mid-range and slightly lower-mid range.
329
+ 5. **Other Brands (Darkest Purple/Blue, sometimes hard to distinguish from Apple):** This category seems to have a substantial presence across all price points, particularly at the lower end. This suggests a large variety of less prominent brands catering to different price segments.
330
+ - **Overlapping Areas/Stacked Bars:** The stacked nature of the chart shows the total number of products at each price point by adding up the heights of the different brand segments.''')
331
+
332
+ st.write("### AGE vs PRODUCT CATEGORY and PRICE")
333
+ # Create the histogram plot
334
+ fig = px.histogram(df, x='CustomerAge', y='Price', color='Category', title="Customer Age and Product Category Distribution")
335
+
336
+ # Render the plot in Streamlit
337
+ st.plotly_chart(fig)
338
+ st.markdown('''**Insights :**
339
+
340
+ - **Category Distribution Across Age:** The stacked bars illustrate how the proportion of each product category contributes to the total orders within each age group.
341
+
342
+ 1. **Smartphones (Blue):** Appear to have a fairly consistent demand across all age groups, forming the base of most stacks. This suggests smartphones are a popular category regardless of age.
343
+ 2. **Smart Watches (Red):** Show a notable presence, with potentially higher contributions in the younger and middle-age groups. This could indicate that smartwatches are more popular among these demographics.
344
+ 3. **Tablets (Green):** Have a somewhat consistent demand across age groups, similar to smartphones but with a smaller overall contribution to total orders.
345
+ 4. **Laptops (Purple):** Appear to have a strong presence across all age groups, often rivaling or exceeding smartphones in contribution. This suggests laptops are essential for a wide range of ages.
346
+ 5. **Headphones (Orange):** Show a relatively consistent pattern across age groups, with a moderate contribution to total orders.
347
+
348
+ - Insights:
349
+
350
+ 1. **Age-Related Preferences:** While some categories like smartphones and laptops seem to have broad appeal, there are hints of age-related preferences. For example, smartwatches might be more popular among younger demographics.
351
+ 2. **Dominant Categories:** Smartphones and laptops appear to be the most consistently popular categories across most age groups.''')
352
+
353
+ st.write("### HEATMAP | CORRELATION MATRIX")
354
+ st.write("#### Label Encoding")
355
+ import pandas as pd
356
+ import seaborn as sns
357
+ import matplotlib.pyplot as plt
358
+ from sklearn.preprocessing import LabelEncoder
359
+ import streamlit as st
360
+
361
+ # Create a LabelEncoder instance
362
+ label_encoder = LabelEncoder()
363
+
364
+ # Fit and transform the 'ProductBrand' column
365
+ df['Brand'] = label_encoder.fit_transform(df['Brand'])
366
+
367
+ # Get the mapping of labels to numeric values for 'Brand' column
368
+ brand_mapping = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
369
+
370
+ # Display the mapping in Streamlit
371
+ st.write(f"Label Encoding Mapping for Brand: {brand_mapping}")
372
+
373
+ # Fit and transform the 'Category' column
374
+ df['Category'] = label_encoder.fit_transform(df['Category'])
375
+
376
+ # Get the mapping of labels to numeric values for 'Category' column
377
+ category_mapping = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
378
+
379
+ # Display the mapping in Streamlit
380
+ st.write(f"Label Encoding Mapping for Category: {category_mapping}")
381
+
382
+ # Calculate correlation matrix (only for numeric columns)
383
+ df_numeric = df.select_dtypes(include=['number'])
384
+
385
+ # Calculate correlation matrix
386
+ corr = df_numeric.corr()
387
+
388
+ # Create the heatmap plot
389
+ fig, ax = plt.subplots(figsize=(20, 10))
390
+ sns.heatmap(corr, annot=True, ax=ax, cmap='coolwarm')
391
+
392
+ # Add title
393
+ ax.set_title('Correlation Matrix')
394
+
395
+ # Adjust layout and render plot in Streamlit
396
+ plt.tight_layout()
397
+ st.pyplot(fig)
398
+
399
+ # Display insights in Streamlit
400
+ st.markdown('''**Insights:**
401
+
402
+ Correlation is a statistical measure that indicates the strength and direction of the linear relationship between two variables. The correlation coefficient ranges from -1 to 1, with the following interpretations:
403
+
404
+ - -1: Perfect negative correlation (as one variable increases, the other decreases)
405
+ - 0: No correlation (the variables are independent)
406
+ - 1: Perfect positive correlation (as one variable increases, the other increases)''')