rasmodev commited on
Commit
891dffa
·
verified ·
1 Parent(s): 3ce9ef9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -103
app.py CHANGED
@@ -2,120 +2,55 @@ import pandas as pd
2
  import streamlit as st
3
  import numpy as np
4
  import pickle
5
-
6
- # Load the saved components:
7
- with open("rf_model.pkl", "rb") as f:
8
- components = pickle.load(f)
9
-
10
- # Extract the individual components
11
- num_imputer = components["num_imputer"]
12
- cat_imputer = components["cat_imputer"]
13
- encoder = components["encoder"]
14
- scaler = components["scaler"]
15
- dt_model = components["models"]
16
 
17
  st.image("https://pbs.twimg.com/media/DywhyJiXgAIUZej?format=jpg&name=medium")
18
- st.title("Sales Prediction App")
19
-
20
- st.caption("This app predicts sales patterns of Corporation Favorita over time in different stores in Ecuador based on the inputs.")
21
 
22
  # Sidebar with input field descriptions
23
  st.sidebar.header("Description of The Required Input Fields")
24
- st.sidebar.markdown("**Store Number**: The number of the store.")
25
- st.sidebar.markdown("**Product Family**: Product Family such as 'AUTOMOTIVE', 'BEAUTY', etc. "
26
- "Details:\n"
27
- " - **AUTOMOTIVE**: Products related to the automotive industry.\n"
28
- " - **BEAUTY**: Beauty and personal care products.\n"
29
- " - **CELEBRATION**: Products for celebrations and special occasions.\n"
30
- " - **CLEANING**: Cleaning and household maintenance products.\n"
31
- " - **CLOTHING**: Clothing and apparel items.\n"
32
- " - **FOODS**: Food items and groceries.\n"
33
- " - **GROCERY**: Grocery products.\n"
34
- " - **HARDWARE**: Hardware and tools.\n"
35
- " - **HOME**: Home improvement and decor products.\n"
36
- " - **LADIESWEAR**: Women's clothing.\n"
37
- " - **LAWN AND GARDEN**: Lawn and garden products.\n"
38
- " - **LIQUOR,WINE,BEER**: Alcoholic beverages.\n"
39
- " - **PET SUPPLIES**: Products for pets and animals.\n"
40
- " - **STATIONERY**: Stationery and office supplies.")
41
- st.sidebar.markdown("**Number of Items on Promotion**: Number of items on promotion within a particular shop.")
42
- st.sidebar.markdown("**City**: City where the store is located.")
43
- st.sidebar.markdown("**Cluster**: Cluster number which is a grouping of similar stores.")
44
- st.sidebar.markdown("**Transactions**: Number of transactions.")
45
- st.sidebar.markdown("**Crude Oil Price**: Daily Crude Oil Price.")
46
-
47
 
48
  # Create the input fields
49
  input_data = {}
50
- col1,col2,col3 = st.columns(3)
51
  with col1:
52
- input_data['store_nbr'] = st.slider("Store Number",0,54)
53
- input_data['family'] = st.selectbox("Product Family", ['AUTOMOTIVE', 'BEAUTY', 'CELEBRATION', 'CLEANING', 'CLOTHING', 'FOODS',
54
- 'GROCERY', 'HARDWARE', 'HOME', 'LADIESWEAR', 'LAWN AND GARDEN', 'LIQUOR,WINE,BEER',
55
- 'PET SUPPLIES', 'STATIONERY'])
56
- input_data['onpromotion'] =st.number_input("Number of Items on Promotion",step=1)
57
- input_data['state'] = st.selectbox("State Where The Store Is Located", ['Pichincha', 'Cotopaxi', 'Chimborazo', 'Imbabura',
58
- 'Santo Domingo de los Tsachilas', 'Bolivar', 'Pastaza', 'Tungurahua', 'Guayas', 'Santa Elena', 'Los Rios', 'Azuay', 'Loja',
59
- 'El Oro', 'Esmeraldas', 'Manabi'])
60
- input_data['transactions'] = st.number_input("Number of Transactions", step=1)
61
 
62
- with col2:
63
- input_data['store_type'] = st.selectbox("Store Type",['A', 'B', 'C', 'D', 'E'])
64
- input_data['cluster'] = st.selectbox("Cluster", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
65
- input_data['dcoilwtico'] = st.number_input("Crude Oil Price",step=1)
66
- input_data['year'] = st.number_input("Year",step=1)
67
- with col3:
68
- input_data['month'] = st.slider("Month",1,12)
69
- input_data['day'] = st.slider("Day",1,31)
70
- input_data['dayofweek'] = st.number_input("Day of Week (0=Sunday and 6=Satruday)",step=1)
71
 
72
-
73
- # Create a button to make a prediction
74
  if st.button("Predict"):
75
-
76
- # Convert the input data to a pandas DataFrame
77
- input_df = pd.DataFrame([input_data])
78
-
79
- # Product Categorization Based on Families
80
- food_families = ['BEVERAGES', 'BREAD/BAKERY', 'FROZEN FOODS', 'MEATS', 'PREPARED FOODS', 'DELI', 'PRODUCE', 'DAIRY', 'POULTRY', 'EGGS', 'SEAFOOD']
81
- home_families = ['HOME AND KITCHEN I', 'HOME AND KITCHEN II', 'HOME APPLIANCES']
82
- clothing_families = ['LINGERIE', 'LADYSWARE']
83
- grocery_families = ['GROCERY I', 'GROCERY II']
84
- stationery_families = ['BOOKS', 'MAGAZINES', 'SCHOOL AND OFFICE SUPPLIES']
85
- cleaning_families = ['HOME CARE', 'BABY CARE', 'PERSONAL CARE']
86
- hardware_families = ['PLAYERS AND ELECTRONICS', 'HARDWARE']
87
-
88
- # Apply the same preprocessing steps as done during training
89
- input_df['family'] = np.where(input_df['family'].isin(food_families), 'FOODS', input_df['family'])
90
- input_df['family'] = np.where(input_df['family'].isin(home_families), 'HOME', input_df['family'])
91
- input_df['family'] = np.where(input_df['family'].isin(clothing_families), 'CLOTHING', input_df['family'])
92
- input_df['family'] = np.where(input_df['family'].isin(grocery_families), 'GROCERY', input_df['family'])
93
- input_df['family'] = np.where(input_df['family'].isin(stationery_families), 'STATIONERY', input_df['family'])
94
- input_df['family'] = np.where(input_df['family'].isin(cleaning_families), 'CLEANING', input_df['family'])
95
- input_df['family'] = np.where(input_df['family'].isin(hardware_families), 'HARDWARE', input_df['family'])
96
-
97
- categorical_columns = ['family', 'store_type', 'state']
98
- numerical_columns = ['transactions', 'dcoilwtico']
99
-
100
- # Impute missing values
101
- input_df_cat = input_df[categorical_columns].copy()
102
- input_df_num = input_df[numerical_columns].copy()
103
- input_df_cat_imputed = cat_imputer.transform(input_df_cat)
104
- input_df_num_imputed = num_imputer.transform(input_df_num)
105
-
106
- # Encode categorical features
107
- input_df_cat_encoded = pd.DataFrame(encoder.transform(input_df_cat_imputed).toarray(),
108
- columns=encoder.get_feature_names_out(categorical_columns))
109
-
110
- # Scale numerical features
111
- input_df_num_scaled = scaler.transform(input_df_num_imputed)
112
- input_df_num_sc = pd.DataFrame(input_df_num_scaled, columns=numerical_columns)
113
-
114
- # Combine encoded categorical features and scaled numerical features
115
- input_df_processed = pd.concat([input_df_num_sc, input_df_cat_encoded], axis=1)
116
-
117
  # Make predictions using the trained model
118
- predictions = dt_model.predict(input_df_processed)
119
-
120
- # Display the predicted sales value to the user:
121
  st.write("The predicted sales are:", predictions[0])
 
2
  import streamlit as st
3
  import numpy as np
4
  import pickle
5
+ from sklearn.preprocessing import MinMaxScaler
 
 
 
 
 
 
 
 
 
 
6
 
7
  st.image("https://pbs.twimg.com/media/DywhyJiXgAIUZej?format=jpg&name=medium")
8
+ st.title("Store Sales Prediction App")
9
+ st.caption("This app predicts sales patterns in different stores based on the inputs.")
 
10
 
11
  # Sidebar with input field descriptions
12
  st.sidebar.header("Description of The Required Input Fields")
13
+ st.sidebar.markdown("**Shop ID**: Unique identifier for a specific shop.")
14
+ st.sidebar.markdown("**Item ID**: Unique identifier for a product.")
15
+ st.sidebar.markdown("**Item Price**: Current price of an item.")
16
+ st.sidebar.markdown("**Item Category ID**: Unique identifier for an item category.")
17
+ st.sidebar.markdown("**Total Sales**: The total daily sales.")
18
+ st.sidebar.markdown("**Day**: Day the product was purchased.")
19
+ st.sidebar.markdown("**Month**: Month the product was purchased.")
20
+ st.sidebar.markdown("**Year**: Year the product was purchased.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  # Create the input fields
23
  input_data = {}
24
+ col1, col2 = st.columns(2)
25
  with col1:
26
+ input_data['shop_id'] = st.slider("Shop ID", 0, 54)
27
+ input_data['item_id'] = st.slider("Item ID", 100000, 1022169)
28
+ input_data['item_price'] = st.number_input("Item Price", 0, 153990)
29
+ input_data['item_category_id'] = st.slider("Item Category ID", 0, 166)
 
 
 
 
 
30
 
31
+ with col2:
32
+ input_data['day'] = st.slider("Day", 1, 31)
33
+ input_data['month'] = st.slider("Month", 1, 12)
34
+ input_data['year'] = st.number_input("Year", 2018, 2019, 2020)
 
 
 
 
 
35
 
36
+ # Create a button to make a prediction
 
37
  if st.button("Predict"):
38
+ # Feature Scaling
39
+ numerical_cols = ['shop_id', 'item_id', 'item_price', 'item_category_id', 'total_sales', 'day', 'month', 'year', 'day_of_week']
40
+ scaler = MinMaxScaler()
41
+ input_df = pd.DataFrame(input_data, index=[0])
42
+ input_df_scaled = scaler.fit_transform(input_df[numerical_cols])
43
+ input_df_scaled = pd.DataFrame(input_df_scaled, columns=numerical_cols)
44
+
45
+ # Load the scaler and model
46
+ with open('model_and_scaler.pkl', 'rb') as file:
47
+ model_and_scaler = pickle.load(file)
48
+
49
+ # Extract the model
50
+ rf_model = model_and_scaler['model']
51
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  # Make predictions using the trained model
53
+ predictions = rf_model.predict(input_df_scaled)
54
+
55
+ # Display the predicted sales value to the user
56
  st.write("The predicted sales are:", predictions[0])