Yatheshr commited on
Commit
612cad1
·
verified ·
1 Parent(s): 95f79f0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+
6
+ from sklearn.preprocessing import MinMaxScaler
7
+ from tensorflow.keras.models import Sequential
8
+ from tensorflow.keras.layers import LSTM, Dense
9
+
10
+ def lstm_forecast(file, forecast_months):
11
+ # Load and preprocess data
12
+ df = pd.read_csv(file)
13
+ df['Month'] = pd.to_datetime(df['Month'])
14
+ df.set_index('Month', inplace=True)
15
+ df = df.sort_index()
16
+
17
+ if 'Spend' not in df.columns:
18
+ raise ValueError("CSV must contain a 'Spend' column.")
19
+
20
+ data = df[['Spend']]
21
+
22
+ # Scale data
23
+ scaler = MinMaxScaler()
24
+ scaled_data = scaler.fit_transform(data)
25
+
26
+ # Create sequences
27
+ def create_sequences(data, seq_length):
28
+ X, y = [], []
29
+ for i in range(len(data) - seq_length):
30
+ X.append(data[i:i+seq_length])
31
+ y.append(data[i+seq_length])
32
+ return np.array(X), np.array(y)
33
+
34
+ seq_length = 12
35
+ X, y = create_sequences(scaled_data, seq_length)
36
+ X = X.reshape((X.shape[0], X.shape[1], 1))
37
+
38
+ # Build LSTM model
39
+ model = Sequential([
40
+ LSTM(64, return_sequences=False, input_shape=(seq_length, 1)),
41
+ Dense(1)
42
+ ])
43
+ model.compile(optimizer='adam', loss='mse')
44
+ model.fit(X, y, epochs=30, batch_size=1, verbose=0)
45
+
46
+ # Forecast future values
47
+ forecast_input = scaled_data[-seq_length:].reshape((1, seq_length, 1))
48
+ forecast = []
49
+
50
+ for _ in range(forecast_months):
51
+ pred = model.predict(forecast_input, verbose=0)[0]
52
+ forecast.append(pred)
53
+ forecast_input = np.append(forecast_input[:, 1:, :], [[pred]], axis=1)
54
+
55
+ forecast = scaler.inverse_transform(forecast)
56
+
57
+ # Create forecast dates
58
+ last_date = df.index[-1]
59
+ forecast_dates = pd.date_range(start=last_date + pd.DateOffset(months=1), periods=forecast_months, freq='M')
60
+
61
+ # Plotting
62
+ plt.figure(figsize=(12, 6))
63
+ plt.plot(df.index, df['Spend'], label='Historical Spend', marker='o')
64
+ plt.plot(forecast_dates, forecast, label='LSTM Forecast', marker='o', color='green')
65
+ plt.title("Credit Card Spend Forecast with LSTM")
66
+ plt.xlabel("Month")
67
+ plt.ylabel("Spend")
68
+ plt.grid(True)
69
+ plt.legend()
70
+
71
+ return plt.gcf()
72
+
73
+ # Gradio Interface
74
+ interface = gr.Interface(
75
+ fn=lstm_forecast,
76
+ inputs=[
77
+ gr.File(label="Upload credit_card_spend.csv"),
78
+ gr.Slider(minimum=6, maximum=24, step=1, value=12, label="Months to Forecast")
79
+ ],
80
+ outputs=gr.Plot(label="LSTM Forecast Plot"),
81
+ title="📊 Credit Card Spend Forecast using LSTM",
82
+ description="Upload a CSV with 'Month' and 'Spend' columns to forecast future trends using an LSTM model."
83
+ )
84
+
85
+ interface.launch()