Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,47 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
import numpy as np
|
| 3 |
from datetime import datetime
|
| 4 |
-
from prophet import Prophet
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
import gradio as gr
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
def simulate_factory_data(days=
|
| 9 |
date_rng = pd.date_range(end=datetime.now(), periods=24 * days, freq=freq)
|
| 10 |
df = pd.DataFrame(date_rng, columns=['ds'])
|
| 11 |
df['temperature'] = np.random.normal(loc=70, scale=4, size=(len(date_rng)))
|
| 12 |
-
|
| 13 |
-
df['
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
| 18 |
return df
|
| 19 |
|
| 20 |
def forecast_temperature(hours):
|
| 21 |
-
periods = int(hours) # Prophet expects integer periods
|
| 22 |
df = simulate_factory_data()
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
fig, ax = plt.subplots(figsize=(10, 5))
|
| 29 |
ax.plot(df['ds'], df['temperature'], label='Actual')
|
| 30 |
-
ax.plot(
|
| 31 |
-
ax.fill_between(forecast['ds'], forecast['yhat_lower'], forecast['yhat_upper'], alpha=0.2, label='Confidence')
|
| 32 |
ax.axhspan(85, 100, color='red', alpha=0.1, label='Danger Zone')
|
| 33 |
-
ax.set_title("Machine Temperature Forecast")
|
| 34 |
ax.set_xlabel("Time")
|
| 35 |
ax.set_ylabel("Temperature (°C)")
|
| 36 |
ax.legend()
|
|
@@ -39,10 +50,10 @@ def forecast_temperature(hours):
|
|
| 39 |
|
| 40 |
demo = gr.Interface(
|
| 41 |
fn=forecast_temperature,
|
| 42 |
-
inputs=gr.Slider(
|
| 43 |
outputs=gr.Plot(label="Forecasted Temperature Chart"),
|
| 44 |
-
title="Smart Factory AI Pipeline",
|
| 45 |
-
description="Forecast machine temperature using
|
| 46 |
)
|
| 47 |
|
| 48 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
import numpy as np
|
| 3 |
from datetime import datetime
|
|
|
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
import gradio as gr
|
| 6 |
+
from xgboost import XGBRegressor
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
|
| 9 |
+
def simulate_factory_data(days=7, freq='H'):
|
| 10 |
date_rng = pd.date_range(end=datetime.now(), periods=24 * days, freq=freq)
|
| 11 |
df = pd.DataFrame(date_rng, columns=['ds'])
|
| 12 |
df['temperature'] = np.random.normal(loc=70, scale=4, size=(len(date_rng)))
|
| 13 |
+
anomaly_indices = np.random.choice(len(df), size=8, replace=False)
|
| 14 |
+
df.loc[anomaly_indices, 'temperature'] += np.random.uniform(10, 20, size=8)
|
| 15 |
+
return df
|
| 16 |
+
|
| 17 |
+
def create_lag_features(df, lags=6):
|
| 18 |
+
for i in range(1, lags + 1):
|
| 19 |
+
df[f'lag_{i}'] = df['temperature'].shift(i)
|
| 20 |
+
df = df.dropna().reset_index(drop=True)
|
| 21 |
return df
|
| 22 |
|
| 23 |
def forecast_temperature(hours):
|
|
|
|
| 24 |
df = simulate_factory_data()
|
| 25 |
+
df = create_lag_features(df)
|
| 26 |
+
X = df[[f'lag_{i}' for i in range(1, 7)]]
|
| 27 |
+
y = df['temperature']
|
| 28 |
+
model = XGBRegressor(n_estimators=100, learning_rate=0.1)
|
| 29 |
+
model.fit(X, y)
|
| 30 |
+
|
| 31 |
+
last_row = df.iloc[-1][[f'lag_{i}' for i in range(1, 7)]].values
|
| 32 |
+
preds = []
|
| 33 |
+
for _ in range(int(hours)):
|
| 34 |
+
pred = model.predict([last_row])[0]
|
| 35 |
+
preds.append(pred)
|
| 36 |
+
last_row = np.roll(last_row, -1)
|
| 37 |
+
last_row[-1] = pred
|
| 38 |
+
|
| 39 |
+
future_dates = pd.date_range(start=df['ds'].iloc[-1], periods=int(hours)+1, freq='H')[1:]
|
| 40 |
fig, ax = plt.subplots(figsize=(10, 5))
|
| 41 |
ax.plot(df['ds'], df['temperature'], label='Actual')
|
| 42 |
+
ax.plot(future_dates, preds, label='Forecast', color='orange')
|
|
|
|
| 43 |
ax.axhspan(85, 100, color='red', alpha=0.1, label='Danger Zone')
|
| 44 |
+
ax.set_title("Machine Temperature Forecast (XGBoost)")
|
| 45 |
ax.set_xlabel("Time")
|
| 46 |
ax.set_ylabel("Temperature (°C)")
|
| 47 |
ax.legend()
|
|
|
|
| 50 |
|
| 51 |
demo = gr.Interface(
|
| 52 |
fn=forecast_temperature,
|
| 53 |
+
inputs=gr.Slider(6, 48, value=24, step=1, label="Forecast Hours"),
|
| 54 |
outputs=gr.Plot(label="Forecasted Temperature Chart"),
|
| 55 |
+
title="Smart Factory AI Pipeline (XGBoost)",
|
| 56 |
+
description="Forecast machine temperature using XGBoost. Red zone shows potential overheating."
|
| 57 |
)
|
| 58 |
|
| 59 |
if __name__ == "__main__":
|