CoolFace
Apppublic

Feiiisal/Streamlit_Income_Classification

sourceHugging Facemitupdated 3y agoView on Hugging Face
2likes
app.py151 linesDownload Raw Back to root
1import streamlit as st2import pandas as pd3import pickle4import os5from transformers import log_transform6 7# Load the model and encoder8SRC = os.path.abspath('.')9pipeline_path = os.path.join(SRC, 'pipeline.pkl')10model_path = os.path.join(SRC, 'rfc_model.pkl')11 12with open(pipeline_path, 'rb') as file:13    pipeline = pickle.load(file)14 15with open(model_path, 'rb') as file:16    model = pickle.load(file)17 18# Sidebar for navigation19st.sidebar.title("Navigation")20options = st.sidebar.radio("Select a page:", ["Prediction", "Model Information", "Feedback"])21 22 23# Prediction Page24if options == "Prediction":25    st.title("Income Classification - Prediction")26 27    # Input fields28    age = st.number_input("Age", min_value=0)29    gender = st.selectbox("Gender", ['Female', 'Male'])30    education = st.selectbox("Education", ['High School', 'Children', 'Middle School', 'Masters', 'Bachelors Degree',31                                           'Elementary', 'College Dropout', 'Associates Degree', 'Professional Degree',32                                           'Doctorate'])33    worker_class = st.selectbox("Worker Class", ['Private', 'Federal government', 'Never worked', 'Local government',34                                                 'Self-employed-incorporated', 'Self-employed-not incorporated',35                                                 'State government', 'Without pay'])36    marital_status = st.selectbox("Marital Status", ['Widowed', 'Never married', 'Married-civilian spouse present',37                                                     'Divorced', 'Married-spouse absent', 'Separated',38                                                     'Married-A F spouse present'])39    race = st.selectbox("Race", ['White', 'Black', 'Asian or Pacific Islander', 'Amer Indian Aleut or Eskimo', 'Other'])40    is_hispanic = st.selectbox("Is Hispanic", ['All other', 'Mexican-American', 'Central or South American',41                                               'Mexican (Mexicano)', 'Puerto Rican', 'Other Spanish', 'Cuban',42                                               'Do not know', 'Chicano'])43    employment_commitment = st.selectbox("Employment Commitment", ['Not in labor force', 'Children or Armed Forces',44                                                                   'Full-time schedules', 'PT for econ reasons usually PT',45                                                                   'Unemployed full-time',46                                                                   'PT for non-econ reasons usually FT',47                                                                   'PT for econ reasons usually FT',48                                                                   'Unemployed part- time'])49    employment_stat = st.number_input("Employment Status", min_value=0, max_value=2, step=1)50    wage_per_hour = st.number_input("Wage per Hour", min_value=0)51    working_week_per_year = st.number_input("Working Week per Year", min_value=0)52    industry_code = st.number_input("Industry Code", min_value=0)53    industry_code_main = st.selectbox("Industry Code Main", ['Not in universe or children', 'Hospital services',54                                                             'Retail trade', 'Finance insurance and real estate',55                                                             'Manufacturing-nondurable goods', 'Transportation',56                                                             'Business and repair services', 'Medical except hospital',57                                                             'Education', 'Construction', 'Manufacturing-durable goods',58                                                             'Public administration', 'Agriculture',59                                                             'Other professional services', 'Mining',60                                                             'Utilities and sanitary services', 'Private household services',61                                                             'Personal services except private HH', 'Wholesale trade',62                                                             'Communications', 'Entertainment', 'Social services',63                                                             'Forestry and fisheries', 'Armed Forces'])64    occupation_code = st.number_input("Occupation Code", min_value=0)65    occupation_code_main = st.selectbox("Occupation Code Main", ['Unknown', 'Adm support including clerical',66                                                                 'Executive admin and managerial', 'Sales',67                                                                 'Machine operators assmblrs & inspctrs', 'Other service',68                                                                 'Precision production craft & repair',69                                                                 'Professional specialty', 'Handlers equip cleaners etc',70                                                                 'Transportation and material moving',71                                                                 'Farming forestry and fishing', 'Private household services',72                                                                 'Technicians and related support', 'Protective services',73                                                                 'Armed Forces'])74    total_employed = st.selectbox("Total Employed", [0, 1, 2, 3, 4, 5, 6])75    household_summary = st.selectbox("Household Summary", ['Householder', 'Child 18 or older', 76                                                           'Child under 18 never married', 'Spouse of householder', 77                                                           'Nonrelative of householder', 'Other relative of householder', 78                                                           'Group Quarters- Secondary individual', 'Child under 18 ever married'])79    vet_benefit = st.number_input("Vet Benefit", min_value=0, max_value=2, step=1)80    tax_status = st.selectbox("Tax Status", ['Head of household', 'Single', 'Nonfiler', 'Joint both 65+',81                                             'Joint both under 65', 'Joint one under 65 & one 65+'])82    gains = st.number_input("Gains", min_value=0)83    losses = st.number_input("Losses", min_value=0)84    stocks_status = st.number_input("Stocks Status", min_value=0)85    citizenship = st.selectbox("Citizenship", ['citizen', 'foreigner'])86    87 88    if st.button('Predict Income Level'):89        input_data = pd.DataFrame([[90            age, gender, education, worker_class, marital_status, race, is_hispanic, employment_commitment,91            employment_stat, wage_per_hour, working_week_per_year, industry_code, industry_code_main, occupation_code,92            occupation_code_main, total_employed, household_summary, vet_benefit, tax_status, gains, losses,93            stocks_status, citizenship94        ]], columns=[95            'age', 'gender', 'education', 'worker_class', 'marital_status', 'race', 'is_hispanic', 96            'employment_commitment', 'employment_stat', 'wage_per_hour', 'working_week_per_year', 97            'industry_code', 'industry_code_main', 'occupation_code', 'occupation_code_main', 'total_employed', 98            'household_summary', 'vet_benefit', 'tax_status', 'gains', 'losses', 'stocks_status', 99            'citizenship'100        ])101 102        # Preprocess the input data through the pipeline before making predictions103        input_data_transformed = pipeline.transform(input_data)104 105        # Predict and display results106        prediction = model.predict(input_data_transformed)107        probability = model.predict_proba(input_data_transformed).max(axis=1)[0]108        result = "Above Limit" if prediction[0] == 1 else "Below Limit"109        st.success(f'Income Level Prediction: {result}')110        st.info(f'Prediction Probability: {probability:.2f}')111 112 113# Model Information Page114elif options == "Model Information":115    st.title("Model Information")116    st.write("""117        ### Model Description118        In a world where understanding financial demographics is key to tailor services and opportunities, our model serves as a powerful tool to predict an individual's income level. This insight can be instrumental for businesses, policymakers, and researchers in making informed decisions.119 120        - **Model Type:** Random Forest Classifier121          - The Random Forest is a versatile and robust machine learning method that combines multiple decision trees to produce more accurate and stable predictions. It's known for its high accuracy, ability to handle large datasets with higher dimensionality, and its robustness to overfitting.122 123        - **Training Data:** 124          - The model is trained on comprehensive census data, encompassing a wide range of features such as age, education, marital status, race, occupation, and more. This rich dataset ensures a nuanced understanding of the socio-economic factors influencing income levels.125 126        - **F1 Score:** 98%127          - With an F1 score of 98%, the model stands as a reliable predictor, demonstrating its effectiveness in understanding and categorizing income levels.128 129        - **What It Aims to Solve:**130          - **Economic Research:** Assists in socio-economic studies, understanding income distribution, and identifying key factors influencing income levels.131          - **Targeted Marketing:** Enables businesses to tailor their marketing strategies by understanding the income brackets of their potential customer base.132          - **Policy Making:** Aids policymakers in crafting targeted welfare schemes and tax brackets.133          - **Personalized Services:** Financial institutions can offer more personalized financial advice or services based on predicted income levels.134 135        - **Ethical Considerations:**136          - We are committed to ethical AI practices. We recognize the importance of privacy, fairness, and inclusivity in our model's application and strive to prevent biases.137 138    """)139 140 141# Feedback Page142elif options == "Feedback":143    st.title("Feedback")144    st.write("We value your feedback! Please let us know your thoughts about the model and interface.")145    feedback = st.text_area("Enter your feedback here")146    if st.button("Submit"):147        # Logic to store feedback, can be a simple file write or a database insert148        with open("feedback.txt", "a") as file:149            file.write(f"{feedback}\n")150        st.success("Thank you for your feedback!")151