Spaces:
Sleeping
Sleeping
File size: 5,851 Bytes
b6345bc |
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 |
import streamlit as st
import pandas as pd
import torch
import torch.nn as nn
from sklearn.preprocessing import StandardScaler, LabelEncoder
st.set_page_config(layout="wide")
# Add custom CSS for background image and styling
# Add custom CSS for background image and styling
st.markdown("""
<style>
.stApp {
background-image: url("https://cdn.pixabay.com/photo/2020/01/28/11/14/galaxy-4799471_1280.jpg");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: auto; /* Allows the page to expand for scrolling */
overflow: auto; /* Enables scrolling if the page content overflows */
}
/* Adjust opacity of overlay to make content more visible */
.stApp::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0); /* Slightly higher opacity */
z-index: 0;
}
/* Ensure content appears above the overlay */
.stApp > * {
position: relative;
z-index: 1;
}
/* Ensure the dataframe is visible */
.dataframe {
background-color: rgba(255, 255, 255, 0.9) !important;
z-index: 2;
}
/* Style text elements for better visibility */
h1, h3, span, div {
text-shadow: 1px 1px 2px rgba(255, 255, 255, 0.2);
}
</style>
""", unsafe_allow_html=True)
# Custom title styling functions
def colored_title(text, color):
st.markdown(f"<h1 style='color: {color};'>{text}</h1>", unsafe_allow_html=True)
def colored_subheader(text, color):
st.markdown(f"<h3 style='color: {color};'>{text}</h3>", unsafe_allow_html=True)
def colored_text(text, color):
st.markdown(f"<span style='color: {color};'>{text}</span>", unsafe_allow_html=True)
class ANNModel(nn.Module):
def __init__(self, input_size):
super(ANNModel, self).__init__()
self.fc1 = nn.Linear(input_size, 64)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
@st.cache_resource
def load_model():
_, X_scaled, _ = load_and_preprocess_data()
input_size = X_scaled.shape[1]
model = ANNModel(input_size=input_size)
try:
state_dict = torch.load('model_weights.pth', map_location=torch.device('cpu'))
model.load_state_dict(state_dict)
model.eval()
return model
except Exception as e:
st.error(f"Error loading model: {str(e)}")
return None
@st.cache_data
def load_and_preprocess_data():
df = pd.read_csv('Life Expectancy Data.csv')
df.columns = df.columns.str.strip()
df_display = df.copy()
expected_features = [
'Adult Mortality', 'infant deaths', 'Alcohol', 'percentage expenditure', 'Hepatitis B',
'Measles', 'BMI', 'under-five deaths', 'Polio', 'Total expenditure',
'Diphtheria', 'HIV/AIDS', 'GDP', 'Population', 'thinness 1-19 years',
'thinness 5-9 years', 'Income composition of resources', 'Schooling',
'Country', 'Status', 'Year'
]
for feature in expected_features:
if feature not in df.columns:
st.warning(f"Missing column '{feature}' - Creating with default values")
df[feature] = 0
df_display[feature] = 0
for column in df.columns:
if df[column].dtype == 'object':
fill_value = df[column].mode()[0]
df[column].fillna(fill_value, inplace=True)
df_display[column].fillna(fill_value, inplace=True)
else:
fill_value = df[column].median()
df[column].fillna(fill_value, inplace=True)
df_display[column].fillna(fill_value, inplace=True)
label_encoders = {}
categorical_cols = ['Country', 'Status']
for col in categorical_cols:
le = LabelEncoder()
df[col] = le.fit_transform(df[col].astype(str))
label_encoders[col] = le
X = df[expected_features]
y = df['Life expectancy']
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
return df_display, X_scaled, y
def main():
colored_title("Life Expectancy Estimation", "yellow")
df_display, X_scaled, y = load_and_preprocess_data()
colored_subheader("Dataset Preview", "yellow")
st.dataframe(df_display.head())
colored_subheader("Select a Row for Prediction:", "yellow")
colored_text("Select a Row Index", "red")
selected_row_index = st.selectbox("", options=range(len(df_display)), index=0, label_visibility="collapsed")
predict_button = st.button("Predict Life Expectancy")
if predict_button:
model = load_model()
if model is not None:
row_to_predict = X_scaled[selected_row_index].reshape(1, -1)
row_tensor = torch.tensor(row_to_predict, dtype=torch.float32)
try:
with torch.no_grad():
prediction = model(row_tensor).item()
colored_subheader("Prediction Results:", "yellow")
colored_text(f"Predicted Life Expectancy: {prediction:.2f} years", "red")
except RuntimeError as e:
st.error(f"Prediction error: {str(e)}")
st.write("Input shape:", row_tensor.shape)
st.write("Expected shape: 1x21")
# Display the selected row with original categorical values
colored_subheader("Selected Row for Prediction:", "yellow")
st.write(df_display.iloc[selected_row_index])
if __name__ == "__main__":
main()
|