Prathamesh1420 commited on
Commit
4de73ff
·
verified ·
1 Parent(s): cc3976d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mlflow
2
+ import mlflow.sklearn
3
+ from sklearn.datasets import load_diabetes
4
+ from sklearn.model_selection import train_test_split
5
+ from sklearn.linear_model import LinearRegression
6
+ from sklearn.metrics import mean_squared_error
7
+ from pyngrok import ngrok
8
+ import gradio as gr
9
+
10
+ # MLflow setup
11
+ mlflow.set_tracking_uri("./mlruns") # Local directory for tracking
12
+ mlflow.set_experiment("House Price Prediction")
13
+
14
+ # Training function
15
+ def train_and_log_model():
16
+ # Load dataset
17
+ data = load_diabetes()
18
+ X = data.data
19
+ y = data.target
20
+
21
+ # Split dataset
22
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
23
+
24
+ # Train model
25
+ model = LinearRegression()
26
+ model.fit(X_train, y_train)
27
+
28
+ # Predict and evaluate
29
+ y_pred = model.predict(X_test)
30
+ mse = mean_squared_error(y_test, y_pred)
31
+
32
+ # Log to MLflow
33
+ with mlflow.start_run():
34
+ mlflow.log_param("model", "Linear Regression")
35
+ mlflow.log_metric("mse", mse)
36
+ mlflow.sklearn.log_model(model, "model")
37
+
38
+ return mse, "Model training complete and logged to MLflow!"
39
+
40
+ # Start MLflow UI with Ngrok
41
+ def start_mlflow_ui():
42
+ public_url = ngrok.connect(5000) # Expose the MLflow UI running on port 5000
43
+ mlflow_command = "mlflow ui --host 0.0.0.0 --port 5000"
44
+ return_code = os.system(mlflow_command)
45
+ if return_code != 0:
46
+ return "Error: Unable to start MLflow UI."
47
+ return f"MLflow UI is accessible at {public_url}"
48
+
49
+ # Gradio Interface Functions
50
+ def train_model():
51
+ mse, message = train_and_log_model()
52
+ return f"MSE: {mse}\n{message}"
53
+
54
+ def get_mlflow_ui_link():
55
+ public_url = start_mlflow_ui()
56
+ return public_url
57
+
58
+ # Gradio UI
59
+ with gr.Blocks() as demo:
60
+ gr.Markdown("## House Price Prediction with MLflow")
61
+ train_btn = gr.Button("Train Model and Log to MLflow")
62
+ mlflow_btn = gr.Button("Start MLflow UI")
63
+ output = gr.Textbox(label="Output")
64
+
65
+ train_btn.click(train_model, inputs=[], outputs=output)
66
+ mlflow_btn.click(get_mlflow_ui_link, inputs=[], outputs=output)
67
+
68
+ # Launch Gradio App
69
+ if __name__ == "__main__":
70
+ demo.launch()