Sowmith22's picture
Update app.py
2b37d5e verified
import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import warnings
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
warnings.filterwarnings("ignore")
# Load the dataset
df = pd.read_csv(r"data.csv")
df.fillna(df.mean(), inplace=True)
# Create Tabs
tab1, tab2, tab3 = st.tabs(["πŸ“˜ Project Overview", "πŸ“Š EDA", "πŸ” Fault Prediction"])
# ----------------------------- TAB 1 ---------------------------------
with tab1:
st.header("πŸš— Brake System Fault Detection")
st.markdown("### 🧩 Business Problem")
st.markdown("""
In the automotive industry, ensuring the safety and reliability of braking systems is **mission-critical**. Traditional brake inspections are typically **manual and reactive**, often identifying problems **only after they occur** or during scheduled maintenance.
However, undetected faults in braking systems can lead to:
- **Brake failure during operation**
- **Reduced vehicle control**
- **Increased risk of accidents**
- **Expensive emergency repairs**
Manufacturers and fleet managers need a **real-time fault detection system** using **sensor data** to:
- Monitor brake system health continuously
- **Predict faults proactively**
- **Minimize vehicle downtime**
- Enhance **safety, reliability, and cost-efficiency**
""")
feature_desc = {
'Brake_Pressure': "Pressure applied to the brake pedal.",
'Pad_Wear_Level': "Indicates the wear level of brake pads.",
'ABS_Status': "1 if Anti-lock Braking System is active, else 0.",
'Wheel_Speed_FL': "Speed of the front-left wheel.",
'Wheel_Speed_FR': "Speed of the front-right wheel.",
'Wheel_Speed_RL': "Speed of the rear-left wheel.",
'Wheel_Speed_RR': "Speed of the rear-right wheel.",
'Fluid_Temperature': "Temperature of the brake fluid.",
'Pedal_Position': "How far the brake pedal is pressed."
}
selected = st.selectbox("Select a feature to understand:", list(feature_desc.keys()))
st.info(f"πŸ“˜ **{selected}**: {feature_desc[selected]}")
# 🎯 Goal
st.markdown("### 🎯 Goal")
st.markdown("""
Build a data-driven model that detects braking system faults using sensor data such as brake pressure, wheel speeds, fluid temperature, and pedal position.
""")
# πŸ’Ό Business Objective
st.markdown("### πŸ“Œ Business Objective")
st.markdown("""
- Detect faults early to reduce vehicle failure risks.
- Analyze sensor behavior during fault vs non-fault conditions.
- Support preventive maintenance using historical data patterns.
""")
st.markdown("### πŸ“Š Data Understanding")
st.markdown("""
The dataset contains **real-time sensor readings** collected from a vehicle's braking system to detect faults.
#### πŸ”’ Numerical Features:
- **Brake_Pressure**
- **Pad_Wear_Level**
- **Wheel_Speed_FL**, **Wheel_Speed_FR**, **Wheel_Speed_RL**, **Wheel_Speed_RR**
- **Fluid_Temperature**
- **Pedal_Position**
#### πŸ”  Categorical Feature:
- **ABS_Status**: `1` = Active, `0` = Inactive
#### 🎯 Target Variable:
- **Fault**: `1` = Fault Detected, `0` = No Fault
""")
# ----------------------------- TAB 2 ---------------------------------
with tab2:
st.title("πŸ“Š Exploratory Data Analysis")
st.subheader("πŸ“„ View Dataset Preview")
if st.button("πŸ” Show Dataset Head"):
st.dataframe(df.head()) # Displays the first few rows to understand the data format and structure
st.subheader("⚠️ Fault Distribution")
fault_counts = df['Fault'].value_counts()
st.bar_chart(fault_counts) # Insight: Helps us understand class imbalance. If faults are rare, classification might need balancing.
st.write(df['Fault'].value_counts(normalize=True) * 100) # Insight: Shows percentage distribution of Fault vs Normal.
st.subheader("πŸ“Š Correlation Heatmap")
corr = df.corr()
fig, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm", ax=ax)
st.pyplot(fig)
# Insight: Shows correlation between features. Helps identify multicollinearity (e.g., front and rear wheel speeds may be strongly correlated).
st.markdown("### πŸ“‰ Feature Distributions by Fault")
features = ['Brake_Pressure', 'Pad_Wear_Level', 'Wheel_Speed_FL', 'Wheel_Speed_FR',
'Wheel_Speed_RL', 'Wheel_Speed_RR', 'Fluid_Temperature', 'Pedal_Position']
for feature in features:
st.markdown(f"#### πŸ” {feature}")
fig, ax = plt.subplots()
sns.kdeplot(data=df, x=feature, hue="Fault", fill=True, common_norm=False, alpha=0.4, ax=ax)
st.pyplot(fig)
# Insight: Helps compare how each feature behaves under Fault vs Normal.
# For example, if Faults have higher brake pressure, this plot will reveal it through overlapping or shifting distributions.
st.markdown("### πŸ“¦ Boxplots to Compare Fault vs Normal")
for feature in features:
st.markdown(f"#### πŸ“¦ {feature} vs Fault")
fig, ax = plt.subplots()
sns.boxplot(data=df, x='Fault', y=feature, palette="Set2", ax=ax)
st.pyplot(fig)
# Insight: Boxplots show outliers, spread, and median differences between Fault and No Fault.
# Useful to detect features with significant variance or skew in faulty cases.
st.markdown("### πŸ“ Scatterplots: Detect Patterns or Anomalies")
st.markdown("These help you check combinations of features with color-coded fault info.")
fig, ax = plt.subplots()
sns.scatterplot(data=df, x="Brake_Pressure", y="Pad_Wear_Level", hue="Fault", palette="Set1", ax=ax)
ax.set_title("Brake Pressure vs Pad Wear Level")
st.pyplot(fig)
# Insight: Shows relationship between brake pressure and pad wear.
# You may find that high pressure and high wear are often associated with faults.
fig, ax = plt.subplots()
sns.scatterplot(data=df, x="Pedal_Position", y="Fluid_Temperature", hue="Fault", palette="Set2", ax=ax)
ax.set_title("Pedal Position vs Fluid Temperature")
st.pyplot(fig)
# Insight: Helps detect abnormal combinations (e.g., high pedal position with low fluid temperature) that could indicate a fault.
# ----------------------------- TAB 3 ---------------------------------
with tab3:
st.markdown(
"""
<style>
.stApp {
background-color: #e6f2ff;
padding: 12px;
}
</style>
""",
unsafe_allow_html=True
)
st.markdown("## πŸš— Vehicle Brake System Fault Detection")
st.markdown("#### Enter Brake Sensor Values to Predict Any System Fault")
# Prepare data
X = df.drop("Fault", axis=1)
y = df["Fault"]
# UI for user input
Brake_Pressure = st.slider("πŸ’¨ Brake Pressure (psi)", 50.0, 500.0, step=0.1)
Pad_Wear_Level = st.slider("πŸ›ž Pad Wear Level (%)", 0.0, 100.0, step=0.1)
ABS_Status = st.slider("πŸ›‘ ABS Status (0 = Off, 1 = On)", 0, 1, step=1)
Wheel_Speed_FL = st.slider("βš™οΈ Wheel Speed FL (km/h)", 0.0, 400.0, step=0.1)
Wheel_Speed_FR = st.slider("βš™οΈ Wheel Speed FR (km/h)", 0.0, 400.0, step=0.1)
Wheel_Speed_RL = st.slider("βš™οΈ Wheel Speed RL (km/h)", 0.0, 300.0, step=0.1)
Wheel_Speed_RR = st.slider("βš™οΈ Wheel Speed RR (km/h)", 0.0, 300.0, step=0.1)
Fluid_Temperature = st.slider("🌑️ Fluid Temperature (°C)", -20.0, 150.0, step=0.1)
Pedal_Position = st.slider("🦢 Pedal Position (%)", 0.0, 100.0, step=0.1)
# Train model
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=29)
model = LogisticRegression()
model.fit(x_train, y_train)
user_input = pd.DataFrame([[Brake_Pressure, Pad_Wear_Level, ABS_Status, Wheel_Speed_FL,
Wheel_Speed_FR, Wheel_Speed_RL, Wheel_Speed_RR,
Fluid_Temperature, Pedal_Position]],
columns=X.columns)
if st.button("πŸ” Predict Brake Fault"):
y_pred = model.predict(user_input)
prob = model.predict_proba(user_input)[0][1]
if y_pred[0] == 1:
st.error(f"🚨 Fault Detected in Brake System! (Confidence: {prob:.2%})")
issues = []
if Brake_Pressure < 60 or Brake_Pressure > 130:
issues.append("πŸ”΄ Abnormal Brake Pressure")
if Pad_Wear_Level >= 80:
issues.append("🟠 Brake Pads Critically Worn")
elif Pad_Wear_Level >= 60:
issues.append("🟑 Brake Pads Heavily Worn")
if ABS_Status == 0:
issues.append("πŸ”΅ ABS System Not Active")
if Wheel_Speed_FL < 0 or Wheel_Speed_FL > 130:
issues.append("πŸ”΄ Front Left Wheel Speed Abnormal")
if Wheel_Speed_FR < 0 or Wheel_Speed_FR > 130:
issues.append("πŸ”΄ Front Right Wheel Speed Abnormal")
if Wheel_Speed_RL < 0 or Wheel_Speed_RL > 130:
issues.append("πŸ”΄ Rear Left Wheel Speed Abnormal")
if Wheel_Speed_RR < 0 or Wheel_Speed_RR > 130:
issues.append("πŸ”΄ Rear Right Wheel Speed Abnormal")
if Fluid_Temperature < -20 or Fluid_Temperature > 120:
issues.append("πŸ”₯ Abnormal Brake Fluid Temperature")
if 20 < Pedal_Position < 60:
issues.append("🟑 Moderate Brake Pedal Pressed")
if 60 <= Pedal_Position <= 100:
issues.append("πŸ›‘ Brake Pedal Fully Pressed")
if Pedal_Position <= 20:
issues.append("πŸ” Low Brake Pedal Engagement")
for issue in issues:
st.markdown(f"- {issue}")
else:
st.success(f"βœ… No Fault Detected. (Confidence: {1 - prob:.2%})")
st.info("πŸš— Your vehicle's brake system appears healthy.")