| | |
| | """stringleveldigits.159 |
| | |
| | Automatically generated by Colab. |
| | |
| | Original file is located at |
| | https://colab.research.google.com/drive/1PYxiyOc2syUh3LwBeNHT7Ks2uQcfVk_n |
| | """ |
| |
|
| | import numpy as np |
| | import pandas as pd |
| |
|
| | import os |
| |
|
| | for dirnam, _, filenames in os.walk('financial_risk_assessment.csv'): |
| | for filename in filenames: |
| | print(os.path.join(dirname, filename)) |
| |
|
| | import pandas as pd |
| | import numpy as np |
| | import matplotlib.pyplot as plt |
| | import seaborn as sns |
| | from sklearn.model_selection import train_test_split |
| | from sklearn.preprocessing import StandardScaler, OneHotEncoder |
| | from sklearn.compose import ColumnTransformer |
| | from sklearn.pipeline import Pipeline |
| | from sklearn.impute import SimpleImputer |
| | from sklearn.ensemble import RandomForestClassifier |
| | from sklearn.metrics import classification_report, confusion_matrix |
| |
|
| | sns.set(style="whitegrid") |
| |
|
| | df = pd.read_csv('financial_risk_assessment.csv') |
| |
|
| | df.head() |
| |
|
| | df.info() |
| |
|
| | df.describe(include=[np.number]) |
| |
|
| | df.describe(include=[object]) |
| |
|
| | df.isnull().sum() |
| |
|
| | plt.figure(figsize=(8,6)) |
| | sns.countplot(x='Risk Rating', data=df) |
| | plt.title('Distribution of Risk Ratings') |
| | plt.show() |
| |
|
| | num_features = ['Age', 'Income', 'Credit Score', 'Loan Amount', 'Years at Current Job', |
| | 'Debt-to-Income Ratio', 'Assets Value', 'Number of Dependents', 'Previous Defaults'] |
| | df[num_features].hist(figsize=(15,12), bins=30, edgecolor='black') |
| | plt.suptitle('Histograms of Numerical Features') |
| | plt.show() |
| |
|
| | plt.figure(figsize=(15,10)) |
| | for i, feature in enumerate(num_features): |
| | plt.subplot(3, 3, i+1) |
| | sns.boxplot(x='Risk Rating', y=feature, data=df) |
| | plt.title(f'Boxplot of {feature}') |
| | plt.tight_layout() |
| | plt.show() |
| |
|
| | plt.figure(figsize=(12,10)) |
| | correlation_matrix = df[num_features].corr() |
| | sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', vmin=-1, vmax=1) |
| | plt.title('Correlation Heatmap') |
| | plt.show() |
| |
|
| | for column in['Gender', 'Education Level', 'Marital Status', 'Loan Purpose', 'Employment Status', 'Payment History', 'City', 'State', 'Country']: |
| | print('f{column} unique values:') |
| | print(df[column].value_counts()) |
| | print() |
| |
|
| | X = df.drop('Risk Rating', axis=1) |
| | y = df['Risk Rating'] |
| |
|
| | 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'] |
| | categorical_features = ['Gender', 'Education Level', 'Marital Status', 'Loan Purpose', 'Employment Status', 'Payment History', 'City', 'State', 'Country'] |
| |
|
| | numeric_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]) |
| | categorical_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]) |
| | preprocessor = ColumnTransformer(transformers=[('num', numeric_transformer, numeric_features),('cat', categorical_transformer, categorical_features)]) |
| |
|
| | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) |
| | model = Pipeline(steps=[('preprocessor', preprocessor), ('classifier', RandomForestClassifier(n_estimators=100, random_state=42))]) |
| |
|
| | model.fit(X_train, y_train) |
| |
|
| | y_pred = model.predict(X_test) |
| |
|
| | print("Classification Report:") |
| | print(classification_report(y_test, y_pred)) |
| |
|
| | conf_matrix = confusion_matrix(y_test, y_pred) |
| | plt.figure(figsize=(10,7)) |
| | sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=['Low', 'Medium', 'High'], yticklabels=['Low','Medium', 'High']) |
| | plt.xlabel('Predicted') |
| | plt.ylabel('Actual') |
| | plt.title('Confusion Matrix') |
| | plt.show() |