WSYAM806 commited on
Commit
35caaaa
1 Parent(s): 185eba1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -133
app.py CHANGED
@@ -2,8 +2,10 @@ import streamlit as st
2
  import pandas as pd
3
  import joblib
4
  import numpy as np
5
- from sklearn.cluster import KMeans
6
  import time
 
 
 
7
 
8
  page_bg_img = """
9
  <style>[data-testid="stAppViewContainer"]{
@@ -20,53 +22,14 @@ background-color: rgba(0,0,0,0);
20
 
21
  """
22
 
23
- Home, Eda, App, Conclusion = st.tabs(['Home', 'Eda', 'App', 'Conclusion'])
24
-
25
- with Conclusion:
26
- st.title("Conclusion")
27
- st.write("Yes, the result of implementing the loan prediction model can indeed solve the mentioned problems effectively. The loan prediction model offers various advantages to the lending institution and its customers, addressing key challenges in the loan approval process. Here's how the model can solve the problems:")
28
- st.write("1. Enhanced Loan Approval Process: The loan prediction model automates and optimizes the loan approval process by accurately predicting loan approval or rejection. This reduces the need for manual reviews, streamlines the process, and saves time and resources.")
29
- st.write("2. Risk Mitigation and Improved Decision Making: The model's segmentation of approved loans into low, moderate, and high-risk categories enables better assessment of creditworthiness. By identifying high-risk borrowers, the institution can take appropriate risk mitigation measures to reduce defaults and potential losses.")
30
- st.write("3. Customer-Centric Approach: The model provides faster and more reliable loan decisions to customers, creating a better customer experience. Faster loan approvals and access to funds benefit customers, while low-risk borrowers may enjoy more favorable loan terms, incentivizing timely repayments.")
31
- st.write("4. Improved Portfolio Management: Accurate risk segmentation and loan approval predictions support better portfolio management. The institution can maintain a balanced distribution of risk levels, optimizing the overall portfolio risk and potentially increasing profitability.")
32
- st.write("5. Compliance and Regulatory Alignment: The model ensures that lending decisions align with regulatory guidelines and compliance requirements. By incorporating fairness and transparency, the institution reduces bias and ensures adherence to industry standards.")
33
- st.write("6. Competitive Advantage: The advanced loan prediction model gives the lending institution a competitive edge. Quicker loan approvals, reduced risk exposure, and improved customer satisfaction can attract more borrowers and enhance the institution's reputation in the market.")
34
- st.write("In conclusion, implementing the loan prediction model brings significant benefits to the lending institution and its customers. It streamlines operations, enhances risk assessment, improves decision-making, and ensures compliance, ultimately providing a more efficient and customer-friendly loan approval process. The model's positive impact can position the lending institution as a competitive player in the market, attracting more borrowers and strengthening its position in the industry.")
35
- st.subheader("**Possible Reasons for Unmatched Predictions:**")
36
- st.write("- Data Quality Issues: Unmatched predictions could be attributed to data quality problems, such as missing or incorrect values, outliers, or inconsistencies in the dataset. Ensuring data cleanliness and accuracy is crucial for model performance.")
37
- st.write("- Complex Cases: Some loan applications might involve complex or unusual situations that the model has not encountered during training. The model might struggle to generalize to such cases, leading to unmatched predictions.")
38
- st.write("- Imbalanced Data: While the overall dataset might be balanced, certain subgroups or specific classes within the data might be imbalanced. The model may face challenges in accurately predicting these imbalanced classes.")
39
- st.write("- Model Complexity: The RFC model, while powerful, could potentially be overfitting the training data, leading to difficulties in generalizing to unseen instances.")
40
- st.subheader("**Steps for Improvement:**")
41
- st.write("- Data Analysis and Preprocessing: Investigate the unmatched predictions to identify patterns and potential data quality issues. Address missing values, outliers, and inconsistencies in the data. Conduct thorough exploratory data analysis to understand the distribution of features in the unmatched instances.")
42
- st.write("- Feature Engineering: Evaluate the existing features and consider creating new features that might better represent complex relationships in the data. Feature engineering could provide the model with additional information to improve predictions.")
43
- st.write("- Model Evaluation and Tuning: Reevaluate the model's hyperparameters and consider alternative approaches for hyperparameter tuning. Techniques like GridSearch or RandomizedSearch can help optimize the model's performance.")
44
- st.write("- Ensemble Methods: Consider using ensemble methods, such as Stacking or Boosting, to combine predictions from multiple models and improve overall accuracy and robustness.")
45
- st.write("- Handling Imbalanced Data: If certain classes are imbalanced, implement strategies like oversampling, undersampling, or using class weights to balance the dataset during training.")
46
- st.write("- Regularization: Apply regularization techniques to prevent overfitting and improve the model's ability to generalize to unseen data.")
47
- st.subheader("**Model Conclusion**")
48
- st.write("The presence of 55 unmatched predictions in the RFC model indicates the need for further analysis and improvement. By addressing data quality issues, optimizing hyperparameters, considering feature engineering, and exploring ensemble methods, the model's performance can be enhanced. Regular evaluation and monitoring will ensure that the model remains effective in predicting loan approvals and supports the lending institution's decision-making process.")
49
 
50
  with Home:
51
- st.title("Milestone 2 - Create Model Loan Prediction")
52
  st.subheader("Problem Statement")
53
- st.write('Develop a robust machine learning model for loan prediction that accurately classifies loan applications as either approved or rejected, while also segmenting the approved loans into three risk categories: low risk, moderate risk, and high risk. The model should leverage historical loan data, applicant information, and credit analysis to make informed decisions, enabling the lending institution to streamline the loan approval process and mitigate potential credit risks effectively.')
54
- st.image('loan.jpg')
55
- bisnis = st.container()
56
- with bisnis:
57
- st.subheader("Business Implcation")
58
- st.write("**1. Enhanced Loan Approval Process:**")
59
- st.write("Enhancing the loan approval process involves using advanced predictive models to automate and optimize the decision-making process for loan applications. By implementing a loan prediction model, lending institutions can accurately assess the creditworthiness of applicants, predict loan approval outcomes, and expedite the approval process. This results in reduced manual reviews and faster loan decisions, improving operational efficiency and customer experience. The importance of an enhanced loan approval process lies in its ability to streamline operations, save time and resources, and increase the institution's capacity to handle a higher volume of loan applications effectively.")
60
- st.write("**2. Risk Mitigation and Improved Decision Making:**")
61
- st.write("Risk mitigation is a critical aspect of lending institutions' operations. The use of predictive models, such as credit risk assessment models, enables lenders to identify high-risk borrowers accurately. By assessing credit risk more effectively, lending institutions can make informed decisions regarding loan approvals, interest rates, and loan terms. Improved decision-making leads to a reduced risk of default and potential losses, enhancing the overall financial stability of the institution. The importance of risk mitigation lies in safeguarding the institution's financial health and ensuring responsible lending practices.")
62
- st.write("**3. Customer-Centric Approach:**")
63
- st.write("A customer-centric approach emphasizes meeting the needs and preferences of borrowers. Implementing a loan prediction model can lead to faster loan approvals and more personalized loan terms based on borrowers' credit profiles. Low-risk borrowers may receive more favorable interest rates, encouraging responsible borrowing behavior. The importance of a customer-centric approach is twofold: it enhances customer satisfaction and loyalty while also reducing the institution's exposure to high-risk borrowers, resulting in improved loan portfolio quality.")
64
- st.write("**4. Improved Portfolio Management:**")
65
- st.write("Effective portfolio management is crucial for lending institutions to maintain a balanced and diversified loan portfolio. Loan prediction models aid in categorizing loans into different risk segments (low, moderate, high), allowing institutions to optimize their portfolios by strategically allocating resources to various risk categories. A well-managed portfolio reduces the risk of concentration in high-risk loans and increases the potential for profitable returns. The importance of improved portfolio management lies in ensuring long-term financial stability and maximizing returns on investment.")
66
- st.write("**5. Compliance and Regulatory Alignment:**")
67
- st.write("Lending institutions operate within a complex regulatory landscape. Predictive models can be designed to incorporate fairness and transparency, aligning lending decisions with regulatory guidelines. This helps prevent discriminatory practices, ensures compliance with fair lending laws, and enhances the institution's reputation. The importance of compliance and regulatory alignment is to protect the institution from legal risks, maintain trust with customers and regulators, and uphold ethical lending standards.")
68
- st.write("**6. Competitive Advantage:**")
69
- st.write("Implementing advanced predictive models for loan approvals can provide lending institutions with a competitive advantage in the market. Faster loan processing, accurate risk assessment, and personalized loan offerings attract more borrowers and improve the institution's market positioning. A competitive advantage enables the institution to capture a larger market share, achieve higher customer retention rates, and ultimately drive business growth and profitability.attract more borrowers and enhance the institution's reputation.")
70
 
71
  with Eda:
72
  st.title("Exploratory Data Analysis")
@@ -76,106 +39,86 @@ with Eda:
76
 
77
  with dataset:
78
  st.subheader("Dataset")
79
- st.text("https://www.kaggle.com/datasets/architsharma01/loan-approval-prediction-dataset")
80
- df = pd.read_csv('loan_approval_dataset.csv')
81
  st.dataframe(df)
82
- st.write('Default Curreny : INR')
83
- with analysis:
 
 
 
 
 
 
84
  st.subheader("Data Overview")
85
- st.image('data overview.PNG')
86
- st.subheader("Varibles")
87
- st.image('variables 1.PNG')
88
- st.image('variables 2.PNG')
89
- st.image('variables 3.PNG')
90
- st.image('variables 4.PNG')
91
- st.image('variables 5.PNG')
92
- st.image('variables 6.PNG')
93
- st.image('variables 7.PNG')
94
- st.image('variables 8.PNG')
95
- st.image('variables 9.PNG')
96
- st.image('variables 10.PNG')
97
- st.image('variables 11.PNG')
98
- st.image('variables 12.PNG')
99
- st.image('variables 13.PNG')
100
- st.subheader("Interacations")
101
- st.image('intercation.PNG')
102
- st.subheader("Correlations")
103
- st.image('correlation.PNG')
104
- st.subheader("Missing Value")
105
- st.image('correlation.PNG')
106
- with conclusion:
107
- st.subheader("Conclusion")
108
- st.image('conclusion.PNG')
 
 
 
 
 
 
109
 
110
  with App:
111
- st.subheader("New user model prediction")
112
- cluster = joblib.load('cluster.pkl')
113
- model = joblib.load('all_process.pkl')
114
 
115
- df = pd.read_csv('loan_approval_dataset.csv')
116
- num_col = [' income_annum', ' loan_amount', ' loan_term', ' cibil_score', ' residential_assets_value', ' commercial_assets_value', ' luxury_assets_value', ' bank_asset_value']
117
- cluster_data = df.drop(columns=[col for col in df.columns if col not in num_col])
118
- cluster_df = cluster.fit_transform(cluster_data)
119
- k_3 = KMeans(n_clusters=3)
120
- label3 = k_3.fit_transform(cluster_df)
121
- label = pd.DataFrame(label3)
122
- df = pd.concat([label.reset_index(drop=True), df], axis=1)
123
- df.rename(columns={0: "cluster"}, inplace=True)
124
-
125
- income_annum = st.slider('income_annum', 0,9999999)
126
- loan_amount = st.slider('loan_amount', 0,9999999)
127
- loan_term = st.slider('loan_term', 2, 24)
128
- cibil_score = st.slider('cibil_score', 0,900)
129
- residential_assets_value = st.slider('residential_assets_value', 0, 9999999)
130
- commercial_assets_value = st.slider('commercial_assets_value',0,9999999)
131
- luxury_assets_value = st.slider('luxury_assets_value',0,9999999)
132
- bank_asset_value = st.slider('bank_asset_value',0,9999999)
133
- education = st.selectbox('education',[' Not Graduate', ' Graduate'])
134
  data = {
135
- ' income_annum': income_annum,
136
- ' loan_amount': loan_amount,
137
- ' loan_term': loan_term,
138
- ' cibil_score': cibil_score,
139
- ' residential_assets_value': residential_assets_value,
140
- ' commercial_assets_value': commercial_assets_value,
141
- ' luxury_assets_value': luxury_assets_value,
142
- ' bank_asset_value': bank_asset_value,
143
- ' education': education,
144
  }
145
  input = pd.DataFrame(data, index=[0])
146
  st.subheader('User Input')
147
  st.write(input)
148
  if st.button('Predict'):
149
- progress_bar = st.progress(0)
150
- for perc_completed in range(100):
151
- time.sleep(0.05)
152
- progress_bar.progress(perc_completed+1)
153
- num_col = [' income_annum', ' loan_amount', ' loan_term', ' cibil_score', ' residential_assets_value', ' commercial_assets_value', ' luxury_assets_value', ' bank_asset_value']
154
- def_cluster = input.drop(columns=[col for col in input.columns if col not in num_col])
155
- def_pca = cluster.transform(def_cluster)
156
- labelz = k_3.predict(def_pca)
157
- cluster_names = {
158
- 0: 'Moderate-Risk Customers',
159
- 1: 'Low-Risk Customers',
160
- 2: 'High-Risk Customers'
161
- }
162
- cluster_labels = [cluster_names[label] for label in labelz]
163
- input['cluster'] = cluster_labels
164
-
165
- if np.all(labelz == 0):
166
- st.write('Based on user input, the placement cluster: Moderate-Risk Customers')
167
- elif np.all(labelz == 1):
168
- st.write('Based on user input, the placement cluster: Low-Risk Customers')
169
- elif np.all(labelz == 2):
170
- st.write('Based on user input, the placement cluster: High-Risk Customers')
171
-
172
- prediction = model.predict(input)
173
-
174
- if prediction == 0:
175
- prediction = ' Rejected'
176
  else:
177
- prediction = ' Approved'
178
 
179
- st.write('The model approval status: ',prediction)
 
180
 
181
 
 
2
  import pandas as pd
3
  import joblib
4
  import numpy as np
 
5
  import time
6
+ import seaborn as sns
7
+ import matplotlib.pyplot as plt
8
+ import tensorflow as tf
9
 
10
  page_bg_img = """
11
  <style>[data-testid="stAppViewContainer"]{
 
22
 
23
  """
24
 
25
+ Home, Eda, App = st.tabs(['Home', 'Eda', 'App'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  with Home:
28
+ st.title("P2 Milestone 1 - Create a Robust Costumer Churn Prediction")
29
  st.subheader("Problem Statement")
30
+ st.write('Create a robust costumer churn prediction to directly intialize and handle the appropriate actions to prevent costumers leaving our services')
31
+ st.image('Customer-Churn.PNG')
32
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  with Eda:
35
  st.title("Exploratory Data Analysis")
 
39
 
40
  with dataset:
41
  st.subheader("Dataset")
42
+ st.Write("The dataset is related to customer churn prediction, where the goal is to predict whether a customer is likely to churn based on the given features. Machine learning models can be trained on this dataset to predict the churn risk of customers, helping businesses take appropriate actions to retain customers and improve customer satisfaction.")
43
+ df = pd.read_csv('churn.csv')
44
  st.dataframe(df)
45
+
46
+ with analysis:
47
+ imbalance = st.container()
48
+ member = st.container()
49
+ behavior_1 = st.container()
50
+ behavior_2 = st.container()
51
+ behavior_3 = st.container()
52
+ correlation = st.container()
53
  st.subheader("Data Overview")
54
+ with imbalance:
55
+ st.subheader("Imbalance Data Target")
56
+ sns.countplot(data=df, x='churn_risk_score', hue='churn_risk_score')
57
+ with member:
58
+ st.subheader("Membership")
59
+ sns.countplot(data=df, x='membership_category', hue='churn_risk_score')
60
+ plt.xticks(rotation=45, ha='right')
61
+ plt.show
62
+ st.subheader("Customer Behavior")
63
+ with behavior_1:
64
+ sns.countplot(data=df, x='preferred_offer_types', hue='churn_risk_score')
65
+ plt.xticks(rotation=45, ha='right')
66
+ plt.show
67
+ with behavior_2:
68
+ sns.countplot(data=df, x='medium_of_operation', hue='churn_risk_score')
69
+ plt.xticks(rotation=45, ha='right')
70
+ plt.show
71
+ with behavior_3:
72
+ sns.countplot(data=df, x='internet_option', hue='churn_risk_score')
73
+ plt.xticks(rotation=45, ha='right')
74
+ plt.show
75
+ st.write("Costumer are more likely to churn if choose option without offer, Medium of operation using smartphone is more likely to churn but not significanly different with dekstop user and it seems that is no indication between internet option")
76
+
77
+ with correlation:
78
+ st.subheader("Numeric Correlation")
79
+ fig,ax = plt.subplots(figsize=[20,15])
80
+ corr = df.corr()
81
+ ax = sns.heatmap(corr,annot=True)
82
+ plt.show()
83
+
84
 
85
  with App:
86
+ st.subheader("Churn Prediction")
87
+ model_tf = tf.keras.models.load_model("model_best.hdf5")
88
+ preprocess = joblib.load('full_pipeline.pkl')
89
 
90
+ df = pd.read_csv('churn.csv')
91
+
92
+ user_id = st.text_input('Your ID')
93
+ age = st.slider('age', 0,100)
94
+ membership_category = st.selectbox('membership',['No Membership', 'Basic Membership','Silver Membership', 'Gold Membership', 'Premium Membership', 'Platinum Membership'])
95
+ avg_transaction_value = st.slider('avg_transaction_value', 0,999999)
96
+ avg_frequency_login_days = st.slider('avg_frequency_login_days', 0, 24)
97
+ points_in_wallet = st.slider('points_in_wallet',0,9999999)
98
+ feedback = st.selectbox('membership',['No reason specified', 'Poor Customer Service','Poor Product Quality', 'Poor Website', 'Products always in Stock', 'Quality Customer Care','Reasonable Price', 'Too many ads', 'User Friendly Website'])
99
+
 
 
 
 
 
 
 
 
 
100
  data = {
101
+ 'user_id': user_id,
102
+ 'age': age,
103
+ 'membership_category': membership_category,
104
+ 'avg_transaction_value': avg_transaction_value,
105
+ 'avg_frequency_login_days': avg_frequency_login_days,
106
+ 'points_in_wallet': points_in_wallet,
107
+ 'feedback': feedback,
108
+
 
109
  }
110
  input = pd.DataFrame(data, index=[0])
111
  st.subheader('User Input')
112
  st.write(input)
113
  if st.button('Predict'):
114
+ process = preprocess.transform(input)
115
+ prediction = model_tf.predict(input)
116
+ if prediction == 1:
117
+ prediction = 'Churn'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  else:
119
+ prediction = 'Not Churn'
120
 
121
+ st.write('Based on user input, the placement model predicted: ')
122
+ st.write(prediction)
123
 
124