Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import joblib | |
| import numpy as np | |
| import pandas as pd | |
| import plotly.graph_objects as go | |
| # Page config | |
| st.set_page_config( | |
| page_title="Fraud Detection System", | |
| page_icon="π‘οΈ", | |
| layout="wide" | |
| ) | |
| # --- 2. SIDEBAR INSTRUCTIONS (PASTE HERE) --- | |
| with st.sidebar: | |
| st.header("π How to Use") | |
| st.info(""" | |
| 1. **Enter Features:** Fill in the values for V1 through V28. | |
| 2. **Set Amount:** Enter the dollar value of the transaction. | |
| 3. **Analyze:** Click the **'Run Fraud Analysis'** button. | |
| 4. **Result:** The AI will classify the transaction. | |
| """) | |
| st.warning("π‘ **Tip:** Try small decimal values (e.g., -1.5 or 0.5).") | |
| # Load model and scaler | |
| def load_model(): | |
| model = joblib.load('fraud_detection_model.pkl') | |
| scaler = joblib.load('scaler.pkl') | |
| return model, scaler | |
| model, scaler = load_model() | |
| # Title and description | |
| st.title("π‘οΈ Credit Card Fraud Detection System") | |
| st.markdown("---") | |
| # Sidebar | |
| with st.sidebar: | |
| st.header("Navigation") | |
| page = st.radio("Select Mode:", ["Single Prediction", "Batch Prediction", "About"]) | |
| st.markdown("---") | |
| st.markdown("### π Model Stats") | |
| st.metric("Accuracy", "99.9%") | |
| st.metric("Training Samples", "284,807") | |
| st.metric("Features", "30") | |
| # Single Prediction Page | |
| if page == "Single Prediction": | |
| st.header("π Single Transaction Prediction") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.subheader("Transaction Details") | |
| time = st.number_input("Time (seconds)", value=0.0, help="Seconds from first transaction") | |
| amount = st.number_input("Amount ($)", value=100.0, min_value=0.0) | |
| with col2: | |
| st.subheader("Quick Test") | |
| test_type = st.selectbox( | |
| "Load Sample Data:", | |
| ["Custom", "Normal Transaction", "Fraudulent Transaction"] | |
| ) | |
| st.markdown("---") | |
| st.subheader("PCA Components (V1 - V28)") | |
| st.info("These are anonymized features. For testing, use values between -5 and 5") | |
| # Create input fields for V1-V28 | |
| v_values = [] | |
| cols = st.columns(4) | |
| for i in range(28): | |
| with cols[i % 4]: | |
| if test_type == "Normal Transaction": | |
| default_val = np.random.normal(0, 1) | |
| elif test_type == "Fraudulent Transaction": | |
| default_val = np.random.normal(0, 2) | |
| else: | |
| default_val = 0.0 | |
| v_values.append(st.number_input(f"V{i+1}", value=float(default_val), format="%.4f")) | |
| st.markdown("---") | |
| if st.button("π Predict Transaction", type="primary", use_container_width=True): | |
| # Prepare features | |
| features = np.array([[time] + v_values + [amount]]) | |
| # Scale amount | |
| features_scaled = features.copy() | |
| features_scaled[0, -1] = scaler.transform([[amount]])[0][0] | |
| # Predict | |
| prediction = model.predict(features_scaled)[0] | |
| probability = model.predict_proba(features_scaled)[0] | |
| # Display results | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| if prediction == 1: | |
| st.error("π¨ FRAUD DETECTED") | |
| else: | |
| st.success("β LEGITIMATE") | |
| with col2: | |
| fraud_prob = probability[1] * 100 | |
| st.metric("Fraud Probability", f"{fraud_prob:.2f}%") | |
| with col3: | |
| confidence = max(probability) * 100 | |
| st.metric("Confidence", f"{confidence:.2f}%") | |
| # Probability gauge | |
| fig = go.Figure(go.Indicator( | |
| mode = "gauge+number", | |
| value = fraud_prob, | |
| title = {'text': "Fraud Risk Score"}, | |
| gauge = { | |
| 'axis': {'range': [None, 100]}, | |
| 'bar': {'color': "darkred" if fraud_prob > 50 else "green"}, | |
| 'steps': [ | |
| {'range': [0, 30], 'color': "lightgreen"}, | |
| {'range': [30, 70], 'color': "yellow"}, | |
| {'range': [70, 100], 'color': "lightcoral"} | |
| ], | |
| 'threshold': { | |
| 'line': {'color': "red", 'width': 4}, | |
| 'thickness': 0.75, | |
| 'value': 50 | |
| } | |
| } | |
| )) | |
| fig.update_layout(height=300) | |
| st.plotly_chart(fig, use_container_width=True) | |
| # Batch Prediction Page | |
| elif page == "Batch Prediction": | |
| st.header("π Batch Transaction Analysis") | |
| uploaded_file = st.file_uploader( | |
| "Upload CSV file with transactions", | |
| type=['csv'], | |
| help="File should contain columns: Time, V1-V28, Amount" | |
| ) | |
| if uploaded_file is not None: | |
| df = pd.read_csv(uploaded_file) | |
| st.subheader("Preview of uploaded data:") | |
| st.dataframe(df.head(10)) | |
| if st.button("π Analyze All Transactions", type="primary"): | |
| with st.spinner("Analyzing transactions..."): | |
| # Scale Amount | |
| if 'Amount' in df.columns: | |
| df_scaled = df.copy() | |
| df_scaled['Amount'] = scaler.transform(df[['Amount']]) | |
| else: | |
| df_scaled = df | |
| # Predict | |
| predictions = model.predict(df_scaled) | |
| probabilities = model.predict_proba(df_scaled) | |
| # Add results | |
| df['Prediction'] = ['Fraud' if p == 1 else 'Legitimate' for p in predictions] | |
| df['Fraud_Probability'] = [prob[1] * 100 for prob in probabilities] | |
| # Summary stats | |
| fraud_count = sum(predictions) | |
| total = len(predictions) | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.metric("Total Transactions", total) | |
| with col2: | |
| st.metric("Fraudulent", fraud_count, delta=f"{fraud_count/total*100:.2f}%") | |
| with col3: | |
| st.metric("Legitimate", total - fraud_count) | |
| # Show results | |
| st.subheader("Results:") | |
| st.dataframe(df) | |
| # Download button | |
| csv = df.to_csv(index=False) | |
| st.download_button( | |
| label="π₯ Download Results as CSV", | |
| data=csv, | |
| file_name="fraud_predictions.csv", | |
| mime="text/csv" | |
| ) | |
| # About Page | |
| else: | |
| st.header("π About This System") | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.subheader("π€ Model Information") | |
| st.markdown(""" | |
| - **Algorithm:** Random Forest Classifier | |
| - **Training Dataset:** 284,807 transactions | |
| - **Features:** 30 (Time, V1-V28, Amount) | |
| - **Accuracy:** 99.9% | |
| - **Precision:** 95%+ | |
| - **Recall:** 92%+ | |
| """) | |
| with col2: | |
| st.subheader("π Security Features") | |
| st.markdown(""" | |
| - PCA-anonymized transaction features | |
| - Real-time fraud detection | |
| - Batch processing capability | |
| - Probability-based scoring | |
| - High accuracy with low false positives | |
| """) | |
| st.markdown("---") | |
| st.subheader("β οΈ Important Notes") | |
| st.warning(""" | |
| - This is a demonstration system for educational purposes | |
| - Real-world fraud detection requires multi-layered security | |
| - Always verify high-risk transactions manually | |
| - Model performance may vary with new data patterns | |
| """) | |
| st.markdown("---") | |
| st.subheader("π οΈ Technologies Used") | |
| st.code(""" | |
| - Python 3.8+ | |
| - Scikit-learn (Machine Learning) | |
| - Streamlit (Web Interface) | |
| - Pandas & NumPy (Data Processing) | |
| - Plotly (Visualizations) | |
| - SMOTE (Handling Imbalanced Data) | |
| """) | |
| st.markdown("---") | |
| st.info("Built with β€οΈ for the ML community") | |
| # Footer | |
| st.markdown("---") | |
| st.markdown( | |
| "<div style='text-align: center; color: gray;'>Credit Card Fraud Detection System | Powered by Machine Learning</div>", | |
| unsafe_allow_html=True | |
| ) |