It appears that both the original test.py and the desired model_testing.py formats you've provided are identical. However, to ensure clarity and address potential improvements or modifications you might be aiming for, I'll present the model_testing.py script with enhanced formatting and added comments for better understanding. Additionally, I'll address the preservation of the txn_id in the output, which seems to be dropped during preprocessing but used later for predictions.
Here's the refined model_testing.py:
# model_testing.py
import pandas as pd
import pickle
import numpy as np
import os
from sklearn.preprocessing import LabelEncoder, StandardScaler
class Hackathon:
def __init__(self, artifacts_path='artifacts'):
"""
Initialize the Hackathon by loading the model and preprocessing artifacts.
Parameters:
- artifacts_path: str, path to the directory containing the artifacts.
"""
# Load model
model_path = os.path.join(artifacts_path, 'model.pkl')
with open(model_path, 'rb') as f:
self.model = pickle.load(f)
# Load label encoder
le_path = os.path.join(artifacts_path, 'label_encoder.pkl')
with open(le_path, 'rb') as f:
self.le = pickle.load(f)
# Load scaler
scaler_path = os.path.join(artifacts_path, 'scaler.pkl')
with open(scaler_path, 'rb') as f:
self.scaler = pickle.load(f)
def preprocess(self, df):
"""
Preprocess the input data in the same manner as the training data.
Parameters:
- df: pandas DataFrame, input data.
Returns:
- pandas DataFrame, preprocessed data.
"""
# Keep 'txn_id' for later use and drop it from features
txn_ids = df['txn_id'] if 'txn_id' in df.columns else None
drop_cols = ['txn_id', 'trndate', 'payee_account_number', 'payer_address']
df = df.drop(columns=drop_cols, errors='ignore')
# Handle missing values
df.fillna(-999, inplace=True)
# Encode categorical variables
categorical_cols = ['payee_bank', 'payee_tpap', 'txn_type', 'initiation_mode',
'payer_tpap', 'payer_bank']
for col in categorical_cols:
if col in df.columns:
# Handle unseen labels by assigning 'Unknown'
df[col] = df[col].astype(str).apply(
lambda x: x if x in self.le.classes_ else 'Unknown'
)
# If 'Unknown' was not in training, add it
if 'Unknown' not in self.le.classes_:
self.le.classes_ = np.append(self.le.classes_, 'Unknown')
df[col] = self.le.transform(df[col])
# Feature engineering: Extract year, month, day from date columns
date_cols = [
'upi_min_dt_payer', 'upi_min_dt_payee', 'py_max_asdt_payer', 'py_max_asdt_payee',
'mas_minasdt_mob_payer', 'mas_minasdt_mob_payee',
'mas_vpa_pr_minasdt_payer', 'mas_vpa_pr_maxasdt_payer',
'mas_vpa_py_minasdt_payee', 'mas_vpa_py_maxasdt_payee',
'mas_maxasdt_mob_payer', 'mas_maxasdt_mob_payee'
]
for col in date_cols:
if col in df.columns:
df[col] = pd.to_datetime(df[col], errors='coerce', dayfirst=True)
df[col + '_year'] = df[col].dt.year.fillna(0).astype(int)
df[col + '_month'] = df[col].dt.month.fillna(0).astype(int)
df[col + '_day'] = df[col].dt.day.fillna(0).astype(int)
df = df.drop(columns=[col])
# Scale numerical features
numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns.tolist()
if 'fraud' in numeric_cols:
numeric_cols.remove('fraud') # Exclude target if present
df[numeric_cols] = self.scaler.transform(df[numeric_cols])
# Optionally, add 'txn_id' back to the DataFrame if needed
if txn_ids is not None:
df = pd.concat([txn_ids.reset_index(drop=True), df.reset_index(drop=True)], axis=1)
return df
def predict(self, input_data):
"""
Predict whether transactions are fraudulent or not.
Parameters:
- input_data: pandas DataFrame containing transaction records.
Returns:
- pandas Series with predictions (0 or 1).
"""
# Preprocess the input data
df_processed = self.preprocess(input_data)
# Make predictions
preds = self.model.predict(df_processed)
return pd.Series(preds)
# Example usage:
if __name__ == '__main__':
# Load sample input data
sample_data = pd.read_csv('sample_test.csv') # Replace with actual input data
# Initialize the model
fraud_model = Hackathon()
# Make predictions
predictions = fraud_model.predict(sample_data)
# Output predictions
sample_data['predicted_fraud'] = predictions
print(sample_data[['txn_id', 'predicted_fraud']])
Key Enhancements and Clarifications:
-
Preservation of txn_id:
- Issue: In the original script,
txn_id is dropped during preprocessing but later used in the output. This would result in a KeyError if txn_id isn't present in the preprocessed DataFrame.
- Solution: Before dropping, store
txn_id and then concatenate it back after preprocessing to ensure it's available for the final output.
-
Enhanced Documentation:
- Added more detailed docstrings to explain the parameters and return values of methods.
-
Modular Path Handling:
- Separated paths for model, label encoder, and scaler for clarity and easier debugging.
-
Error Handling:
- Ensured that if
txn_id isn't present in the input data, the script won't throw an error.
-
Code Formatting:
- Improved readability with consistent indentation and spacing.
- Added comments to explain each major step within methods.
-
Flexibility in Preprocessing:
- The
preprocess method now optionally retains the txn_id, making the class more flexible depending on whether you need to keep certain identifier columns.
Additional Recommendations:
-
Logging: Implement logging instead of print statements for better monitoring and debugging, especially for larger applications or production environments.
-
Exception Handling: Incorporate try-except blocks to handle potential errors during file loading, data processing, or prediction phases.
-
Configuration Management: Instead of hardcoding paths and parameters, consider using a configuration file or environment variables to manage different environments (development, testing, production).
-
Unit Testing: Develop unit tests for each method to ensure reliability and facilitate maintenance.
-
Dependency Management: Use a requirements.txt or Pipfile to manage Python package dependencies, ensuring consistency across different environments.
If you have specific modifications or a different format in mind, please provide more details so I can assist you accordingly.