trohith89 commited on
Commit
6d1dd5d
·
verified ·
1 Parent(s): bc63c23

Update pages/3_EDA_and_Feature_Engineering.py

Browse files
Files changed (1) hide show
  1. pages/3_EDA_and_Feature_Engineering.py +380 -44
pages/3_EDA_and_Feature_Engineering.py CHANGED
@@ -26,9 +26,10 @@ if 'df' in st.session_state:
26
 
27
  # Univariate Analysis
28
  st.write("### Univariate Analysis")
 
29
 
30
  # Product Category Distribution
31
- st.write("#### Product Category Distribution")
32
  fig, ax = plt.subplots(figsize=(10, 6))
33
  sns.countplot(x='Category', data=df, palette='viridis', ax=ax)
34
  ax.set_title("Product Category Distribution")
@@ -36,72 +37,407 @@ if 'df' in st.session_state:
36
  ax.set_ylabel("Count")
37
  plt.xticks(rotation=45)
38
  st.pyplot(fig)
 
 
 
 
 
 
39
 
40
  # Product Price Distribution
41
- st.write("#### Product Price Distribution")
42
  fig, ax = plt.subplots(figsize=(10, 6))
43
- sns.histplot(df['Price'], kde=True, color='orange', ax=ax)
44
- ax.set_title("Product Price Distribution")
45
- ax.set_xlabel("Product Price")
46
  ax.set_ylabel("Count")
 
47
  st.pyplot(fig)
 
 
 
 
 
48
 
49
  # Bivariate Analysis: Price vs Category
50
- st.write("### Price vs Category")
51
- fig, ax = plt.subplots(figsize=(12, 8))
52
- sns.boxplot(x='Category', y='Price', data=df, palette='mako', ax=ax)
53
- ax.set_title("Product Price by Category")
54
- ax.set_xlabel("Category")
55
- ax.set_ylabel("Price")
56
- plt.xticks(rotation=45)
57
  st.pyplot(fig)
 
 
58
 
59
- # Feature Engineering
60
- st.write("### Feature Engineering")
 
61
 
62
- # Binning Product Price
63
- st.write("#### Product Price Binning")
64
- df['PriceBucket'] = pd.cut(df['Price'], bins=[100, 500, 1000, 1500, 2000, 3000],
65
- labels=['Very Low', 'Low', 'Medium', 'High', 'Very High'])
 
 
 
 
 
 
 
66
  fig, ax = plt.subplots(figsize=(10, 6))
67
- sns.countplot(x='PriceBucket', data=df, palette='icefire', ax=ax)
68
- ax.set_title("Product Price Buckets")
69
  ax.set_xlabel("Price Bucket")
70
  ax.set_ylabel("Count")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  st.pyplot(fig)
72
 
73
- # Encoding Categorical Features
74
- st.write("#### Encoding Categorical Features")
75
- le = LabelEncoder()
76
- df['Category'] = le.fit_transform(df['Category'])
77
- df['Brand'] = le.fit_transform(df['Brand'])
78
- st.write("Label Encoding Applied on 'Category' and 'Brand'.")
79
 
80
- # Polynomial Features for Numerical Columns
81
- st.write("#### Polynomial Feature Engineering")
82
- numeric_columns = df.select_dtypes(include=['int64', 'float64']).columns
83
- poly = PolynomialFeatures(degree=2, include_bias=False)
84
- poly_features = poly.fit_transform(df[numeric_columns])
85
- poly_df = pd.DataFrame(poly_features, columns=poly.get_feature_names_out(numeric_columns))
86
 
87
- st.write("Polynomial Features Created:")
88
- st.dataframe(poly_df.head())
89
 
90
- # Correlation Heatmap
91
- # Correlation Heatmap
92
- st.write("### Correlation Matrix")
 
 
 
 
 
 
 
 
 
93
 
94
- # Select only numerical columns
95
- numerical_df = df.select_dtypes(include=['int64', 'float64'])
 
96
 
97
- # Compute the correlation matrix
98
- corr = numerical_df.corr()
 
 
99
 
100
- # Plot the heatmap
 
 
 
 
 
 
 
 
 
 
101
  fig, ax = plt.subplots(figsize=(12, 8))
102
- sns.heatmap(corr, annot=True, cmap='coolwarm', ax=ax)
103
- ax.set_title("Correlation Matrix")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  st.pyplot(fig)
105
 
 
 
 
 
 
 
 
106
  else:
107
  st.error("No dataset found. Please upload a dataset on the main page first.")
 
26
 
27
  # Univariate Analysis
28
  st.write("### Univariate Analysis")
29
+
30
 
31
  # Product Category Distribution
32
+ st.write("### PRODUCT CATEGORY")
33
  fig, ax = plt.subplots(figsize=(10, 6))
34
  sns.countplot(x='Category', data=df, palette='viridis', ax=ax)
35
  ax.set_title("Product Category Distribution")
 
37
  ax.set_ylabel("Count")
38
  plt.xticks(rotation=45)
39
  st.pyplot(fig)
40
+ st.markdown('''**Insights :**
41
+ - We've 5 Product Categories:
42
+ 1. Smart Phones & Laptops are the most highest and similar in frequency,
43
+ 2. Followed by Smart Watches,
44
+ 3. Tablets and Headphones are little less in frequency overall.''')
45
+
46
 
47
  # Product Price Distribution
48
+ st.write("### BRANDS")
49
  fig, ax = plt.subplots(figsize=(10, 6))
50
+ sns.countplot(x='Brand', data=df, palette='cubehelix', ax=ax)
51
+ ax.set_title("Product Brand Distribution")
52
+ ax.set_xlabel("Product Brand")
53
  ax.set_ylabel("Count")
54
+ plt.xticks(rotation=45)
55
  st.pyplot(fig)
56
+ st.markdown('''**Insights :**
57
+ - We've 5 Brand Categories:
58
+ 1. Samsung & HP are the most highest and similar in frequency,
59
+ 2. Followed by Sony, Aplle and other brands.''')
60
+
61
 
62
  # Bivariate Analysis: Price vs Category
63
+ st.write("### Price Distribution")
64
+ fig, ax = plt.subplots(figsize=(10, 6))
65
+ sns.histplot(df['Price'], kde=True, color='orange', ax=ax) # 'orange' mimics Agsunset
66
+ ax.set_title("Product Price Distribution")
67
+ ax.set_xlabel("Product Price")
68
+ ax.set_ylabel("Count")
 
69
  st.pyplot(fig)
70
+ st.markdown('''**Insights :**
71
+ - **Wide Range:** The products span a considerable price range (from near 0 to 3000).
72
 
73
+ - **Concentration:** There's a noticeable concentration of products priced between roughly 200 and 2500.
74
+
75
+ - **Roughly Uniform:** The distribution appears somewhat uniform with some peaks and valleys. This indicates there isn't a single dominant price point, and products are fairly evenly distributed across the price range (with some exceptions).''')
76
 
77
+
78
+ # Feature Engineering
79
+ st.write("### PRODUCT PRICE BINING)
80
+ # Binning Product Prices into Buckets
81
+ df['ProductPriceBucket'] = pd.cut(
82
+ df['Price'],
83
+ bins=[100, 500, 1000, 1500, 2000, 3000],
84
+ labels=['Very Low', 'Low', 'Medium', 'High', 'Very High']
85
+ )
86
+
87
+ # Plotting Product Price Buckets
88
  fig, ax = plt.subplots(figsize=(10, 6))
89
+ sns.countplot(x='ProductPriceBucket', data=df, palette='icefire', ax=ax)
90
+ ax.set_title("Product Price Bucket Distribution")
91
  ax.set_xlabel("Price Bucket")
92
  ax.set_ylabel("Count")
93
+ plt.xticks(rotation=45)
94
+ st.pyplot(fig)
95
+ st.markdown('''**Insights :**
96
+
97
+ - **Uneven Distribution:** The most striking observation is that the distribution is not even across the price buckets. This suggests that certain price ranges are more common or more popular than others.
98
+
99
+ - **"Very High" Dominance:** The "Very High" price bucket has the highest concentration of products. This indicates that a significant portion of your products fall into this top-tier price range. This could mean you have a focus on premium items, or it might reflect a pricing strategy that emphasizes higher-priced goods.
100
+
101
+ - **Lower Representation in "Very Low":** The "Very Low" bucket has the fewest products. This could indicate a limited number of budget or entry-level items in your product catalog.
102
+
103
+ - **Similar Counts in "Low", "Medium", and "High":** The counts for "Low", "Medium", and "High" appear relatively similar. This suggests a moderate and somewhat consistent distribution of products across these mid-range price points.''')
104
+
105
+ st.write("### AGE DISTRIBUTION")
106
+ st.write("##### Age Binning")
107
+ # Binning Customer Ages into Groups
108
+ df['CustomerAgeGroup'] = pd.qcut(df['CustomerAge'], q=4, labels=['Young', 'Middle-aged', 'Mature', 'Senior'])
109
+
110
+ # Plotting Age Group Distribution and Age Histogram
111
+ fig, axs = plt.subplots(1, 2, figsize=(15, 6))
112
+
113
+ # Age Group Distribution
114
+ sns.countplot(x='CustomerAgeGroup', data=df, ax=axs[0], palette='magma')
115
+ axs[0].set_title("Customer Age Group Distribution")
116
+ axs[0].set_xlabel("Customer Age Group")
117
+ axs[0].set_ylabel("Count")
118
+
119
+ # Age Histogram
120
+ sns.histplot(df['CustomerAge'], kde=True, ax=axs[1], color='teal')
121
+ axs[1].set_title("Customer Age Distribution")
122
+ axs[1].set_xlabel("Customer Age")
123
+ axs[1].set_ylabel("Count")
124
+
125
+ # Adjust layout and render plots
126
+ plt.tight_layout()
127
+ st.pyplot(fig)
128
+ st.markdown('''**Insights :**
129
+ - **Relatively Even Distribution:** The most prominent feature is the relatively even distribution of customers across all four age groups. The bars are of similar height, indicating that each age group represents a comparable portion of the customer base.
130
+
131
+ - **Slight Variation:** While generally even, there are slight variations:
132
+ - **Young:** Appears to have a marginally higher count than the others.
133
+ - **Senior:** Has a slightly lower count compared to "Young" but is very close to "Mature" and "Middle-aged."
134
+ - **No Dominant Age Group:** There's no single dominant age group that significantly outweighs the others. This suggests a broad appeal across different age demographics.''')
135
+
136
+ st.write("### GENDER DISTRIBUTION")
137
+ # Plot the pie chart
138
+ df['CustomerGender'].value_counts().plot(kind='pie',
139
+ colors=['lightblue', 'lightpink'],
140
+ autopct='%1.1f%%', # Shows percentage on pie chart
141
+ startangle=90, # Start the pie chart at a specific angle
142
+ wedgeprops={'edgecolor': 'black'}, # Adds borders to the slices
143
+ ax=axs)
144
+
145
+ # Add title and legend
146
+ axs.set_title("Customer Gender Distribution")
147
+ axs.legend(labels=['Female', 'Male'], loc='upper left', fontsize=12, title="Customer Gender")
148
+
149
+ # Adjust layout and render plot in Streamlit
150
+ plt.tight_layout()
151
+ st.pyplot(fig)
152
+ st.markdwon('''**Insights :** Almost same proportion for both the genders
153
+ - Male (49.1%)
154
+ - Female (50.9%)''')
155
+ st.write("### PURCHASE FREQUENCY DISTRIBUTION")
156
+ # Create a figure and axis for the plot
157
+ fig, axs = plt.subplots(1, 1, figsize=(10, 6))
158
+
159
+ # Plot the histogram with KDE
160
+ sns.histplot(df['PurchaseFrequency'], kde=True, color='purple', bins=30, ax=axs)
161
+
162
+ # Add title and labels
163
+ axs.set_title("Purchase Frequency Distribution")
164
+ axs.set_xlabel("Purchase Frequency")
165
+ axs.set_ylabel("Count")
166
+
167
+ # Adjust layout and render plot in Streamlit
168
+ plt.tight_layout()
169
+ st.pyplot(fig)
170
+ st.write("#### The Range is 1 - 19")
171
+
172
+ st.write("### CUSTOMER SATISFACTION DISTRIBUTION")
173
+ # Create a figure and axis for the plot
174
+ fig, axs = plt.subplots(1, 1, figsize=(10, 6))
175
+
176
+ # Plot the histogram with KDE using the specified color
177
+ sns.histplot(df['CustomerSatisfaction'], kde=True, color=sns.color_palette("crest", n_colors=1)[0], ax=axs)
178
+
179
+ # Add title and labels
180
+ axs.set_title("Customer Satisfaction Distribution")
181
+ axs.set_xlabel("Customer Satisfaction")
182
+ axs.set_ylabel("Count")
183
+
184
+ # Adjust layout and render plot in Streamlit
185
+ plt.tight_layout()
186
+ st.pyplot(fig)
187
+
188
+ st.markdown('''**Insights :**
189
+
190
+ - **Multimodal Distribution:** The most striking aspect is the multimodal nature of the distribution. There are distinct peaks around the integer values (1, 2, 3, 4, 5). This suggests that customers tend to provide whole-number ratings rather than choosing intermediate values.
191
+
192
+ - **Relatively Uniform Peaks:** The peaks seem relatively uniform in height, indicating a somewhat even distribution of satisfaction levels across the rating scale. This might imply that there isn't a strong concentration of extremely satisfied or dissatisfied customers.''')
193
+
194
+
195
+ st.write("### CUSTOMER SATISFACTION DISTRIBUTION")
196
+ # Create a figure and axis for the plot
197
+ fig, axs = plt.subplots(1, 1, figsize=(8, 6))
198
+
199
+ # Plot the pie chart
200
+ wedges, texts, autotexts = axs.pie(purchase_intent_counts,
201
+ labels=purchase_intent_counts.index,
202
+ colors=sns.color_palette("coolwarm", n_colors=len(purchase_intent_counts)),
203
+ autopct='%1.1f%%',
204
+ startangle=90,
205
+ wedgeprops={'edgecolor': 'black'})
206
+
207
+ # Add legend and title
208
+ axs.legend(wedges, purchase_intent_counts.index, title="Purchase Intent", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
209
+ axs.set_title("Purchase Intent Distribution")
210
+
211
+ # Adjust layout and render plot in Streamlit
212
+ plt.tight_layout()
213
+ st.pyplot(fig)
214
+
215
+ st.markdown('''**Insights :**
216
+ - We've 0 and 1 which means Not Purchase and Purchase.
217
+
218
+ - A binary classification problem.
219
+
220
+ - 0: Not Purchase --> 43.4%
221
+
222
+ - 1: Purchase --> 56.6%''')
223
+
224
+ st.write("## **Bivariate and MultivariateAnalysis**")
225
+ st.write("### Ploting Each Variable Against Target Variable")
226
+
227
+ # Exclude the specific columns for histogram plotting
228
+ columns_to_exclude = ['ProductID', 'age_bins', 'ProductPriceBucket', 'PurchaseFrequency', 'CustomerAge', 'PurchaseIntent']
229
+ df_filtered = df.drop(columns=columns_to_exclude)
230
+
231
+ # Set up the subplots grid: 1 row and 3 columns
232
+ fig, axs = plt.subplots(1, 3, figsize=(18, 6))
233
+ axs = axs.flatten() # Flatten the 2D array of axes to easily index
234
+
235
+ # Color palettes to cycle through for each subplot
236
+ color_palettes = ['Blues', 'viridis', 'coolwarm']
237
+
238
+ # Loop through the first 3 columns and plot each histogram
239
+ for i, col in enumerate(df_filtered.columns[:3]): # First 3 columns
240
+ axs[i].set_title(f"{col} Distribution")
241
+ axs[i].set_xlabel(col)
242
+ axs[i].set_ylabel("Count")
243
+
244
+ # Create histogram with 'PurchaseIntent' as the hue for color-coding
245
+ sns.histplot(data=df, x=col, hue='PurchaseIntent', multiple="stack",
246
+ palette=color_palettes[i % len(color_palettes)], bins=20, ax=axs[i])
247
+
248
+ # Manually create the custom legend with labels
249
+ handles = [mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[0], label="PurchaseIntent = 0"),
250
+ mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[1], label="PurchaseIntent = 1")]
251
+ axs[i].legend(handles=handles, title="Purchase Intent", loc='upper right')
252
+
253
+ # Adjust layout and render plot in Streamlit
254
+ plt.tight_layout()
255
  st.pyplot(fig)
256
 
257
+ st.markdown('''**Insights :**
258
+
259
+ - **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.
260
+ 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.
 
 
261
 
262
+ - **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.
263
+ 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.
 
 
 
 
264
 
265
+ - **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).
266
+ 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.''')
267
 
268
+ # Set up the subplots grid: 1 row and 3 columns
269
+ fig, axs = plt.subplots(1, 3, figsize=(18, 6))
270
+ axs = axs.flatten() # Flatten the 2D array of axes to easily index
271
+
272
+ # Color palettes to cycle through for each subplot
273
+ color_palettes = ['magma', 'cividis', 'inferno']
274
+
275
+ # Loop through the next 3 columns and plot each histogram
276
+ for i, col in enumerate(df_filtered.columns[3:6]): # Next 3 columns
277
+ axs[i].set_title(f"{col} Distribution")
278
+ axs[i].set_xlabel(col)
279
+ axs[i].set_ylabel("Count")
280
 
281
+ # Create histogram with 'PurchaseIntent' as the hue for color-coding
282
+ sns.histplot(data=df, x=col, hue='PurchaseIntent', multiple="stack",
283
+ palette=color_palettes[i % len(color_palettes)], bins=20, ax=axs[i])
284
 
285
+ # Manually create the custom legend with labels
286
+ handles = [mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[0], label="PurchaseIntent = 0"),
287
+ mpatches.Patch(color=sns.color_palette(color_palettes[i % len(color_palettes)])[1], label="PurchaseIntent = 1")]
288
+ axs[i].legend(handles=handles, title="Purchase Intent", loc='upper right')
289
 
290
+ # Adjust layout and render plot in Streamlit
291
+ plt.tight_layout() # Correct method name here
292
+ st.pyplot(fig)
293
+
294
+ st.amrkdown('''**Insights :**
295
+
296
+ - **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.
297
+ - **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.''')
298
+
299
+ st.write("### PRODUCT VS BRANDS")
300
+ # Create the plot
301
  fig, ax = plt.subplots(figsize=(12, 8))
302
+ sns.histplot(data=df, x='Category', hue='Brand', multiple="stack", palette='rocket', bins=20, ax=ax)
303
+
304
+ # Add title and labels
305
+ ax.set_title("Product Category and Brand Distribution")
306
+ ax.set_xlabel("Product Category")
307
+ ax.set_ylabel("Count")
308
+
309
+ # Manually create legend if it's not generated
310
+ handles, labels = ax.get_legend_handles_labels()
311
+
312
+ if not labels:
313
+ # Ensure unique brand names appear in the legend
314
+ unique_brands = df['Brand'].unique()
315
+ palette = sns.color_palette('rocket', len(unique_brands))
316
+
317
+ # Create legend handles with reversed color order
318
+ handles = [plt.Rectangle((0, 0), 1, 1, color=palette[i]) for i in range(len(unique_brands))]
319
+
320
+ # Reverse both handles and labels
321
+ handles = handles[::-1]
322
+ labels = unique_brands[::-1]
323
+
324
+ # Apply reversed legend
325
+ ax.legend(handles, labels, title="Product Brand", loc='upper right')
326
+
327
+ # Adjust layout and render plot in Streamlit
328
+ plt.tight_layout()
329
+ st.pyplot(fig)
330
+ st.markdown("#### All products are from all the brands present in the dataset.")
331
+
332
+ st.write("### PRODUCT VS PRICE")
333
+ # Create the histogram plot
334
+ fig = px.histogram(df, x='Price', color='Category', title="Product Category and Price Distribution",
335
+ color_discrete_sequence=px.colors.sequential.Blackbody)
336
+
337
+ # Render the plot in Streamlit
338
+ st.plotly_chart(fig)
339
+ st.markdown('''**Insights :**
340
+ - **Price Range:** The x-axis shows a price range likely from 0 to 3000 (units unspecified, but presumably currency).
341
+
342
+ - **Category Distribution Across Price:** The stacked areas illustrate how the proportion of each product category varies across the price spectrum.
343
+ 1. .**Smartphones (Black):** Appear to be concentrated in the lower to mid-price ranges, with fewer smartphones at the higher price points.
344
+ 2. **Smart Watches (Red):** Show a relatively consistent distribution across the price range, though perhaps slightly more prevalent in the mid-range.
345
+ 3. **Tablets (Yellow):** Seem to be more common in the mid-price range, with fewer tablets at both the low and high ends.
346
+ 4. **Laptops (White):** Tend to dominate the higher price ranges, as expected. There are very few laptops at the lower price points.
347
+ 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.
348
+
349
+ - **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.''')
350
+
351
+ st.write("### BRANDS VS PRICE")
352
+ # Create the histogram plot
353
+ fig = px.histogram(df, x='Price', color='Brand', title="Product Category and Price Distribution",
354
+ color_discrete_sequence=px.colors.sequential.Plasma)
355
+
356
+ # Render the plot in Streamlit
357
+ st.plotly_chart(fig)
358
+ st.markdown('''**Insights :**
359
+
360
+ - **Price Range:** The x-axis covers a price range, likely from 0 to 3000 (currency unspecified).
361
+
362
+ - **Brand Distribution Across Price:** The stacked bars show the count of products from each brand within different price intervals.
363
+
364
+ 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.
365
+
366
+ 2. **HP (Medium Purple):** Also has a fairly broad distribution across price points, with a noticeable presence in the mid-range.
367
+
368
+ 3. **Sony (Lighter Purple):** Seems to be more concentrated in the mid-to-high price range.
369
+ 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.
370
+ 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.
371
+ - **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.''')
372
+
373
+ st.write("### AGE vs PRODUCT CATEGORY and PRICE")
374
+ # Create the histogram plot
375
+ fig = px.histogram(df, x='CustomerAge', y='Price', color='Category', title="Customer Age and Product Category Distribution")
376
+
377
+ # Render the plot in Streamlit
378
+ st.plotly_chart(fig)
379
+ st.markdown('''**Insights :**
380
+
381
+ - **Category Distribution Across Age:** The stacked bars illustrate how the proportion of each product category contributes to the total orders within each age group.
382
+
383
+ 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.
384
+ 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.
385
+ 3. **Tablets (Green):** Have a somewhat consistent demand across age groups, similar to smartphones but with a smaller overall contribution to total orders.
386
+ 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.
387
+ 5. **Headphones (Orange):** Show a relatively consistent pattern across age groups, with a moderate contribution to total orders.
388
+
389
+ - Insights:
390
+
391
+ 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.
392
+ 2. **Dominant Categories:** Smartphones and laptops appear to be the most consistently popular categories across most age groups.''')
393
+
394
+ st.write("### HEATMAP | CORRELATION MATRIX")
395
+ st.write("#### Label Encoding")
396
+ import pandas as pd
397
+ from sklearn.preprocessing import LabelEncoder
398
+ import streamlit as st
399
+
400
+ # Create a LabelEncoder instance
401
+ label_encoder = LabelEncoder()
402
+
403
+ # Fit and transform the 'ProductBrand' column
404
+ df['Brand'] = label_encoder.fit_transform(df['Brand'])
405
+
406
+ # Get the mapping of labels to numeric values for 'Brand' column
407
+ brand_mapping = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
408
+
409
+ # Display the mapping in Streamlit
410
+ st.write(f"Label Encoding Mapping for Brand: {brand_mapping}")
411
+
412
+ # Fit and transform the 'Category' column
413
+ df['Category'] = label_encoder.fit_transform(df['Category'])
414
+
415
+ # Get the mapping of labels to numeric values for 'Category' column
416
+ category_mapping = dict(zip(label_encoder.classes_, label_encoder.transform(label_encoder.classes_)))
417
+
418
+ # Display the mapping in Streamlit
419
+ st.write(f"Label Encoding Mapping for Category: {category_mapping}")
420
+
421
+ # Calculate correlation matrix
422
+ corr = df.corr()
423
+
424
+ # Create the heatmap plot
425
+ fig, ax = plt.subplots(figsize=(20, 10))
426
+ sns.heatmap(corr, annot=True, ax=ax)
427
+
428
+ # Add title
429
+ ax.set_title('Correlation Matrix')
430
+
431
+ # Adjust layout and render plot in Streamlit
432
+ plt.tight_layout()
433
  st.pyplot(fig)
434
 
435
+ st.markdown('''**Insights :**
436
+
437
+ 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:
438
+
439
+ - -1: Perfect negative correlation (as one variable increases, the other decreases)
440
+ - 0: No correlation (the variables are independent)
441
+ - 1: Perfect positive correlation (as one variable increases, the other increases)''')
442
  else:
443
  st.error("No dataset found. Please upload a dataset on the main page first.")