WSYAM806 commited on
Commit
dc62c03
1 Parent(s): 2eb9d46

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -136
app.py CHANGED
@@ -20,128 +20,80 @@ 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("Final Project - Uncover potential insights 1999 Czech Bank Financial Dataset ")
52
  st.subheader("Abstract")
53
  st.write('This study presents an exploratory analysis of banking data to uncover potential insights and patterns related to customer behavior, credit risk assessment, geographic influences, customer segmentations, and time series trends. The analysis is conducted by integrating multiple tables containing transaction records, customer demographics, and district characteristics. The study employs various analytical techniques to extract valuable information from the data.')
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")
73
- dataset = st.container()
74
- analysis = st.container()
75
- conclusion = st.container()
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)
@@ -150,32 +102,47 @@ with App:
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
 
 
20
 
21
  """
22
 
23
+ Home, App = st.tabs(['Home','App'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  with Home:
26
  st.title("Final Project - Uncover potential insights 1999 Czech Bank Financial Dataset ")
27
  st.subheader("Abstract")
28
  st.write('This study presents an exploratory analysis of banking data to uncover potential insights and patterns related to customer behavior, credit risk assessment, geographic influences, customer segmentations, and time series trends. The analysis is conducted by integrating multiple tables containing transaction records, customer demographics, and district characteristics. The study employs various analytical techniques to extract valuable information from the data.')
29
+ st.image('bank-building.jpg')
30
+ st.subheader("Objective")
31
+ st.write('In the realm of Customer Behavior Analysis, the study investigates transaction frequency patterns among different account types, distinguishing between owners and users. Additionally, the research delves into the average transaction amounts and account balances across distinct demographic regions. The analysis further dissects transaction types, such as credit and debit, based on customer attributes, uncovering trends and correlations between demographics and transaction behaviors.')
32
+ st.write('Credit Risk Assessment is another focal point, wherein the study evaluates the intricate connection between client demographics and their credit activities. Notably, the study scrutinizes credit utilization ratios among diverse demographic groups and explores the relationship between unemployment rates and loan default rates. By employing these insights, the study contributes to the enhancement of credit risk assessment strategies.')
33
+ st.write('Geographic Analysis explores the interplay between district characteristics and banking activities. The study investigates how features like district population and urban ratio influence banking behaviors, yielding valuable insights into regional banking dynamics.')
34
+ st.write('Time Series Analysis forms an essential component of this study, unraveling transaction trends and patterns over time. The study identifies peak transaction periods and explores any seasonality in transaction frequencies or amounts. By uncovering temporal trends, the research contributes to proactive decision-making for resource allocation and customer service enhancements.')
35
+ st.write('Furthermore, the study employs advanced techniques such as Customer Segmentations, wherein clustering algorithms are utilized to group customers based on transaction behaviors and demographic attributes. These segments provide a deeper understanding of customer profiles and enable tailored services. The identification of high-value customers based on criteria such as average salary, transaction volume, and account types is an integral part of this analysis.')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  with App:
39
+ st.subheader("Cluster Prediction and Product Recommendation")
40
+ selected_features = joblib.load('selected_features.txt')
41
+ n_components = joblib.load('n_components.txt')
42
+ pipeline = joblib.load('pipeline.pkl')
43
+
44
+ df = pd.read_csv('df_trans.csv')
45
+ pension = pd.read_csv("pension_package.csv")
46
+ investment = pd.read_csv("investment_package.csv")
47
+ mortgage = pd.read_csv("mortgage_package.csv")
48
+ cluster_df = pipeline.fit(df)
49
 
 
 
 
 
 
 
 
 
 
50
 
51
+ account_id = st.number_input('Account ID')
52
+ total_amount = st.number_input('Accumulate Spending In Year')
53
+ total_balance = st.number_input('Accumulate Balance After Spending In Year')
54
+ transaction_count = st.number_input('Accumulate Transaction In Year')
55
+ Trans_Withdrawal_x = st.number_input('Accumulate Type Withdrawal Transaction In Year')
56
+ Trans_Credit = st.number_input('Accumulate Type Credit Card Transaction In Year')
57
+ Trans_Debit = st.number_input('Accumulate Type Debit Card Transaction In Year')
58
+ Collection_From_Other Bank = st.number_input('Accumulate Collection From Other Bank In Year')
59
+ Credit_Card_Withdrawal = st.number_input('Accumulate Credit Card Withdrawal In Year')
60
+ Credit_in_Cash = st.number_input('Accumulate Credit in Cash In Year')
61
+ Interest = st.number_input('Accumulate Interest In Year')
62
+ Remittance_From_Other_Bank = st.number_input('Accumulate Remittance From Other Bank In Year')
63
+ Trans_Withdrawal_y = st.number_input('Accumulate Trans Withdrawal Operation In Year')
64
+ Household_Payment = st.number_input('Accumulate Household Payment In Year')
65
+ Insurance_Payment = st.number_input('Accumulate Insurance Payment In Year')
66
+ Interest_Credit = st.number_input('Accumulate Interest Credit In Year')
67
+ Loan_Payment = st.number_input('Accumulate Loan Payment In Year')
68
+ Old_age_Pension_Payment = st.number_input('Accumulate Old age Pension Payment In Year')
69
+ Payment_of_Statement = st.number_input('Accumulate Payment of Statement In Year')
70
+ Sanction_Negative_Bal= st.number_input('Accumulate Sanction Negative Bal. In Year')
71
+ Standard_Payment = st.number_input('Accumulate Standard Payment In Year')
72
+
73
  data = {
74
+ 'account_id': account_id,
75
+ 'total_amount': total_amount,
76
+ 'total_balance': total_balance,
77
+ 'transaction_count': transaction_count,
78
+ 'Trans Withdrawal_x': Trans_Withdrawal_x,
79
+ 'Trans_Credit': Trans_Credit,
80
+ 'Trans_Debit': Trans_Debit,
81
+ 'Collection From Other Bank': Collection_From_Other Bank,
82
+ 'Credit Card Withdrawal': Credit_Card_Withdrawal,
83
+ 'Credit in Cash': Credit_in_Cash,
84
+ 'Interest': Interest,
85
+ 'Remittance From Other Bank': Remittance_From_Other_Bank,
86
+ 'Trans Withdrawal_y': Trans_Withdrawal_y,
87
+ 'Household Payment': Household_Payment,
88
+ 'Insurance Payment': Insurance_Payment,
89
+ 'Interest Credit': Interest_Credit,
90
+ 'Loan Payment': Loan_Payment,
91
+ 'Old age Pension Payment': Old_age_Pension_Payment,
92
+ 'Payment of Statement': Payment_of_Statement,
93
+ 'Sanction Negative Bal.': Sanction_Negative_Bal,
94
+ 'Standard Payment': Standard_Payment,
95
  }
96
+
97
  input = pd.DataFrame(data, index=[0])
98
  st.subheader('User Input')
99
  st.write(input)
 
102
  for perc_completed in range(100):
103
  time.sleep(0.05)
104
  progress_bar.progress(perc_completed+1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
+ prediction = pipeline.predict(input)
107
+ input['cluster'] = prediction
108
+ print('Account Cluser Status : ', prediction)
109
+ print("\n----------------\n")
110
+ for index, values in input.iterrows():
111
+ for idx_ps, val_ps in pension.iterrows():
112
+ if values['cluster'] == val_ps['Cluster']:
113
+ print(f'For account : ', values['account_id'])
114
+ print('Based on the client characteristic, here are the pension package product to offer :\n')
115
+ print(f"Product Name: {val_ps['Product Name']} \n")
116
+ val_ps_def = val_ps['Features'].split(',')
117
+ print(f'Features :\n')
118
+ for i in val_ps_def:
119
+ i = i.strip(" '\"[]")
120
+ print('*', i)
121
+ # Print a separator
122
+ print("\n----------------\n")
123
+ for idx_iv, val_iv in investment.iterrows():
124
+ if values['cluster'] == val_iv['Cluster']:
125
+ print(f'For account : ', values['account_id'])
126
+ print('Based on the client characteristic, here are the investment package product to offer :\n')
127
+ print(f"Product Name: {val_iv['Product Name']} \n")
128
+ val_iv_def = val_iv['Features'].split(',')
129
+ print(f'Features :\n')
130
+ for h in val_iv_def:
131
+ h = h.strip(" '\"[]")
132
+ print('*', h)
133
+ # Print a separator
134
+ print("\n----------------\n")
135
+ for idx_mg, val_mg in mortgage.iterrows():
136
+ if values['cluster'] == val_mg['Cluster']:
137
+ print(f'For account : ', values['account_id'])
138
+ print('Based on the client characteristic, here are the mortgage package product to offer :\n')
139
+ print(f"Product Name: {val_mg['Product Name']} \n")
140
+ val_mg_def = val_mg['Features'].split(',')
141
+ print(f'Features :\n')
142
+ for j in val_mg_def:
143
+ j = j.strip(" '\"[]")
144
+ print('*', j)
145
+ # Print a separator
146
+ print("\n----------------\n")
147
 
148