IISCM / app.py
Anupam202224's picture
Create app.py
0b955fc verified
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# Function to preprocess data
def preprocess_data(data):
# Convert date column to datetime
data['date'] = pd.to_datetime(data['date'])
# Create a sequence feature
data['sequence'] = np.arange(len(data))
# Scale the demand values
scaler = MinMaxScaler()
data['demand_scaled'] = scaler.fit_transform(data['demand'].values.reshape(-1, 1))
return data, scaler
# Function for demand forecasting
def forecast_demand(data, model_type='LSTM'):
data, scaler = preprocess_data(data)
X = data[['sequence']]
y = data['demand_scaled']
# Split the data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
if model_type == 'LSTM':
# Reshape the input data for LSTM
X_train = X_train.values.reshape(-1, 1, 1)
X_test = X_test.values.reshape(-1, 1, 1)
model = Sequential()
model.add(LSTM(64, input_shape=(1, 1)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X_train, y_train, epochs=50, batch_size=32, verbose=0)
forecast = model.predict(X_test)
# Inverse scale the forecasted values
forecast = scaler.inverse_transform(forecast)
elif model_type == 'RandomForest':
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
forecast = model.predict(X_test)
# Inverse scale the forecasted values
forecast = scaler.inverse_transform(forecast.reshape(-1, 1)).squeeze()
# Inverse scale the actual test values
y_test = scaler.inverse_transform(y_test.values.reshape(-1, 1)).squeeze()
return forecast, y_test
# Gradio interface
import gradio as gr
def run_app():
with gr.Blocks() as demo:
gr.Markdown("# Intelligent Inventory and Supply Chain Management")
with gr.Tab("Demand Forecasting"):
with gr.Row():
model_type = gr.Radio(["LSTM", "RandomForest"], label="Model Type")
with gr.Row():
data_upload = gr.File(label="Upload Data")
forecast_button = gr.Button("Forecast Demand")
with gr.Row():
forecast_plot = gr.Plot()
forecast_output = gr.Dataframe(label="Forecasted Demand")
forecast_button.click(forecast_demand_wrapper, inputs=[data_upload, model_type], outputs=[forecast_plot, forecast_output])
demo.launch()
if __name__ == "__main__":
run_app()