Spaces:
Sleeping
Sleeping
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.") | |