FirePrediction / app.py
santhoshkumarganth's picture
update path changed
4f501ce verified
Raw History Blame Contribute Delete
4.46 kB
import streamlit as st
import pandas as pd
import plotly.express as px
import seaborn as sns
import numpy as np
import pickle
import datetime
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
import matplotlib.pyplot as plt
# Load dataset and preprocess
def preprocess_data():
df = pd.read_csv('fire_prediction_dataset_large.csv')
label_encoder = LabelEncoder()
df['Area'] = label_encoder.fit_transform(df['Area'])
X = df.drop(columns=['Fire Occurrence'])
y = df['Fire Occurrence']
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
return X_train, X_test, y_train, y_test, df, X_scaled, y
X_train, X_test, y_train, y_test, df, X_scaled, y = preprocess_data()
# Train Random Forest model
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
y_pred = rf_model.predict(X_test)
cv_scores = cross_val_score(rf_model, X_scaled, y, cv=5)
# Save Random Forest model
pickle.dump(rf_model, open('fire_model.pkl', 'wb'))
# Load advanced model
advanced_model = pickle.load(open('advanced_model.pkl', 'rb'))
def predict_forest(model, oxygen, humidity, temperature):
try:
oxygen, humidity, temperature = float(oxygen), float(humidity), float(temperature)
input_data = np.array([[oxygen, humidity, temperature]]).astype(np.float64)
prediction = model.predict_proba(input_data)[0][0]
return round(prediction, 2)
except ValueError:
return None
# Streamlit App
st.set_page_config(page_title="Forest Fire Prediction", page_icon="πŸ”₯", layout="wide")
st.title("πŸ”₯ Forest Fire Prediction & Analysis")
# Tabs for Navigation
tabs = st.tabs(["πŸ“Š Model Evaluation", "πŸ”₯ Fire Risk Prediction"])
with tabs[0]:
st.header("Model Performance Metrics")
st.write(f'Accuracy: {accuracy_score(y_test, y_pred):.3f}')
st.write(f'MSE: {mean_squared_error(y_test, y_pred):.3f}')
st.write(f'MAE: {mean_absolute_error(y_test, y_pred):.3f}')
st.write(f'RΒ² Score: {r2_score(y_test, y_pred):.3f}')
st.write(f'Precision: {precision_score(y_test, y_pred):.3f}')
st.write(f'Recall: {recall_score(y_test, y_pred):.3f}')
st.write(f'F1 Score: {f1_score(y_test, y_pred):.3f}')
st.subheader("Confusion Matrix")
fig, ax = plt.subplots()
sns.heatmap(confusion_matrix(y_test, y_pred), annot=True, fmt='d', cmap='Blues', xticklabels=['No Fire', 'Fire'], yticklabels=['No Fire', 'Fire'])
plt.xlabel('Predicted')
plt.ylabel('Actual')
st.pyplot(fig)
st.subheader("Fire Occurrence Distribution")
st.plotly_chart(px.histogram(df, x='Fire Occurrence', title='Fire Occurrence Distribution', nbins=2))
st.subheader("Feature Impact")
for feature in ['Temperature', 'Humidity', 'Oxygen']:
st.plotly_chart(px.box(df, x='Fire Occurrence', y=feature, color='Fire Occurrence', title=f'{feature} vs Fire Occurrence'))
with tabs[1]:
st.header("Fire Risk Prediction")
model_choice = st.selectbox("Choose Model", ["Random Forest Model", "Advanced Model"])
oxygen = st.text_input("Oxygen Level (%)", "")
humidity = st.text_input("Humidity (%)", "")
temperature = st.text_input("Temperature (Β°C)", "")
if st.button("Predict πŸ”₯"):
model = rf_model if model_choice == "Random Forest Model" else advanced_model
output = predict_forest(model, oxygen, humidity, temperature)
if output is None:
st.error("🚨 Please enter valid numerical values.")
else:
st.success(f"πŸ”₯ Fire Probability: **{output * 100:.2f}%**")
if output > 0.5:
st.error("Forest in🚨 High Risk! of fire occurence")
else:
st.success("βœ… Low Risk! No worries.....")
st.subheader("πŸ“œ Recent Predictions")
try:
with open("fire_predictions.txt", "r") as file:
past_predictions = file.readlines()
for pred in past_predictions[-5:]:
st.text(pred.strip())
except FileNotFoundError:
st.write("No previous predictions found.")