antitheft159 commited on
Commit
2e0a0de
·
verified ·
1 Parent(s): 4059353

Upload stringleveldigits_159.py

Browse files
Files changed (1) hide show
  1. stringleveldigits_159.py +101 -0
stringleveldigits_159.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """stringleveldigits.159
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1PYxiyOc2syUh3LwBeNHT7Ks2uQcfVk_n
8
+ """
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ import os
14
+
15
+ for dirnam, _, filenames in os.walk('financial_risk_assessment.csv'):
16
+ for filename in filenames:
17
+ print(os.path.join(dirname, filename))
18
+
19
+ import pandas as pd
20
+ import numpy as np
21
+ import matplotlib.pyplot as plt
22
+ import seaborn as sns
23
+ from sklearn.model_selection import train_test_split
24
+ from sklearn.preprocessing import StandardScaler, OneHotEncoder
25
+ from sklearn.compose import ColumnTransformer
26
+ from sklearn.pipeline import Pipeline
27
+ from sklearn.impute import SimpleImputer
28
+ from sklearn.ensemble import RandomForestClassifier
29
+ from sklearn.metrics import classification_report, confusion_matrix
30
+
31
+ sns.set(style="whitegrid")
32
+
33
+ df = pd.read_csv('financial_risk_assessment.csv')
34
+
35
+ df.head()
36
+
37
+ df.info()
38
+
39
+ df.describe(include=[np.number])
40
+
41
+ df.describe(include=[object])
42
+
43
+ df.isnull().sum()
44
+
45
+ plt.figure(figsize=(8,6))
46
+ sns.countplot(x='Risk Rating', data=df)
47
+ plt.title('Distribution of Risk Ratings')
48
+ plt.show()
49
+
50
+ num_features = ['Age', 'Income', 'Credit Score', 'Loan Amount', 'Years at Current Job',
51
+ 'Debt-to-Income Ratio', 'Assets Value', 'Number of Dependents', 'Previous Defaults']
52
+ df[num_features].hist(figsize=(15,12), bins=30, edgecolor='black')
53
+ plt.suptitle('Histograms of Numerical Features')
54
+ plt.show()
55
+
56
+ plt.figure(figsize=(15,10))
57
+ for i, feature in enumerate(num_features):
58
+ plt.subplot(3, 3, i+1)
59
+ sns.boxplot(x='Risk Rating', y=feature, data=df)
60
+ plt.title(f'Boxplot of {feature}')
61
+ plt.tight_layout()
62
+ plt.show()
63
+
64
+ plt.figure(figsize=(12,10))
65
+ correlation_matrix = df[num_features].corr()
66
+ sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', vmin=-1, vmax=1)
67
+ plt.title('Correlation Heatmap')
68
+ plt.show()
69
+
70
+ for column in['Gender', 'Education Level', 'Marital Status', 'Loan Purpose', 'Employment Status', 'Payment History', 'City', 'State', 'Country']:
71
+ print('f{column} unique values:')
72
+ print(df[column].value_counts())
73
+ print()
74
+
75
+ X = df.drop('Risk Rating', axis=1)
76
+ y = df['Risk Rating']
77
+
78
+ numeric_features = ['Age', 'Income', 'Credit Score', 'Loan Amount', 'Years at Current Job', 'Debt-to-Income Ratio', 'Assets Value', 'Number of Dependents', 'Previous Defaults', 'Marital Status Change']
79
+ categorical_features = ['Gender', 'Education Level', 'Marital Status', 'Loan Purpose', 'Employment Status', 'Payment History', 'City', 'State', 'Country']
80
+
81
+ numeric_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])
82
+ categorical_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore'))])
83
+ preprocessor = ColumnTransformer(transformers=[('num', numeric_transformer, numeric_features),('cat', categorical_transformer, categorical_features)])
84
+
85
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
86
+ model = Pipeline(steps=[('preprocessor', preprocessor), ('classifier', RandomForestClassifier(n_estimators=100, random_state=42))])
87
+
88
+ model.fit(X_train, y_train)
89
+
90
+ y_pred = model.predict(X_test)
91
+
92
+ print("Classification Report:")
93
+ print(classification_report(y_test, y_pred))
94
+
95
+ conf_matrix = confusion_matrix(y_test, y_pred)
96
+ plt.figure(figsize=(10,7))
97
+ sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=['Low', 'Medium', 'High'], yticklabels=['Low','Medium', 'High'])
98
+ plt.xlabel('Predicted')
99
+ plt.ylabel('Actual')
100
+ plt.title('Confusion Matrix')
101
+ plt.show()