alidenewade commited on
Commit
a3b997c
·
verified ·
1 Parent(s): e8eb5aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -0
app.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ from sklearn.preprocessing import MinMaxScaler
7
+ from sklearn.linear_model import ElasticNet
8
+ from sklearn.model_selection import train_test_split
9
+ import gradio as gr
10
+
11
+ # Define the safety function
12
+ def safety(freedom):
13
+ return 1 - 0.7374 * freedom**2
14
+
15
+ # Load and process data for feature importance
16
+ def load_data():
17
+ # Replace this path with the appropriate dataset URL or local file path for Hugging Face deployment
18
+ data = pd.read_csv("data_ml.csv") # Ensure the dataset is uploaded to the Hugging Face repo
19
+ X = data.drop(columns=["Freedom"], errors="ignore")
20
+ y = data["Freedom"] if "Freedom" in data.columns else None
21
+ return X, y
22
+
23
+ # Calculate top features affecting safety
24
+ def get_top_features(X, y):
25
+ if y is None:
26
+ return pd.DataFrame({"Features": [], "Importance": []})
27
+
28
+ # Split data and train ElasticNet model
29
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
30
+ model = ElasticNet(alpha=1.0, l1_ratio=0.5, random_state=0).fit(X_train, y_train)
31
+
32
+ # Get feature importance
33
+ feature_importance = pd.DataFrame({
34
+ "Features": X.columns,
35
+ "Importance": np.abs(model.coef_)
36
+ }).nlargest(7, "Importance").reset_index(drop=True)
37
+ return feature_importance
38
+
39
+ # Generate PPF curve data
40
+ freedom = np.arange(0, 1.01, 0.01)
41
+ safety_values = safety(freedom)
42
+
43
+ # Initialize data and top features
44
+ X, y = load_data()
45
+ top_features = get_top_features(X, y)
46
+
47
+ # Function to update outputs when slider changes
48
+ def update_prediction(freedom_value):
49
+ # Calculate safety
50
+ safety_score = safety(freedom_value)
51
+
52
+ # Create PPF plot
53
+ fig, ax = plt.subplots(figsize=(8, 6))
54
+ ax.plot(freedom, safety_values, label='Safety = 1 - 0.7374 * Freedom²', color='blue', linestyle='--')
55
+ ax.scatter(freedom_value, safety_score, color='red', zorder=5)
56
+ ax.text(
57
+ freedom_value,
58
+ safety_score,
59
+ f"Selected Point ({freedom_value:.2f}, {safety_score:.2f})",
60
+ fontsize=9,
61
+ verticalalignment='bottom'
62
+ )
63
+ ax.set_title("Safety vs Freedom Relationship")
64
+ ax.set_xlabel("Freedom")
65
+ ax.set_ylabel("Safety")
66
+ ax.legend()
67
+ ax.grid(False)
68
+
69
+ return (
70
+ f"Predicted Safety: {safety_score:.4f}",
71
+ fig,
72
+ top_features
73
+ )
74
+
75
+ # Create Gradio interface
76
+ with gr.Blocks() as app:
77
+ gr.Markdown("# Country Safety Predictor")
78
+
79
+ with gr.Row():
80
+ # Freedom slider
81
+ freedom_slider = gr.Slider(
82
+ label="Freedom Score (0 = Least Free, 1 = Most Free)",
83
+ minimum=0,
84
+ maximum=1,
85
+ value=0.5,
86
+ step=0.01
87
+ )
88
+
89
+ with gr.Row():
90
+ # Text box for safety prediction
91
+ safety_text = gr.Textbox(label="Predicted Safety:", value="")
92
+
93
+ with gr.Row():
94
+ # Plot output for safety vs freedom
95
+ plot_output = gr.Plot(label="Safety vs Freedom Relationship")
96
+
97
+ with gr.Row():
98
+ # Dataframe display for top features
99
+ features_output = gr.Dataframe(label="Top Features Affecting Safety")
100
+
101
+ # Set up the interface
102
+ freedom_slider.change(
103
+ fn=update_prediction,
104
+ inputs=freedom_slider,
105
+ outputs=[safety_text, plot_output, features_output]
106
+ )
107
+
108
+ # Run the app
109
+ if __name__ == "__main__":
110
+ app.queue().launch(debug=False, share=True) # Enable sharing for Hugging Face deployment