Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -41,6 +41,11 @@ def load_data():
|
|
| 41 |
# Load data
|
| 42 |
df = load_data()
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
# Sidebar for navigation
|
| 45 |
page = st.sidebar.selectbox("Choose a page", ["Data Explorer", "Model Training", "Price Prediction"])
|
| 46 |
|
|
@@ -54,82 +59,82 @@ if page == "Data Explorer":
|
|
| 54 |
st.subheader("Data Visualization")
|
| 55 |
fig, ax = plt.subplots(1, 2, figsize=(15, 5))
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
demand_col = [col for col in df.columns if 'demand' in col.lower()]
|
| 60 |
-
|
| 61 |
-
if price_col and 'suggested_price' in df.columns:
|
| 62 |
-
ax[0].scatter(df[price_col[0]], df['suggested_price'])
|
| 63 |
ax[0].set_xlabel(price_col[0])
|
| 64 |
-
ax[0].set_ylabel(
|
| 65 |
-
ax[0].set_title(f'{price_col[0]} vs
|
| 66 |
|
| 67 |
-
if demand_col and
|
| 68 |
-
ax[1].scatter(df[demand_col[0]], df[
|
| 69 |
ax[1].set_xlabel(demand_col[0])
|
| 70 |
-
ax[1].set_ylabel(
|
| 71 |
-
ax[1].set_title(f'{demand_col[0]} vs
|
| 72 |
|
| 73 |
st.pyplot(fig)
|
| 74 |
|
| 75 |
elif page == "Model Training":
|
| 76 |
st.title("Model Training")
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
# Model architecture
|
| 101 |
-
model = Sequential([
|
| 102 |
-
Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
|
| 103 |
-
Dense(32, activation='relu'),
|
| 104 |
-
Dense(16, activation='relu'),
|
| 105 |
-
Dense(1)
|
| 106 |
-
])
|
| 107 |
-
|
| 108 |
-
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mae'])
|
| 109 |
-
|
| 110 |
-
# Training
|
| 111 |
-
if st.button("Train Model"):
|
| 112 |
-
with st.spinner("Training in progress..."):
|
| 113 |
-
history = model.fit(X_train, y_train, validation_split=0.2, epochs=100, batch_size=32, verbose=0)
|
| 114 |
|
| 115 |
-
|
|
|
|
| 116 |
|
| 117 |
-
#
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
st.pyplot(fig)
|
| 125 |
|
| 126 |
-
|
| 127 |
-
model.save('dynamic_pricing_model.h5')
|
| 128 |
-
joblib.dump(scaler, 'scaler.pkl')
|
| 129 |
-
joblib.dump(encoders, 'encoders.pkl')
|
| 130 |
-
joblib.dump(feature_cols, 'feature_cols.pkl')
|
| 131 |
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
elif page == "Price Prediction":
|
| 135 |
st.title("Price Prediction")
|
|
@@ -140,6 +145,7 @@ elif page == "Price Prediction":
|
|
| 140 |
scaler = joblib.load('scaler.pkl')
|
| 141 |
encoders = joblib.load('encoders.pkl')
|
| 142 |
feature_cols = joblib.load('feature_cols.pkl')
|
|
|
|
| 143 |
|
| 144 |
# User input
|
| 145 |
input_data = {}
|
|
@@ -166,7 +172,7 @@ elif page == "Price Prediction":
|
|
| 166 |
# Make prediction
|
| 167 |
if st.button("Predict Price"):
|
| 168 |
predicted_price = model.predict(input_scaled)[0][0]
|
| 169 |
-
st.success(f"Predicted
|
| 170 |
else:
|
| 171 |
st.warning("Please train the model first!")
|
| 172 |
|
|
|
|
| 41 |
# Load data
|
| 42 |
df = load_data()
|
| 43 |
|
| 44 |
+
# Identify price and demand columns
|
| 45 |
+
price_col = [col for col in df.columns if 'price' in col.lower() and col != 'suggested_price']
|
| 46 |
+
demand_col = [col for col in df.columns if 'demand' in col.lower()]
|
| 47 |
+
target_col = 'suggested_price' if 'suggested_price' in df.columns else (price_col[0] if price_col else None)
|
| 48 |
+
|
| 49 |
# Sidebar for navigation
|
| 50 |
page = st.sidebar.selectbox("Choose a page", ["Data Explorer", "Model Training", "Price Prediction"])
|
| 51 |
|
|
|
|
| 59 |
st.subheader("Data Visualization")
|
| 60 |
fig, ax = plt.subplots(1, 2, figsize=(15, 5))
|
| 61 |
|
| 62 |
+
if price_col and target_col:
|
| 63 |
+
ax[0].scatter(df[price_col[0]], df[target_col])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
ax[0].set_xlabel(price_col[0])
|
| 65 |
+
ax[0].set_ylabel(target_col)
|
| 66 |
+
ax[0].set_title(f'{price_col[0]} vs {target_col}')
|
| 67 |
|
| 68 |
+
if demand_col and target_col:
|
| 69 |
+
ax[1].scatter(df[demand_col[0]], df[target_col])
|
| 70 |
ax[1].set_xlabel(demand_col[0])
|
| 71 |
+
ax[1].set_ylabel(target_col)
|
| 72 |
+
ax[1].set_title(f'{demand_col[0]} vs {target_col}')
|
| 73 |
|
| 74 |
st.pyplot(fig)
|
| 75 |
|
| 76 |
elif page == "Model Training":
|
| 77 |
st.title("Model Training")
|
| 78 |
|
| 79 |
+
if not target_col:
|
| 80 |
+
st.error("No suitable target column (suggested_price or another price column) found in the dataset.")
|
| 81 |
+
else:
|
| 82 |
+
# Data preprocessing
|
| 83 |
+
categorical_cols = df.select_dtypes(include=['object']).columns
|
| 84 |
+
numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
|
| 85 |
+
|
| 86 |
+
# Remove target column from features if it exists
|
| 87 |
+
feature_cols = [col for col in numeric_cols if col != target_col]
|
| 88 |
+
|
| 89 |
+
encoders = {}
|
| 90 |
+
for col in categorical_cols:
|
| 91 |
+
encoders[col] = LabelEncoder()
|
| 92 |
+
df[f'{col}_encoded'] = encoders[col].fit_transform(df[col])
|
| 93 |
+
feature_cols.append(f'{col}_encoded')
|
| 94 |
+
|
| 95 |
+
X = df[feature_cols]
|
| 96 |
+
y = df[target_col]
|
| 97 |
+
|
| 98 |
+
scaler = StandardScaler()
|
| 99 |
+
X_scaled = scaler.fit_transform(X)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# Split the data
|
| 102 |
+
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
|
| 103 |
|
| 104 |
+
# Model architecture
|
| 105 |
+
model = Sequential([
|
| 106 |
+
Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
|
| 107 |
+
Dense(32, activation='relu'),
|
| 108 |
+
Dense(16, activation='relu'),
|
| 109 |
+
Dense(1)
|
| 110 |
+
])
|
|
|
|
| 111 |
|
| 112 |
+
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mae'])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
# Training
|
| 115 |
+
if st.button("Train Model"):
|
| 116 |
+
with st.spinner("Training in progress..."):
|
| 117 |
+
history = model.fit(X_train, y_train, validation_split=0.2, epochs=100, batch_size=32, verbose=0)
|
| 118 |
+
|
| 119 |
+
st.success("Model trained successfully!")
|
| 120 |
+
|
| 121 |
+
# Plot training history
|
| 122 |
+
fig, ax = plt.subplots(figsize=(10, 5))
|
| 123 |
+
ax.plot(history.history['loss'], label='Training Loss')
|
| 124 |
+
ax.plot(history.history['val_loss'], label='Validation Loss')
|
| 125 |
+
ax.set_xlabel('Epoch')
|
| 126 |
+
ax.set_ylabel('Loss')
|
| 127 |
+
ax.legend()
|
| 128 |
+
st.pyplot(fig)
|
| 129 |
+
|
| 130 |
+
# Save model and preprocessing objects
|
| 131 |
+
model.save('dynamic_pricing_model.h5')
|
| 132 |
+
joblib.dump(scaler, 'scaler.pkl')
|
| 133 |
+
joblib.dump(encoders, 'encoders.pkl')
|
| 134 |
+
joblib.dump(feature_cols, 'feature_cols.pkl')
|
| 135 |
+
joblib.dump(target_col, 'target_col.pkl')
|
| 136 |
+
|
| 137 |
+
st.info("Model and preprocessing objects saved.")
|
| 138 |
|
| 139 |
elif page == "Price Prediction":
|
| 140 |
st.title("Price Prediction")
|
|
|
|
| 145 |
scaler = joblib.load('scaler.pkl')
|
| 146 |
encoders = joblib.load('encoders.pkl')
|
| 147 |
feature_cols = joblib.load('feature_cols.pkl')
|
| 148 |
+
target_col = joblib.load('target_col.pkl')
|
| 149 |
|
| 150 |
# User input
|
| 151 |
input_data = {}
|
|
|
|
| 172 |
# Make prediction
|
| 173 |
if st.button("Predict Price"):
|
| 174 |
predicted_price = model.predict(input_scaled)[0][0]
|
| 175 |
+
st.success(f"Predicted {target_col}: ${predicted_price:.2f}")
|
| 176 |
else:
|
| 177 |
st.warning("Please train the model first!")
|
| 178 |
|