-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamlit_Ex
More file actions
220 lines (173 loc) · 7.56 KB
/
Copy pathStreamlit_Ex
File metadata and controls
220 lines (173 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# import module
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly_express as px
import streamlit as st
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
from xgboost import XGBRegressor
from xgboost import plot_importance
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import lightgbm as lgb
from lightgbm import LGBMRegressor
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import GridSearchCV
from PIL import Image
# Add title
st.title('Hello, let’s build an app!')
st.write('We will predict and show in app something.')
# Read the csv file and parse the 'date' column as datetime
data = pd.read_csv('us.csv', parse_dates=['date'])
st.write(data['date'].head())
#create image
img = Image.open('Frame.png')
st.image(img, width = 300)
#adding radio button
status = st.radio('Select animal: ', ('Cat','Dog'))
#conditional statement to print cat or dog
if(status == 'Cat'):
st.success('Cat')
else:
st.success('Dog')
# Read data from csv.
data_2=pd.read_csv('jfk_weather_cleaned.csv', sep=',')
# Sort data by date column.
data_2.sort_values(by=['DATE'], inplace=True)
data_2['day_of_week'] = data_2['DATE'].dt.dayofweek.astype(int)
data_2['day_of_month'] = data_2['DATE'].dt.day.astype(int)
data_2['month'] = data_2['DATE'].dt.month.astype(int)
data_2['week_of_year'] = data_2['DATE'].dt.isocalendar().week.astype(int)
data_2['season'] = (data_2['DATE'].dt.month % 12 + 3) // 3
# Encode col1, col2, col3 variables.
le = preprocessing.LabelEncoder()
data_2['HOURLYPressureTendencyCons'] = le.fit_transform(data_2['HOURLYPressureTendencyCons'])
data_2['HOURLYDewPointTempF'] = le.fit_transform(data_2['HOURLYDewPointTempF'])
data_2['HOURLYWindSpeed'] = le.fit_transform(data_2['HOURLYWindSpeed'])
data_2['HOURLYSeaLevelPressure'] = le.fit_transform(data_2['HOURLYSeaLevelPressure'])
data_2['HOURLYRelativeHumidity'] = le.fit_transform(data_2['HOURLYRelativeHumidity'])
data_2['HOURLYWindDirectionCos'] = le.fit_transform(data_2['HOURLYWindDirectionCos'])
def report_metric(pred, test, model_name):
# Creates report with mae, rmse and r2 metric and returns as df
mae = mean_absolute_error(pred, test)
mse = mean_squared_error(pred, test)
rmse = np.sqrt(mse)
r2 = r2_score(test, pred)
metric_data = {'Metric': ['MAE', 'RMSE', 'R2'], model_name: [mae, rmse, r2]}
metric_df = pd.DataFrame(metric_data)
return metric_df
def plot_preds(data_date,test_date, target, pred):
# Plots prediction vs real
fig = plt.figure(figsize=(20,10))
plt.plot(data_date, target, label = 'Real')
plt.plot(test_date, pred, label = 'Pred')
plt.legend()
st.pyplot(fig)
# Split train test and define test period.
test_period = -20
test = data_2[test_period:]
train = data_2[:test_period]
### Prepare for model 1 Linear Regressor
from sklearn.linear_model import LinearRegression
x_trainm1 = train[['HOURLYPressureTendencyCons', 'HOURLYDewPointTempF', 'HOURLYWindSpeed', "day_of_week", "day_of_month", "month", "week_of_year", "season"]]
y_trainm1 = train[["HOURLYPressureTendencyCons"]]
x_testm1 = test[['HOURLYPressureTendencyCons', 'HOURLYDewPointTempF', 'HOURLYWindSpeed', "day_of_week", "day_of_month", "month", "week_of_year", "season"]]
y_testm1 = test[["HOURLYPressureTendencyCons"]]
lr = LinearRegression()
lr.fit(x_trainm1, y_trainm1)
m1pred = lr.predict(x_testm1)
metric1 = report_metric(m1pred, y_testm1, "Linear Regression")
### Prepare for model 2 XGB Regressor
x_trainm2 = train[['HOURLYPressureTendencyCons', 'HOURLYDewPointTempF', 'HOURLYWindSpeed', "day_of_week", "day_of_month", "month", "week_of_year", "season"]]
y_trainm2 = train[["HOURLYDewPointTempF"]]
x_testm2 = test[['HOURLYPressureTendencyCons', 'HOURLYDewPointTempF','HOURLYWindSpeed', "day_of_week", "day_of_month", "month", "week_of_year", "season"]]
y_testm2 = test[["HOURLYDewPointTempF"]]
xgb = XGBRegressor(n_estimators=1000, learning_rate=0.05)
# Fit the model
xgb.fit(x_trainm2, y_trainm2)
# Get prediction
m2pred = xgb.predict(x_testm2)
metric2 = report_metric(m2pred, y_testm2, "XGB Regression")
### Prepare for model 3 LGBM Regressor
x_trainm3 = train[['HOURLYPressureTendencyCons', 'HOURLYWindSpeed', "day_of_week", "day_of_month"]]
y_trainm3 = train[["HOURLYWindSpeed"]]
x_testm3 = test[['HOURLYPressureTendencyCons', 'HOURLYWindSpeed', "day_of_week", "day_of_month"]]
y_testm3 = test[["HOURLYWindSpeed"]]
# fit scaler on training data
norm = MinMaxScaler().fit(x_trainm3)
# transform training data
x_train_normm3 = pd.DataFrame(norm.transform(x_trainm3))
# transform testing data
x_test_normm3 = pd.DataFrame(norm.transform(x_testm3))
# We tuned parameters below with best params.
lgb_tune = LGBMRegressor(learning_rate=0.1, max_depth=2, min_child_samples=25,
n_estimators=100, num_leaves=31)
lgb_tune.fit(x_train_normm3, y_trainm3)
m3pred = lgb_tune.predict(x_test_normm3)
metric3 = report_metric(m3pred, y_testm3, "LGBM Regression")
# Create a page dropdown
page = st.sidebar.selectbox("""
Hello there! I’ll guide you!
Please select model""",
["Main Page",
"Linear Regressor",
"XGB Regressor",
"LGBM Regressor",
"Compare Models"])
if page == "Main Page":
### INFO
st.title("Hello, welcome to sales predictor!")
st.write("""
This application predicts sales for the next 20 days with 3 different models
# Sales drivers used in prediction:
- Date: date format time feature
- col1: categorical feature
- col2: second categorical feature
- col3: third categorical feature
- target: target variable to be predicted
""")
st.write("Lets plot sales data!")
st.line_chart(data_2[["DATE", "HOURLYWindSpeed"]].set_index("DATE"))
elif page == "Linear Regressor":
# Base model, it uses linear regression.
st.title("Model 1: ")
st.write("Model 1 works with linear regression as base model.")
st.write("The columns it used are: col1, col2, col3,
day_of_week, day_of_month, month, week_of_year, season")
st.write(metric1)
"""
### Real vs Pred. Plot for 1. Model
"""
plot_preds(data["Date"],test["Date"], data["target"], m1pred)
elif page == “XGB Regressor”:
# Model 2
st.title(“Model 2: “)
st.write(“Model 2 works with XGB Regressor.”)
st.write(“The columns it used are: col1, col2,
col3,day_of_week, day_of_month,
month, week_of_year, season”)
st.write(metric2)
“””
### Real vs Pred. Plot for 2. Model
plot_preds(data["Date"],test["Date"], data["target"], m2pred)
elif page == “Compare Models”:
# Compare models.
st.title(“Compare Models: “)
all_metrics = metric1.copy()
all_metrics[“XGB Regression”] = metric2[“XGB Regression”].copy()
all_metrics[“LGBM Regression”] = metric3[“LGBM Regression”].copy()
st.write(all_metrics)
# Best Model
st.title(“Best Model /XGB Regressor: “)
st.write(“Lets plot best models predictions in detail.”)
# Plot best model results.
plot_preds(test[“Date”],test[“Date”], test[“target”], m2pred)
# Show rowbase best result and real
st.write(“Best Model Predictions vs Real”)
best_pred = pd.DataFrame(test[[“target”]].copy())
best_pred[“pred”] = m2pred
st.write(best_pred)