Updated app.py
Browse files
app.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
from sklearn.model_selection import train_test_split
|
4 |
+
from sklearn.preprocessing import LabelEncoder, StandardScaler
|
5 |
+
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
|
6 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
7 |
+
from sklearn.metrics import confusion_matrix, classification_report
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
import seaborn as sns
|
10 |
+
import re
|
11 |
+
|
12 |
+
st.title("Expense Category Prediction")
|
13 |
+
|
14 |
+
# Load data from CSV
|
15 |
+
df = pd.read_csv("financial_data.csv", sep='\s\s+', engine='python')
|
16 |
+
|
17 |
+
# Data Preprocessing
|
18 |
+
def preprocess_data(df):
|
19 |
+
|
20 |
+
# Clean the date column
|
21 |
+
df['Date'] = df['Date'].str.extract(r'(\d{4}-\d{2}-\d{2})')
|
22 |
+
|
23 |
+
# Forward fill missing dates
|
24 |
+
df['Date'] = df['Date'].ffill()
|
25 |
+
|
26 |
+
# Remove rows with missing dates
|
27 |
+
df.dropna(subset=['Date'], inplace=True)
|
28 |
+
|
29 |
+
# Convert 'Date' to datetime objects
|
30 |
+
df['Date'] = pd.to_datetime(df['Date'])
|
31 |
+
|
32 |
+
# Fill missing values in 'Expense_Category' and 'Description' with 'Unknown'
|
33 |
+
df['Expense_Category'] = df['Expense_Category'].fillna('Unknown')
|
34 |
+
df['Description'] = df['Description'].fillna('Unknown')
|
35 |
+
|
36 |
+
# Convert 'Amount' to numeric, fill missing with 0
|
37 |
+
df['Amount'] = pd.to_numeric(df['Amount'], errors='coerce').fillna(0)
|
38 |
+
|
39 |
+
# Date Feature Engineering
|
40 |
+
df['Month'] = df['Date'].dt.month
|
41 |
+
df['DayOfWeek'] = df['Date'].dt.dayofweek
|
42 |
+
|
43 |
+
# Description Text Processing
|
44 |
+
def clean_text(text):
|
45 |
+
text = text.lower()
|
46 |
+
text = re.sub(r'[^a-zA-Z0-9\s]', '', text)
|
47 |
+
return text
|
48 |
+
|
49 |
+
df['Description_Cleaned'] = df['Description'].apply(clean_text)
|
50 |
+
|
51 |
+
# TF-IDF Vectorization
|
52 |
+
tfidf_vectorizer = TfidfVectorizer(max_features=100) # Limiting features for simplicity
|
53 |
+
tfidf_features = tfidf_vectorizer.fit_transform(df['Description_Cleaned']).toarray()
|
54 |
+
tfidf_df = pd.DataFrame(tfidf_features, index=df.index)
|
55 |
+
|
56 |
+
# Combine Features
|
57 |
+
features_df = pd.concat([df[['Amount', 'Month', 'DayOfWeek']], tfidf_df], axis=1)
|
58 |
+
|
59 |
+
# Encode the target variable
|
60 |
+
label_encoder = LabelEncoder()
|
61 |
+
df['Expense_Category_Encoded'] = label_encoder.fit_transform(df['Expense_Category'])
|
62 |
+
|
63 |
+
# Select features and target
|
64 |
+
X = features_df
|
65 |
+
y = df['Expense_Category_Encoded']
|
66 |
+
|
67 |
+
# Scale the features
|
68 |
+
scaler = StandardScaler()
|
69 |
+
X = scaler.fit_transform(X)
|
70 |
+
|
71 |
+
return X, y, label_encoder, df # Return the original dataframe
|
72 |
+
|
73 |
+
X, y, label_encoder, df = preprocess_data(df.copy())
|
74 |
+
|
75 |
+
# Split data
|
76 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
77 |
+
X, y, test_size=0.2, random_state=42)
|
78 |
+
|
79 |
+
# --- Models ---
|
80 |
+
models = {
|
81 |
+
"Random Forest": RandomForestClassifier(random_state=42),
|
82 |
+
"Gradient Boosting": GradientBoostingClassifier(random_state=42)
|
83 |
+
}
|
84 |
+
|
85 |
+
# --- Streamlit Tabs ---
|
86 |
+
tabs = st.tabs(list(models.keys()))
|
87 |
+
|
88 |
+
for tab, model_name in zip(tabs, models.keys()):
|
89 |
+
with tab:
|
90 |
+
st.header(model_name)
|
91 |
+
model = models[model_name]
|
92 |
+
model.fit(X_train, y_train)
|
93 |
+
y_pred = model.predict(X_test)
|
94 |
+
|
95 |
+
# --- Confusion Matrix ---
|
96 |
+
st.subheader("Confusion Matrix")
|
97 |
+
cm = confusion_matrix(y_test, y_pred)
|
98 |
+
plt.figure(figsize=(8, 6))
|
99 |
+
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues")
|
100 |
+
plt.xlabel("Predicted")
|
101 |
+
plt.ylabel("Actual")
|
102 |
+
st.pyplot(plt.gcf())
|
103 |
+
|
104 |
+
# --- Classification Report ---
|
105 |
+
st.subheader("Classification Report")
|
106 |
+
cr = classification_report(y_test, y_pred,
|
107 |
+
target_names=label_encoder.inverse_transform(
|
108 |
+
df['Expense_Category_Encoded'].unique()),
|
109 |
+
zero_division=0) # Get original category names
|
110 |
+
st.text(cr)
|
111 |
+
|
112 |
+
# --- Remarks ---
|
113 |
+
st.subheader("Remarks")
|
114 |
+
st.write("Model Performance Analysis:")
|
115 |
+
st.write(
|
116 |
+
f"The {model_name} model's performance in predicting Expense Categories is shown above.")
|
117 |
+
st.write("Key Metrics:")
|
118 |
+
st.write(
|
119 |
+
"- The model uses a combination of expense amount, time-based features, and text descriptions to predict the expense category."
|
120 |
+
)
|
121 |
+
st.write(
|
122 |
+
"- The classification report provides insights into the model's precision, recall, and F1-score for each expense category."
|
123 |
+
)
|