alperugurcan's picture
Update app.py
1363fb9 verified
raw
history blame
3.29 kB
import streamlit as st
import numpy as np
import pandas as pd
from tensorflow.keras.models import load_model
from tensorflow.keras.losses import MeanSquaredError
import joblib
@st.cache_resource
def load_resources():
# Load model and scalers
custom_objects = {
'mse': MeanSquaredError(),
'mean_squared_error': MeanSquaredError(),
}
try:
# Load model resources
model = load_model('bike_model.h5', custom_objects=custom_objects)
scaler_x = joblib.load('scaler_x.pkl')
scaler_y = joblib.load('scaler_y.pkl')
features = np.load('feature_names.npy', allow_pickle=True)
# Load original data to get min-max values
df = pd.read_csv('train.csv')
feature_ranges = {
'season': (1, 4, 'Season (1:Spring, 2:Summer, 3:Fall, 4:Winter)'),
'holiday': (0, 1, 'Holiday (0:No, 1:Yes)'),
'workingday': (0, 1, 'Working Day (0:No, 1:Yes)'),
'weather': (1, 4, 'Weather (1:Clear, 2:Mist, 3:Light Rain/Snow, 4:Heavy Rain/Snow)'),
'temp': (df['temp'].min(), df['temp'].max(), 'Temperature (Celsius)'),
'atemp': (df['atemp'].min(), df['atemp'].max(), 'Feels Like Temperature (Celsius)'),
'humidity': (df['humidity'].min(), df['humidity'].max(), 'Humidity (%)'),
'windspeed': (df['windspeed'].min(), df['windspeed'].max(), 'Wind Speed')
}
return model, scaler_x, scaler_y, features, feature_ranges
except Exception as e:
st.error(f"Error loading model: {str(e)}")
raise e
st.title('🚲 Bike Sharing Demand Predictor')
st.write('Predict hourly bike rental demand based on weather conditions and time features.')
try:
model, scaler_x, scaler_y, feature_names, feature_ranges = load_resources()
col1, col2 = st.columns(2)
inputs = {}
for i, feature in enumerate(feature_names):
with col1 if i % 2 == 0 else col2:
min_val, max_val, description = feature_ranges[feature]
if feature in ['season', 'holiday', 'workingday', 'weather']:
# Integer input for categorical variables
inputs[feature] = st.number_input(
f'{description}',
min_value=int(min_val),
max_value=int(max_val),
value=int(min_val),
step=1
)
else:
# Float input for continuous variables
inputs[feature] = st.number_input(
f'{description}',
min_value=float(min_val),
max_value=float(max_val),
value=float(min_val),
step=0.1
)
if st.button('Predict Demand', use_container_width=True):
x = scaler_x.transform(np.array(list(inputs.values())).reshape(1, -1))
x = x.reshape(1, 1, x.shape[1])
pred_scaled = model.predict(x)
pred = scaler_y.inverse_transform(pred_scaled)[0][0]
st.success(f'Predicted demand: {max(0, int(pred))} bikes')
except Exception as e:
st.error(f'Error: {str(e)}')
st.markdown('---')
st.markdown('Made with ❤️ using Streamlit and TensorFlow')