File size: 10,068 Bytes
ebc58e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b37d5e
ebc58e9
 
 
2b37d5e
 
ebc58e9
 
 
 
 
 
2b37d5e
 
ebc58e9
 
 
 
 
 
 
 
 
2b37d5e
 
ebc58e9
 
 
 
 
 
 
2b37d5e
 
ebc58e9
 
 
 
 
 
 
 
2b37d5e
 
ebc58e9
 
 
 
 
2b37d5e
 
 
ebc58e9
 
 
 
 
 
 
063869c
ebc58e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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.")