List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Build and Evaluate an LSTM Model for Retail Store Demand Forecasting

LSTM Model for Retail Store Demand Forecasting

Condition for Building and Evaluating an LSTM Model for Retail Store Demand Forecasting

  • Description:
    To forecast retail store demand, this script preprocesses historical data by handling missing values, encoding categorical features, and scaling the input features. An LSTM model is built and trained on the processed data to predict demand, and performance is evaluated using MAE, MSE, RMSE, and R² metrics.
Step-by-Step Process
  • Import Libraries:
    Import essential libraries like numpy, tensorflow, PIL, and sklearn for image processing and model building.
  • Load and Inspect Data:
    Load retail store inventory data from a CSV file and inspect the data for missing values and datatypes.
  • Preprocess Data:
    Handle missing values, encode categorical features, and scale the input and output variables.
  • Build and Train Model:
    Build an LSTM model with an input layer, LSTM layer, and a dense output layer. Train the model on the preprocessed data.
  • Evaluate and Visualize:
    Evaluate the model's performance using MAE, MSE, RMSE, and R² metrics, and visualize the results.
Sample Source Code
  • # Import Necessary Libraries
    import pandas as pd
    import numpy as np
    from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler
    from sklearn.model_selection import train_test_split
    from tensorflow.keras.layers import LSTM, Dense, Input
    from tensorflow.keras.models import Model
    import warnings
    warnings.filterwarnings("ignore")
    from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

    df = pd.read_csv("/home/soft12/Downloads/sample_dataset/Website/Dataset/retail_store_inventory.csv")

    # Check Null Values
    print("Check Null values\n")
    print(df.isnull().sum())

    # Check Nan Values
    print("\n")
    print("Check Nan Values\n")
    print(df.isna().sum())

    # Check Data types
    print(df.dtypes)

    # Convert Date column into Day,month,year
    df['Date'] = pd.to_datetime(df['Date'])
    df['day'] = df['Date'].dt.day
    df['month'] = df['Date'].dt.month
    df['year'] = df['Date'].dt.year
    df = df.drop('Date',axis=1)

    # Convert object dtype into numeric
    label = LabelEncoder()
    for i in df.columns:
    if df[i].dtypes == 'object':
    df[i] = label.fit_transform(df[i])

    x = df.drop('Demand Forecast',axis=1)
    y = df['Demand Forecast']
    y = np.array(y).reshape(-1,1)

    # Scaling the data
    scaler = StandardScaler()
    x = scaler.fit_transform(x)

    scale = MinMaxScaler()
    y = scale.fit_transform(y)
    y = y.reshape(y.shape[0])

    # Convert the Size Suitable for LSTM
    x = x.reshape(x.shape[0],1,x.shape[1])

    X_train,X_test,y_train,y_test = train_test_split(x,y,test_size=.2,random_state=42)

    def LSTM_model(input_shape):
    # Input layer
    inputs = Input(shape=input_shape)
    # LSTM layer
    lstm_layer = LSTM(32, activation='relu', return_sequences=False)(inputs)
    # Output layer
    output_layer = Dense(1, activation='linear')(lstm_layer)
    # Build the model
    lstm_model = Model(inputs=inputs, outputs=output_layer)
    # Compile the model with Adam optimizer and binary crossentropy loss function
    lstm_model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mse'])
    return lstm_model

    input_shape = (X_train.shape[1],X_train.shape[2])
    model = LSTM_model(input_shape)
    # Summary of Model
    model.summary()
    model.fit(X_train,y_train,batch_size=16,epochs=10,validation_data=(X_test,y_test))

    y_pred = model.predict(X_test)

    # Calculate MAE, MSE, RMSE, R2, and MAPE
    mae = mean_absolute_error(y_test, y_pred)
    mse = mean_squared_error(y_test, y_pred)
    rmse = np.sqrt(mse)
    r2 = r2_score(y_test, y_pred)

    # Print the metrics
    print("___Performance_Metrics___\n")
    print("Mean Absolute Error (MAE): ", mae)
    print("Mean Squared Error (MSE): ", mse)
    print("Root Mean Squared Error (RMSE): ", rmse)
    print("R-squared (R²): ", r2)
Screenshots
  • LSTM Model Output Screenshot