Le Quang Huy commited on
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import kagglehub
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from sklearn.model_selection import train_test_split
|
| 4 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 5 |
+
from sklearn.preprocessing import LabelEncoder
|
| 6 |
+
import os
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
print(" Downloading datasets from Kagglehub...")
|
| 10 |
+
path = kagglehub.dataset_download("ahmeduzaki/earthquake-alert-prediction-dataset")
|
| 11 |
+
csv_files = [f for f in os.listdir(path) if f.endswith('.csv')]
|
| 12 |
+
if not csv_files:
|
| 13 |
+
raise FileNotFoundError("No CSV files found in the downloaded dataset folder. ")
|
| 14 |
+
|
| 15 |
+
file_path = os.path.join(path, csv_files[0])
|
| 16 |
+
print(f"Using dataset file: {file_path}")
|
| 17 |
+
|
| 18 |
+
data = pd.read_csv(file_path)
|
| 19 |
+
print("Dataset loaded successfully")
|
| 20 |
+
print("Columns: ", data.columns.tolist())
|
| 21 |
+
|
| 22 |
+
X = df[['magnitude','depth' ,'cdi', 'mmi', 'sig']]
|
| 23 |
+
y = df['alert']
|
| 24 |
+
label_encoder = LabelEncoder()
|
| 25 |
+
y = label_encoder.fit_transform(y)
|
| 26 |
+
y_encoded = pd.DataFrame(y)
|
| 27 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y_encoded, random_state=42, test_size=0.2)
|
| 28 |
+
rf_model = RandomForestClassifier(
|
| 29 |
+
random_state=42,
|
| 30 |
+
n_estimators=100,
|
| 31 |
+
max_depth=8,
|
| 32 |
+
)
|
| 33 |
+
rf_model.fit(X_train, y_train)
|
| 34 |
+
accuracy = rf_model.score(X_test, y_test)
|
| 35 |
+
print(f"Model Accuracy: {accuracy * 100:.2f}%")
|
| 36 |
+
|
| 37 |
+
def predict_earthquake_alert(magnitude, depth, cdi, mmi, sig):
|
| 38 |
+
user_input = pd.DataFrame([[magnitude, depth, cdi, mmi, sig]], columns=['magnitude','depth','cdi','mmi','sig'])
|
| 39 |
+
preds = rf_model.predict(user_input)[0]
|
| 40 |
+
output = label_encoder.inverse_transform([preds])[0]
|
| 41 |
+
return (f"Predicted Earthquake Alert Level: {output}")
|
| 42 |
+
|
| 43 |
+
interface = gr.Interface(
|
| 44 |
+
fn=predict_earthquake_alert,
|
| 45 |
+
inputs=[
|
| 46 |
+
gr.Number(label="Magnitude"),
|
| 47 |
+
gr.Number(label="Depth"),
|
| 48 |
+
gr.Number(label="CDI"),
|
| 49 |
+
gr.Number(label="MMI"),
|
| 50 |
+
gr.Number(label="SIG")
|
| 51 |
+
],
|
| 52 |
+
outputs = gr.Textbox(label="prediction"),
|
| 53 |
+
title="Earthquake Alert Prediction",
|
| 54 |
+
description="Enter earthquake parameters to predict the alert level using Random Forest Classifier model"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
interface.launch()
|