amariayudha commited on
Commit
e500794
Β·
verified Β·
1 Parent(s): df42ea5

Upload predict.py

Browse files
Files changed (1) hide show
  1. predict.py +113 -26
predict.py CHANGED
@@ -4,6 +4,7 @@ import pandas as pd
4
  import torch
5
  import pickle
6
  from transformers import BertTokenizer, BertForSequenceClassification
 
7
 
8
  # Load the tokenizer and model for sentiment analysis
9
  model_dir = './saved_model/' # Update this path if your model is saved elsewhere
@@ -72,27 +73,88 @@ def run():
72
  st.write("## βœπŸ»πŸ“‘ Input Data: ")
73
  st.write("") # Add a blank line for spacing
74
  st.write("This prediction will be done by first analyzing the sentiment from the feedback provided using a BERT model. The sentiment, along with other features, will then be used to classify whether the customer is likely to churn or not churn using an SVM classifier.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  with st.form(key="data"):
76
  col1, col2 = st.columns(2)
77
  with col1:
78
- customer_id = st.text_input("Customer ID", value="CUST001")
79
- tenure = st.number_input("Tenure (in months)", value=12)
80
  with col2:
81
  contract = st.selectbox(
82
- "contract", ['one year', 'month-to-month', 'two year'], index=1
83
  )
84
  payment_method = st.selectbox(
85
- "payment_method", ['credit card', 'electronic check', 'bank transfer', 'mailed check'],index=0
86
  )
87
- monthly_charges = st.number_input("Monthly charges (in $)",step=1.00)
88
- total_charges = st.number_input("Total charges (in $)",step=1.00)
89
  feedback = st.text_area(
90
  "Feedback",
91
- value="As an event planner, I've worked with many florists, but this one stands out from the crowd. For a recent high-profile corporate gala, they provided centerpieces that were nothing short of spectacular. The creativity and artistry in their designs elevated the entire event. They listened carefully to our theme and color scheme, then created arrangements that perfectly captured the essence of the evening. The flowers were fresh, vibrant, and lasted throughout the night, even under bright lights and air conditioning. What impressed me most was their flexibility - when we needed last-minute changes due to a shift in table arrangements, they accommodated without hesitation. Their team was professional, punctual, and a joy to work with. They arrived well before the event to set up and stayed until everything was perfect. The value for money was excellent, considering the high-quality results and the level of service provided. I've already booked them for several upcoming events, including a charity fundraiser and a product launch. It's rare to find a vendor that consistently exceeds expectations, but this florist does just that.",
92
  height=300
93
  )
94
  topic = st.selectbox(
95
- "topic", ['bouquet preferences', 'delivery issues', 'general feedback', 'price complaints', 'delivery quality', 'product quality', 'customer service', 'price appreciation'], index=2
96
  )
97
  # Submit button
98
  submit = st.form_submit_button("πŸ”˜ Predict")
@@ -109,8 +171,17 @@ def run():
109
  "topic": topic
110
  }
111
 
 
 
 
 
112
  # Sentiment Analysis
113
  if feedback.strip() != "":
 
 
 
 
 
114
  st.write("### πŸ“Š Sentiment Analysis")
115
  st.markdown('---')
116
  labels, confidences = predict_sentiment([feedback])
@@ -127,37 +198,53 @@ def run():
127
  data = pd.DataFrame([data])
128
 
129
  # Load customer churn model
 
 
 
 
 
130
  with open('model.pkl', 'rb') as file_1:
131
  classification = pickle.load(file_1)
132
 
133
- # Predict customer churn using the loaded model
 
 
 
 
134
  churn = classification.predict(data)
 
 
 
 
 
135
 
136
  # Display churn prediction result
137
- st.write("### πŸ•΅οΈβ€β™‚οΈ Prediction Results: ")
138
  st.markdown('---')
139
  st.write("") # Add a blank line for spacing
140
 
141
- if churn == False:
142
- st.error("πŸƒ **Customer is Gonna Churn!!**")
143
- st.image('8908ec58-057d-4bfe-9ce5-74322486859a.png')
144
- st.write('') #space
145
- st.write('### πŸ’­ Feedback To Marketing Team: ')
146
- st.error("""
147
- - **The customer** is likely to churn if we don't take immediate steps to improve our **service quality**. Consistently providing subpar service will push them to seek out competitors who can meet their expectations more reliably, resulting in a loss of **long-term loyalty and revenue**.
 
 
 
 
 
148
 
149
- - Without implementing a more effective **retention strategy**, our customers are at high risk of churning. It’s crucial that we personalize our **offerings, provide timely incentives, and enhance customer communication** to keep them **engaged and loyal** to our brand.
150
 
151
- - The recent product changes have led to growing dissatisfaction among customers, increasing the likelihood of churn. To prevent this, we must swiftly **address their concerns, re-evaluate the changes, and ensure that future updates align with customer expectations** to regain their trust.
152
 
153
- - If we fail to address customer concerns promptly, we risk driving them away. Providing timely and empathetic responses is essential to **resolving issues, maintaining trust, and ensuring that customers feel valued**, which is critical to reducing churn.
154
 
155
- - Without a personalized engagement approach, customers are more likely to churn, as they will **feel disconnected** from our brand. Tailoring our **communication and offers** based on **individual customer preference**s can significantly improve **satisfaction and foster long-term loyalty**.
156
- """)
157
- else:
158
- st.success("πŸ™† Customer is Not Gonna Churn")
159
- st.image('sss.png')
160
- st.balloons()
161
 
162
  if __name__ == "__main__":
163
  run()
 
4
  import torch
5
  import pickle
6
  from transformers import BertTokenizer, BertForSequenceClassification
7
+ import time
8
 
9
  # Load the tokenizer and model for sentiment analysis
10
  model_dir = './saved_model/' # Update this path if your model is saved elsewhere
 
73
  st.write("## βœπŸ»πŸ“‘ Input Data: ")
74
  st.write("") # Add a blank line for spacing
75
  st.write("This prediction will be done by first analyzing the sentiment from the feedback provided using a BERT model. The sentiment, along with other features, will then be used to classify whether the customer is likely to churn or not churn using an SVM classifier.")
76
+
77
+ # Sample data
78
+ samples = {
79
+ "Sample 1": {
80
+ "customer_id": "CUST001",
81
+ "tenure": 12,
82
+ "contract": "two year",
83
+ "payment_method": "credit card",
84
+ "monthly_charges": 1000000.00,
85
+ "total_charges": 6000000.00,
86
+ "feedback": "As an event planner, I've worked with many florists, but this one stands out from the crowd. For a recent high-profile corporate gala, they provided centerpieces that were nothing short of spectacular. The creativity and artistry in their designs elevated the entire event. They listened carefully to our theme and color scheme, then created arrangements that perfectly captured the essence of the evening. The flowers were fresh, vibrant, and lasted throughout the night, even under bright lights and air conditioning. What impressed me most was their flexibility - when we needed last-minute changes due to a shift in table arrangements, they accommodated without hesitation. Their team was professional, punctual, and a joy to work with. They arrived well before the event to set up and stayed until everything was perfect. The value for money was excellent, considering the high-quality results and the level of service provided. I've already booked them for several upcoming events, including a charity fundraiser and a product launch. It's rare to find a vendor that consistently exceeds expectations, but this florist does just that.",
87
+ "topic": "general feedback"
88
+ },
89
+ "Sample 2": {
90
+ "customer_id": "CUST002",
91
+ "tenure": 24,
92
+ "contract": "month-to-month",
93
+ "payment_method": "electronic check",
94
+ "monthly_charges": 750000.00,
95
+ "total_charges": 1800000.00,
96
+ "feedback": "I'm extremely disappointed with the quality of flowers in my recent order from this florist. When I first received the arrangement, I was initially impressed by its appearance. However, within just 24 hours, the flowers had already begun to wilt and lose their vibrancy. This rapid deterioration was shocking, especially considering the premium price I paid for what was supposed to be a high-quality product.\n\nMoreover, the arrangement I received didn't match the picture displayed on the website at all. The website showed a lush, full bouquet with a variety of colorful blooms, but what I got was a sparse arrangement with fewer flowers and less variety than advertised. This discrepancy between the advertised product and what was actually delivered feels misleading and has significantly diminished my trust in this florist.\n\nI've been a loyal customer for two years now, consistently ordering flowers for various occasions, but this experience has made me seriously reconsider my choice of florist. The combination of poor flower quality and misrepresentation of the product has left me feeling frustrated and undervalued as a customer. I expected much better from a service I've used and trusted for so long.",
97
+ "topic": "product quality"
98
+ },
99
+ "Sample 3": {
100
+ "customer_id": "CUST003",
101
+ "tenure": 6,
102
+ "contract": "month-to-month",
103
+ "payment_method": "bank transfer",
104
+ "monthly_charges": 400000.00,
105
+ "total_charges": 2400000.00,
106
+ "feedback": "Avoid this florist at all costs! I ordered a birthday bouquet for my wife, and the experience was a disaster from start to finish. The website was glitchy and outdated, making the ordering process frustrating and time-consuming. Despite selecting a specific delivery date and time frame, they delivered a day early when no one was home, leaving the flowers outside in the heat without any notification. By the time we got to them, they were wilted and sad-looking, with petals already falling off. The arrangement bore little resemblance to the photo on their website - it was sparse, with fewer flowers than promised, and the colors didn't match at all. Some flowers were already dropping petals, clearly not fresh, and there was an unpleasant odor suggesting that some were starting to rot. The vase was a cheap plastic one instead of the glass vase advertised, and there was no card attached despite my having written a message during the order process. When I complained, their response was slow and unsympathetic. They offered to resend flowers, but at that point, the birthday had passed, and the moment was ruined. Their prices are high, but the quality and service don't match at all. This florist clearly doesn't value their customers or take pride in their work. The entire experience was stressful and disappointing, turning what should have been a lovely surprise into a source of frustration. A complete waste of money and a huge disappointment - I would give zero stars if I could.",
107
+ "topic": "general feedback"
108
+ },
109
+ "Sample 4": {
110
+ "customer_id": "CUST004",
111
+ "tenure": 36,
112
+ "contract": "two year",
113
+ "payment_method": "mailed check",
114
+ "monthly_charges": 600000.00,
115
+ "total_charges": 2160000.00,
116
+ "feedback": "I absolutely adore the wide variety of bouquets offered by this florist. Their commitment to providing diverse and creative floral arrangements has kept me a loyal customer for three years now. The seasonal collections, in particular, never fail to impress me with their innovative designs and carefully curated flower selections that perfectly capture the essence of each season.\n\nWhat truly sets this florist apart is the consistent quality of their flowers. Every bouquet I've received has been remarkably fresh, with blooms that are vibrant and long-lasting. It's a joy to watch the flowers slowly open over the course of a week or more, filling my home with beauty and fragrance. This longevity is a testament to the florist's dedication to sourcing the finest quality blooms and their expertise in proper flower care and handling.\n\nMoreover, I appreciate how the florist stays current with floral trends while also offering timeless classics. Whether I'm looking for a modern, avant-garde arrangement or a traditional bouquet, I always find something that suits my taste. The attention to detail in each arrangement, from the selection of complementary flowers to the artful composition, demonstrates a high level of skill and artistic vision. This consistent excellence in both variety and quality is why I remain a satisfied customer and why I wholeheartedly recommend this florist to friends and family.",
117
+ "topic": "bouquet preferences"
118
+ },
119
+ "Sample 5": {
120
+ "customer_id": "CUST005",
121
+ "tenure": 18,
122
+ "contract": "two year",
123
+ "payment_method": "credit card",
124
+ "monthly_charges": 550000.00,
125
+ "total_charges": 990000.00,
126
+ "feedback": "I cannot speak highly enough of the exceptional customer service provided by this florist. Recently, I found myself in a challenging situation where I needed to make last-minute changes to my flower order for a very important event. Feeling anxious about the tight timeline, I reached out to their customer service team, not really expecting much given the short notice.\n\nTo my absolute amazement, the team not only responded promptly but also displayed an incredible level of understanding and willingness to help. They listened attentively to my concerns and the changes I needed, showing genuine empathy for my situation. What impressed me most was their proactive approach - they didn't just passively take my requests, but actively suggested solutions and alternatives that I hadn't even considered, which ended up being perfect for my needs.\n\nThe level of dedication shown by the team went far beyond my expectations. They worked tirelessly to accommodate my changes, coordinating with their florists and delivery team to ensure everything would be perfect. Throughout the process, they kept me updated, alleviating my stress and giving me confidence that everything would work out. When the flowers arrived, right on time and exactly as discussed, I was overjoyed. The quality of the arrangement was superb, and it was clear that extra care had been taken to fulfill my modified request. This experience has solidified my loyalty to this florist. Their commitment to customer satisfaction, even in challenging circumstances, is truly commendable and sets them apart in the industry.",
127
+ "topic": "customer service"
128
+ }
129
+ }
130
+
131
+ # Radio buttons for sample selection (horizontal)
132
+ selected_sample = st.radio("Select a sample", list(samples.keys()), index=0, horizontal=True)
133
+
134
+ # Get the selected sample data
135
+ sample_data = samples[selected_sample]
136
+
137
  with st.form(key="data"):
138
  col1, col2 = st.columns(2)
139
  with col1:
140
+ customer_id = st.text_input("Customer ID", value=sample_data["customer_id"])
141
+ tenure = st.number_input("Tenure (in months)", value=sample_data["tenure"])
142
  with col2:
143
  contract = st.selectbox(
144
+ "contract", ['one year', 'month-to-month', 'two year'], index=['one year', 'month-to-month', 'two year'].index(sample_data["contract"])
145
  )
146
  payment_method = st.selectbox(
147
+ "payment_method", ['credit card', 'electronic check', 'bank transfer', 'mailed check'], index=['credit card', 'electronic check', 'bank transfer', 'mailed check'].index(sample_data["payment_method"])
148
  )
149
+ monthly_charges = st.number_input("Monthly charges", value=sample_data["monthly_charges"], step=1.00)
150
+ total_charges = st.number_input("Total charges", value=sample_data["total_charges"], step=1.00)
151
  feedback = st.text_area(
152
  "Feedback",
153
+ value=sample_data["feedback"],
154
  height=300
155
  )
156
  topic = st.selectbox(
157
+ "topic", ['bouquet preferences', 'delivery issues', 'general feedback', 'price complaints', 'delivery quality', 'product quality', 'customer service', 'price appreciation'], index=['bouquet preferences', 'delivery issues', 'general feedback', 'price complaints', 'delivery quality', 'product quality', 'customer service', 'price appreciation'].index(sample_data["topic"])
158
  )
159
  # Submit button
160
  submit = st.form_submit_button("πŸ”˜ Predict")
 
171
  "topic": topic
172
  }
173
 
174
+ # Create a progress bar
175
+ progress_bar = st.progress(0)
176
+ status_text = st.empty()
177
+
178
  # Sentiment Analysis
179
  if feedback.strip() != "":
180
+ status_text.text("Performing sentiment analysis...")
181
+ for i in range(50):
182
+ time.sleep(0.001)
183
+ progress_bar.progress(i + 1)
184
+
185
  st.write("### πŸ“Š Sentiment Analysis")
186
  st.markdown('---')
187
  labels, confidences = predict_sentiment([feedback])
 
198
  data = pd.DataFrame([data])
199
 
200
  # Load customer churn model
201
+ status_text.text("Loading churn prediction model...")
202
+ for i in range(50, 75):
203
+ time.sleep(0.05)
204
+ progress_bar.progress(i + 1)
205
+
206
  with open('model.pkl', 'rb') as file_1:
207
  classification = pickle.load(file_1)
208
 
209
+ status_text.text("Predicting churn...")
210
+ for i in range(75, 100):
211
+ time.sleep(0.05)
212
+ progress_bar.progress(i + 1)
213
+
214
  churn = classification.predict(data)
215
+ churn_bool = churn.tolist()
216
+
217
+ # Clear the progress bar and status text
218
+ progress_bar.empty()
219
+ status_text.empty()
220
 
221
  # Display churn prediction result
222
+ st.write("### πŸ•΅οΈβ™‚οΈ Prediction Results: ")
223
  st.markdown('---')
224
  st.write("") # Add a blank line for spacing
225
 
226
+ if all (not element for element in churn_bool):
227
+ st.success("πŸ™† Customer is Not Gonna Churn")
228
+ st.image('sss.png')
229
+ st.balloons()
230
+ else:
231
+ if any(element for element in churn_bool):
232
+ st.error("πŸƒ **Customer is Gonna Churn!!**")
233
+ st.image('8908ec58-057d-4bfe-9ce5-74322486859a.png')
234
+ st.write('') # Add a blank line for spacing
235
+ st.write('### πŸ’­ Feedback To Marketing Team: ')
236
+ st.error("""
237
+ - **The customer** is likely to churn if we don't take immediate steps to improve our **service quality**. Consistently providing subpar service will push them to seek out competitors who can meet their expectations more reliably, resulting in a loss of **long-term loyalty and revenue**.
238
 
239
+ - Without implementing a more effective **retention strategy**, our customers are at high risk of churning. It's crucial that we personalize our **offerings, provide timely incentives, and enhance customer communication** to keep them **engaged and loyal** to our brand.
240
 
241
+ - The recent product changes have led to growing dissatisfaction among customers, increasing the likelihood of churn. To prevent this, we must swiftly **address their concerns, re-evaluate the changes, and ensure that future updates align with customer expectations** to regain their trust.
242
 
243
+ - If we fail to address customer concerns promptly, we risk driving them away. Providing timely and empathetic responses is essential to **resolving issues, maintaining trust, and ensuring that customers feel valued**, which is critical to reducing churn.
244
 
245
+ - Without a personalized engagement approach, customers are more likely to churn, as they will **feel disconnected** from our brand. Tailoring our **communication and offers** based on **individual customer preference**s can significantly improve **satisfaction and foster long-term loyalty**.
246
+ """)
247
+ else: st.write("οΏ½οΏ½ **No churn prediction available**")
 
 
 
248
 
249
  if __name__ == "__main__":
250
  run()