trohith89 commited on
Commit
b01e258
·
verified ·
1 Parent(s): 3dc0dec

Update pages/3_EDA_and_Feature_Engineering.py

Browse files
Files changed (1) hide show
  1. pages/3_EDA_and_Feature_Engineering.py +126 -139
pages/3_EDA_and_Feature_Engineering.py CHANGED
@@ -2,8 +2,6 @@ import streamlit as st
2
  import pandas as pd
3
  import seaborn as sns
4
  import matplotlib.pyplot as plt
5
- import matplotlib.patches as mpatches
6
- import plotly.express as px
7
  from sklearn.preprocessing import LabelEncoder
8
 
9
  st.title("Exploratory Data Analysis (EDA)")
@@ -24,170 +22,159 @@ if 'df' in st.session_state:
24
 
25
  st.markdown("Complete EDA + Feature Engineering")
26
  st.markdown("## **Univariate Analysis**")
 
27
  st.markdown("### PRODUCT CATEGORY")
28
- plt.figure(figsize=(10, 6))
29
- sns.countplot(x='Category', data=df, palette='viridis')
30
- plt.title("Product Category Distribution")
31
- plt.xlabel("Product Category")
32
- plt.ylabel("Count")
33
- plt.xticks(rotation=45)
34
- plt.show()
35
- st.markdown('''**Insights :**
36
- - We've 5 Product Categories:
37
- 1. Smart Phones & Laptops are the most highest and similar in frequency,
38
- 2. Followed by Smart Watches,
39
- 3. Tablets and Headphones are little less in frequency overall.''')
40
-
 
41
  st.markdown("### BRANDS")
42
- plt.figure(figsize=(10, 6))
43
- sns.countplot(x='Brand', data=df, palette='cubehelix')
44
- plt.title("Product Brand Distribution")
45
- plt.xlabel("Product Brand")
46
- plt.ylabel("Count")
47
- plt.xticks(rotation=45)
48
- plt.show()
49
- st.markdown('''**Insights :**
50
- - We've 5 Brand Categories:
51
- 1. Samsung & HP are the most highest and similar in frequency,
52
- 2. Followed by Sony, Apple, and other brands.''')
53
-
 
54
  st.markdown("### PRICE DISTRIBUTION")
55
- plt.figure(figsize=(10, 6))
56
- sns.histplot(df['Price'], kde=True, color='orange') # 'orange' mimics Agsunset
57
- plt.title("Product Price Distribution")
58
- plt.xlabel("Product Price")
59
- plt.ylabel("Count")
60
- plt.show()
61
- st.markdown('''**Insights :**
62
- - **Wide Range:** The products span a considerable price range (from near 0 to 3000).
63
- - **Concentration:** There's a noticeable concentration of products priced between roughly 200 and 2500.
64
- - **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).''')
65
-
66
- st.markdown("### PRODUCT PRICE BINING")
 
67
  df['ProductPriceBucket'] = pd.cut(df['Price'], bins=[100, 500, 1000, 1500, 2000, 3000], labels=['Very Low', 'Low', 'Medium', 'High', 'Very High'])
68
- plt.figure(figsize=(10, 6))
69
- sns.countplot(x='ProductPriceBucket', data=df, palette='icefire')
70
- plt.title("Product Price Distribution")
71
- plt.xlabel("Product Price Bucket")
72
- plt.ylabel("Count")
73
- plt.xticks(rotation=45)
74
- plt.show()
75
- st.markdown('''**Insights :**
76
- - **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.
77
- - **"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.
78
- - **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.
79
- - **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.''')
80
-
81
- st.markdown("### AGE DISTRIBUTION")
82
- st.markdown("### AGE BINNING")
83
  df['CustomerAgeGroup'] = pd.qcut(df['CustomerAge'], q=4, labels=['Young', 'Middle-aged', 'Mature', 'Senior'])
84
  fig, axs = plt.subplots(1, 2, figsize=(15, 6))
85
-
86
- # First plot with a new palette
87
- sns.countplot(x='CustomerAgeGroup', data=df, ax=axs[0], palette='magma') # 'magma' palette for a different feel
88
  axs[0].set_title("Customer Age Group Distribution")
89
  axs[0].set_xlabel("Customer Age Group")
90
-
91
- # Second plot with a new color
92
- sns.histplot(df['CustomerAge'], kde=True, ax=axs[1], color='teal') # 'teal' for a distinct color in the second plot
93
  axs[1].set_title("Customer Age Distribution")
94
  axs[1].set_xlabel("Customer Age")
95
-
96
- # Adjust layout for better spacing
97
  plt.tight_layout()
98
- plt.show()
99
- st.markdown('''**Insights :**
100
- - **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.
101
- - **Slight Variation:** While generally even, there are slight variations:
102
- - **Young:** Appears to have a marginally higher count than the others.
103
- - **Senior:** Has a slightly lower count compared to "Young" but is very close to "Mature" and "Middle-aged."
104
- - **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.''')
105
 
106
  st.markdown("### GENDER DISTRIBUTION")
107
- print(df['CustomerGender'].value_counts())
108
- plt.figure(figsize=(10, 8))
109
  df['CustomerGender'].value_counts().plot(kind='pie',
110
- colors=['lightblue', 'lightpink'],
111
- autopct='%1.1f%%', # Shows percentage on pie chart
112
- startangle=90, # Start the pie chart at a specific angle
113
- wedgeprops={'edgecolor': 'black'}) # Adds borders to the slices
114
-
115
- plt.title("Customer Gender Distribution")
116
- plt.legend(labels=['Female', 'Male'], loc='upper left', fontsize=12, title="Customer Gender")
117
-
118
- plt.show()
119
- st.markdown('''**Insights :** Almost same proportion for both the genders
120
- - Male (49.1%)
121
- - Female (50.9%)''')
122
 
123
  st.markdown("### PURCHASE FREQUENCY DISTRIBUTION")
124
- plt.figure(figsize=(10, 6))
125
- sns.histplot(df['PurchaseFrequency'], kde=True, color='purple', bins=30)
126
- plt.title("Purchase Frequency Distribution")
127
- plt.xlabel("Purchase Frequency")
128
- plt.ylabel("Count")
129
- plt.show()
130
- st.markdown('''**Insights :**
131
- - The Range is 1 - 19''')
 
 
132
 
133
  st.markdown("### CUSTOMER SATISFACTION DISTRIBUTION")
134
- plt.figure(figsize=(10, 6))
135
- sns.histplot(df['CustomerSatisfaction'], kde=True, color=sns.color_palette("crest", n_colors=1)[0]) # Use the first color from the palette
136
- plt.title("Customer Satisfaction Distribution")
137
- plt.xlabel("Customer Satisfaction")
138
- plt.ylabel("Count")
139
- plt.show()
140
- st.markdown('''**Insights :**
141
- - **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.
142
- - **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.''')
 
 
143
 
144
  st.markdown("### PURCHASE INTENT DISTRIBUTION")
 
145
  purchase_intent_counts = df['PurchaseIntent'].value_counts()
146
- plt.figure(figsize=(8, 6))
147
- wedges, texts, autotexts = plt.pie(purchase_intent_counts,
148
- labels=purchase_intent_counts.index,
149
- colors=sns.color_palette("coolwarm", n_colors=len(purchase_intent_counts)),
150
- autopct='%1.1f%%',
151
- startangle=90,
152
- wedgeprops={'edgecolor': 'black'})
153
- plt.legend(wedges, purchase_intent_counts.index, title="Purchase Intent", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
154
- plt.title("Purchase Intent Distribution")
155
- plt.show()
156
-
157
- st.markdown('''**Insights :**
158
- \n- We've 0 and 1 which means Not Purchase and Purchase.
159
-
160
- \n- A binary classification problem.
161
-
162
- \n- 0: Not Purchase --> 43.4%
163
-
164
- \n- 1: Purchase --> 56.6%''')
165
-
166
- st.markdown("## **Bivariate Analysis**")
167
- st.markdown("### Price vs. Customer Age Group")
168
- plt.figure(figsize=(10, 6))
169
- sns.boxplot(x='CustomerAgeGroup', y='Price', data=df, palette='Set2')
170
- plt.title("Price Distribution by Customer Age Group")
171
- plt.xlabel("Customer Age Group")
172
- plt.ylabel("Price")
173
- plt.show()
174
- st.markdown('''**Insights :**
175
- - **Wide Price Range Across Groups:** All customer age groups seem to span the full range of product prices, indicating that no specific age group is restricted to a certain price range.
176
- - **Higher Price for Mature and Senior:** There appears to be a slightly higher concentration of products with higher prices in the "Mature" and "Senior" age groups.
177
- - **Middle-aged Customers:** Middle-aged customers tend to purchase more moderately priced products.''')
178
-
179
- # Apply Label Encoding for categorical columns
180
  label_encoder = LabelEncoder()
181
  df['CustomerGender'] = label_encoder.fit_transform(df['CustomerGender'])
182
  df['Brand'] = label_encoder.fit_transform(df['Brand'])
183
  df['Category'] = label_encoder.fit_transform(df['Category'])
184
 
185
- st.markdown("### Correlation Heatmap")
186
  corr_matrix = df.corr()
187
- plt.figure(figsize=(12, 8))
188
- sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5)
189
- plt.title("Correlation Heatmap")
190
- plt.show()
 
 
 
 
 
191
 
192
  else:
193
  st.write("Please upload your data.")
 
2
  import pandas as pd
3
  import seaborn as sns
4
  import matplotlib.pyplot as plt
 
 
5
  from sklearn.preprocessing import LabelEncoder
6
 
7
  st.title("Exploratory Data Analysis (EDA)")
 
22
 
23
  st.markdown("Complete EDA + Feature Engineering")
24
  st.markdown("## **Univariate Analysis**")
25
+
26
  st.markdown("### PRODUCT CATEGORY")
27
+ fig, ax = plt.subplots(figsize=(10, 6))
28
+ sns.countplot(x='Category', data=df, palette='viridis', ax=ax)
29
+ ax.set_title("Product Category Distribution")
30
+ ax.set_xlabel("Product Category")
31
+ ax.set_ylabel("Count")
32
+ ax.tick_params(axis='x', rotation=45)
33
+ st.pyplot(fig)
34
+ st.markdown("""
35
+ **Insights:**
36
+ - 5 product categories observed.
37
+ - Highest frequency: Smart Phones and Laptops.
38
+ - Lowest frequency: Tablets and Headphones.
39
+ """)
40
+
41
  st.markdown("### BRANDS")
42
+ fig, ax = plt.subplots(figsize=(10, 6))
43
+ sns.countplot(x='Brand', data=df, palette='cubehelix', ax=ax)
44
+ ax.set_title("Product Brand Distribution")
45
+ ax.set_xlabel("Product Brand")
46
+ ax.set_ylabel("Count")
47
+ ax.tick_params(axis='x', rotation=45)
48
+ st.pyplot(fig)
49
+ st.markdown("""
50
+ **Insights:**
51
+ - Samsung and HP have the highest frequencies.
52
+ - Sony, Apple, and other brands follow behind.
53
+ """)
54
+
55
  st.markdown("### PRICE DISTRIBUTION")
56
+ fig, ax = plt.subplots(figsize=(10, 6))
57
+ sns.histplot(df['Price'], kde=True, color='orange', ax=ax)
58
+ ax.set_title("Product Price Distribution")
59
+ ax.set_xlabel("Product Price")
60
+ ax.set_ylabel("Count")
61
+ st.pyplot(fig)
62
+ st.markdown("""
63
+ **Insights:**
64
+ - Products span a wide price range, from near 0 to 3000.
65
+ - Significant concentration between 200 and 2500.
66
+ """)
67
+
68
+ st.markdown("### PRODUCT PRICE BINNING")
69
  df['ProductPriceBucket'] = pd.cut(df['Price'], bins=[100, 500, 1000, 1500, 2000, 3000], labels=['Very Low', 'Low', 'Medium', 'High', 'Very High'])
70
+ fig, ax = plt.subplots(figsize=(10, 6))
71
+ sns.countplot(x='ProductPriceBucket', data=df, palette='icefire', ax=ax)
72
+ ax.set_title("Product Price Distribution")
73
+ ax.set_xlabel("Product Price Bucket")
74
+ ax.set_ylabel("Count")
75
+ ax.tick_params(axis='x', rotation=45)
76
+ st.pyplot(fig)
77
+ st.markdown("""
78
+ **Insights:**
79
+ - "Very High" price bucket has the highest concentration.
80
+ - Fewer products in the "Very Low" bucket.
81
+ - "Low", "Medium", and "High" have moderate distribution.
82
+ """)
83
+
84
+ st.markdown("### AGE DISTRIBUTION AND BINNING")
85
  df['CustomerAgeGroup'] = pd.qcut(df['CustomerAge'], q=4, labels=['Young', 'Middle-aged', 'Mature', 'Senior'])
86
  fig, axs = plt.subplots(1, 2, figsize=(15, 6))
87
+
88
+ sns.countplot(x='CustomerAgeGroup', data=df, ax=axs[0], palette='magma')
 
89
  axs[0].set_title("Customer Age Group Distribution")
90
  axs[0].set_xlabel("Customer Age Group")
91
+
92
+ sns.histplot(df['CustomerAge'], kde=True, ax=axs[1], color='teal')
 
93
  axs[1].set_title("Customer Age Distribution")
94
  axs[1].set_xlabel("Customer Age")
95
+
 
96
  plt.tight_layout()
97
+ st.pyplot(fig)
98
+ st.markdown("""
99
+ **Insights:**
100
+ - Age groups are relatively evenly distributed.
101
+ - Slightly higher representation for "Young".
102
+ """)
 
103
 
104
  st.markdown("### GENDER DISTRIBUTION")
105
+ fig, ax = plt.subplots(figsize=(10, 8))
 
106
  df['CustomerGender'].value_counts().plot(kind='pie',
107
+ colors=['lightblue', 'lightpink'],
108
+ autopct='%1.1f%%',
109
+ startangle=90,
110
+ wedgeprops={'edgecolor': 'black'},
111
+ ax=ax)
112
+ ax.set_title("Customer Gender Distribution")
113
+ st.pyplot(fig)
114
+ st.markdown("""
115
+ **Insights:**
116
+ - Gender distribution is almost equal.
117
+ - Female: 50.9%, Male: 49.1%.
118
+ """)
119
 
120
  st.markdown("### PURCHASE FREQUENCY DISTRIBUTION")
121
+ fig, ax = plt.subplots(figsize=(10, 6))
122
+ sns.histplot(df['PurchaseFrequency'], kde=True, color='purple', bins=30, ax=ax)
123
+ ax.set_title("Purchase Frequency Distribution")
124
+ ax.set_xlabel("Purchase Frequency")
125
+ ax.set_ylabel("Count")
126
+ st.pyplot(fig)
127
+ st.markdown("""
128
+ **Insights:**
129
+ - Purchase frequencies range from 1 to 19.
130
+ """)
131
 
132
  st.markdown("### CUSTOMER SATISFACTION DISTRIBUTION")
133
+ fig, ax = plt.subplots(figsize=(10, 6))
134
+ sns.histplot(df['CustomerSatisfaction'], kde=True, color=sns.color_palette("crest", n_colors=1)[0], ax=ax)
135
+ ax.set_title("Customer Satisfaction Distribution")
136
+ ax.set_xlabel("Customer Satisfaction")
137
+ ax.set_ylabel("Count")
138
+ st.pyplot(fig)
139
+ st.markdown("""
140
+ **Insights:**
141
+ - Distinct peaks around integer values (1-5).
142
+ - Indicates customers tend to provide whole-number ratings.
143
+ """)
144
 
145
  st.markdown("### PURCHASE INTENT DISTRIBUTION")
146
+ fig, ax = plt.subplots(figsize=(8, 6))
147
  purchase_intent_counts = df['PurchaseIntent'].value_counts()
148
+ ax.pie(purchase_intent_counts,
149
+ labels=purchase_intent_counts.index,
150
+ colors=sns.color_palette("coolwarm", n_colors=len(purchase_intent_counts)),
151
+ autopct='%1.1f%%',
152
+ startangle=90,
153
+ wedgeprops={'edgecolor': 'black'})
154
+ ax.set_title("Purchase Intent Distribution")
155
+ st.pyplot(fig)
156
+ st.markdown("""
157
+ **Insights:**
158
+ - Binary classification problem (0: Not Purchase, 1: Purchase).
159
+ - 56.6% intent to purchase, 43.4% do not.
160
+ """)
161
+
162
+ st.markdown("### CORRELATION HEATMAP")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  label_encoder = LabelEncoder()
164
  df['CustomerGender'] = label_encoder.fit_transform(df['CustomerGender'])
165
  df['Brand'] = label_encoder.fit_transform(df['Brand'])
166
  df['Category'] = label_encoder.fit_transform(df['Category'])
167
 
 
168
  corr_matrix = df.corr()
169
+ fig, ax = plt.subplots(figsize=(12, 8))
170
+ sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5, ax=ax)
171
+ ax.set_title("Correlation Heatmap")
172
+ st.pyplot(fig)
173
+ st.markdown("""
174
+ **Insights:**
175
+ - Strong correlations can be observed between certain variables.
176
+ - Customer Satisfaction and Purchase Intent might have meaningful relationships.
177
+ """)
178
 
179
  else:
180
  st.write("Please upload your data.")