DeepSoft-Tech commited on
Commit
1bc657d
·
verified ·
1 Parent(s): 93ba0f1

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +84 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,86 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import seaborn as sns
6
+ import joblib
7
+ from sklearn.ensemble import RandomForestClassifier
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.metrics import classification_report, accuracy_score
10
+
11
+ MODEL_FILENAME = "insurance_churn_model.pkl"
12
+
13
+ st.title("Insurance Churn Prediction App")
14
+
15
+ menu = st.sidebar.radio("Navigation", ["Train Model", "Predict Churn"])
16
+
17
+ if menu == "Train Model":
18
+ st.header("Upload Dataset and Train Model")
19
+ uploaded_file = st.file_uploader("Upload Insurance Churn Dataset (CSV)", type=["csv"])
20
+
21
+ if uploaded_file is not None:
22
+ data = pd.read_csv(uploaded_file)
23
+ st.subheader("Dataset Preview")
24
+ st.dataframe(data.head())
25
+
26
+ st.subheader("Summary Statistics")
27
+ st.write(data.describe())
28
+
29
+ if 'churn' in data.columns:
30
+ st.subheader("Churn Distribution")
31
+ fig, ax = plt.subplots()
32
+ sns.countplot(x='churn', data=data, ax=ax)
33
+ st.pyplot(fig)
34
+
35
+ st.subheader("Model Training")
36
+ target_column = st.selectbox("Select Target Column", options=data.columns, index=data.columns.get_loc('churn') if 'churn' in data.columns else 0)
37
+ feature_columns = st.multiselect("Select Feature Columns", options=[col for col in data.columns if col != target_column])
38
+
39
+ if feature_columns and target_column:
40
+ X = pd.get_dummies(data[feature_columns])
41
+ y = data[target_column]
42
+
43
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
44
+
45
+ model = RandomForestClassifier()
46
+ model.fit(X_train, y_train)
47
+
48
+ y_pred = model.predict(X_test)
49
+ st.subheader("Model Performance")
50
+ st.write("Accuracy:", accuracy_score(y_test, y_pred))
51
+ st.text("Classification Report:")
52
+ st.text(classification_report(y_test, y_pred))
53
+
54
+ joblib.dump((model, X.columns.tolist()), MODEL_FILENAME)
55
+ st.success(f"Model trained and saved as {MODEL_FILENAME}")
56
+
57
+ elif menu == "Predict Churn":
58
+ st.header("Insurance Churn Predictor")
59
+
60
+ try:
61
+ model, feature_names = joblib.load(MODEL_FILENAME)
62
+ st.success("Model loaded successfully.")
63
+ except:
64
+ st.error("Model not found. Please train the model first.")
65
+ st.stop()
66
+
67
+ st.subheader("Enter Customer Details")
68
+ input_data = {}
69
+ for feature in feature_names:
70
+ input_data[feature] = st.text_input(f"{feature}", "")
71
+
72
+ if st.button("Predict Churn"):
73
+ try:
74
+ input_df = pd.DataFrame([input_data])
75
+ input_df = pd.get_dummies(input_df)
76
+
77
+ for col in feature_names:
78
+ if col not in input_df.columns:
79
+ input_df[col] = 0
80
+ input_df = input_df[feature_names]
81
 
82
+ prediction = model.predict(input_df)[0]
83
+ st.subheader("Prediction Result")
84
+ st.write(f"Churn: {'Yes' if prediction == 1 else 'No'}")
85
+ except Exception as e:
86
+ st.error(f"Error in prediction: {e}")