There is a score column in a dataset. Your goal is to come up with a formula that estimates the score value from the values of the other columns. We have generated the dataset so that there is a formula that, for each borrower, accurately calculates the score value from the values of the other columns. Finding an accurate formula can be tricky, so you need to find a formula that estimates the score as accurately as possible. Your formula can use the values of any of the 20 columns that describe the borrower, from name to util_flg. The output of the formula should return a single number for each borrower: the score estimate. Example formula in pandas: result = (df[education_level_code'].map({ 'SPECIALTY': 0.2, 'BACHELOR': 0.3, 'MASTER': 0.5}) + 1 - df['approve_flg']) / 2 Here the education level is encoded with a real number, then one is added to it and the value of the approval flag is subtracted. The final result is divided by two. What you can and can't use In your solution, you can use: - any elementary functions and rounding functions - addition, multiplication, subtraction and division operations applied to columns element by element - substitutions: replacing character expressions with numbers, e.g. “MASTER” → 0.3 - property counting functions: number of characters in a string, day of the week for a date, ... - any pandas and numpy functions You need to respect some restrictions: - you can use machine learning algorithms to explore the dataset, but your resulting formula must depend only on the values of the original features and use only the functions described above - your formula must work only with the values of the twenty columns describing the borrower: you cannot refer to row number, other borrowers,... Important: In the formula, all columns must be called by real names (name, create_dttm, etc.) Solution Evaluation The solution will be evaluated on two criteria:
Formula accuracy. The MAE (Mean Absolute Error) metric will be used. All solutions will be ordered by increasing error - the higher the participant's ranking (i.e., the lower the error), the more points he/she will receive.
Report Quality. We will evaluate the completeness and clarity of the report, as well as the originality of the methods applied. In addition, the compactness and simplicity of the formula is evaluated - try to find a simple and beautiful solution.
Solution submission
To submit your solution you need to do three steps.
Step 1: Calculate the error of your formula and round it to the third decimal place according to the rules of mathematics. Enter the resulting value in the first line of the text box on the solution form.
Step 2. Write your final formula in a txt file and attach it to the solution. If you are solving the problem in pandas, copy the final formula and paste it into the file. If you're solving the problem in Excel or Google Sheets, describe the formula in pseudocode.
Step 3: Write a report with a precise description of the final formula and the solution: the logic of matching column names, the steps of formula search, the list of considered solutions. You may cite code fragments in the report. If you used any sources of information, list them. The report should be organized in one pdf file without references to additional parts. File size: no more than 5 A4 pages.
Important notes
Assistant
We will manually check the accuracy of your formula. If the value we get diverges from the value you specify in step 1, you will receive a penalty.
We will check the accuracy of your formula not only on the data you are working with, but also on closed test data. The test data is generated using the same principle as the main dataset, so your formula should show similar results. If the accuracy of your formula deteriorates dramatically, you will receive a penalty.
We will apply your formula to a dataset in which all columns are named correctly. If you get the column names wrong, your formula gets a low score.
To solve this problem, I wrote this code:
import pandas as pd
import numpy as np
data = pd.read_csv('/content/sample_data/credit-c61fbdb3-e0af-4b7b-9301-6ba7a994eeca.csv', header=None, names=column_names)
data = data.drop(index=0).reset_index(drop=True)
from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV
from sklearn.metrics import mean_absolute_error
X = data[features]
y = data['score']
Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print("Best Model MAE on Training Set:", mae_train)
print("Best Model MAE on Test Set:", mae_test)
print("Best Model Parameters:", grid_search.best_params_)
However, it only allows me to get such an MAE:
Best Model MAE on Training Set: 0.0536856410432385
Best Model MAE on Test Set: 0.055032521931449876
Best Model Parameters: {'colsample_bytree': 0.8, 'learning_rate': 0.05, 'max_depth': 3, 'n_estimators': 100, 'subsample': 0.8}
While my goal to lower MAE is less than 0.02
To achieve a MAE below 0.02 for estimating the score based on the other columns in your dataset, relying solely on machine learning models like XGBoost might not suffice, especially when the goal is to derive an explicit formula. Instead, a formula-based approach using linear regression with carefully engineered features can be more effective and aligned with the problem requirements.
Here's a step-by-step guide to developing an accurate formula for estimating the score:
Step 1: Understand and Prepare Your Data
Data Cleaning and Preprocessing:
Handle Missing Values: Ensure all missing values are appropriately handled. Since you’ve already converted some columns to numeric and filled missing values with zeros, ensure this is consistently applied.
Encode Categorical Variables: Convert categorical variables into numerical representations. For example:
Aggregate Features: If applicable, derive aggregate statistics from relevant columns.
Step 2: Develop a Linear Regression Model
A linear regression model provides an explicit formula that can be easily translated into the required format.
Select Relevant Features:
Choose features that have a significant correlation with the score. You can use correlation matrices or feature importance scores from tree-based models to assist in feature selection.
Fit the Linear Regression Model:
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
# Define feature columns
feature_columns = [
'education_level_num', 'age', 'subside_rate', 'days_to_approve',
'days_to_util', 'age_squared', 'education_age_interaction', 'subside_rate_squared',
'approve_flg', 'semester_cost_amt', 'initial_approved_amt'
]
X = data[feature_columns]
y = data['score']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize and fit the model
lr = LinearRegression()
lr.fit(X_train, y_train)
# Predictions
y_pred_train = lr.predict(X_train)
y_pred_test = lr.predict(X_test)
# Calculate MAE
mae_train = mean_absolute_error(y_train, y_pred_train)
mae_test = mean_absolute_error(y_test, y_pred_test)
print("Linear Regression MAE on Training Set:", round(mae_train, 3))
print("Linear Regression MAE on Test Set:", round(mae_test, 3))
Interpret the Model Coefficients:
The coefficients from the linear regression model will form the basis of your formula.
Detail the steps taken, feature engineering, modeling process, and rationale behind the final formula.
Include insights on feature selection, coefficient interpretation, and any optimizations performed.
Ensure the report is clear, concise, and within the 5 A4 pages limit.
Additional Tips
Cross-Validation: Use cross-validation to ensure the model generalizes well to unseen data.
Residual Analysis: Analyze the residuals to identify any patterns or areas where the model might be improved.
Feature Importance: Although not directly applicable to linear models, understanding which features contribute most can guide further feature engineering.
By transitioning to a linear regression approach with meticulous feature engineering and validation, you can derive a precise and interpretable formula that meets the MAE requirements. This method aligns with the problem's constraints and facilitates an explicit formula submission.