|
|
import streamlit as st |
|
|
import pandas as pd |
|
|
import pickle |
|
|
import seaborn as sns |
|
|
import matplotlib.pyplot as plt |
|
|
from sklearn.model_selection import train_test_split |
|
|
from sklearn.linear_model import LogisticRegression |
|
|
from sklearn.preprocessing import LabelEncoder, StandardScaler |
|
|
from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc |
|
|
from io import StringIO |
|
|
|
|
|
|
|
|
st.set_page_config(page_title="Müşteri Kaybı Tahmin Uygulaması", page_icon=":telephone_receiver:", layout="wide") |
|
|
|
|
|
|
|
|
@st.cache_data() |
|
|
def load_data(): |
|
|
df = pd.read_csv('churn.csv') |
|
|
return df |
|
|
|
|
|
df = load_data() |
|
|
|
|
|
|
|
|
|
|
|
st.title("Müşteri Kaybı Tahmin Uygulaması") |
|
|
|
|
|
|
|
|
st.sidebar.header("Navigasyon") |
|
|
page = st.sidebar.radio("Sayfa Seçin:", ["Veri İnceleme", "Model ve Tahmin"]) |
|
|
|
|
|
|
|
|
if page == "Veri İnceleme": |
|
|
st.header("Veri Seti İnceleme") |
|
|
|
|
|
if st.checkbox("Veri Setini Göster"): |
|
|
st.subheader("Veri Seti") |
|
|
st.dataframe(df) |
|
|
|
|
|
if st.checkbox("Özet İstatistikleri Göster"): |
|
|
st.subheader("Özet İstatistikler") |
|
|
st.write(df.describe()) |
|
|
|
|
|
if st.checkbox("Sütun Bilgilerini Göster"): |
|
|
st.subheader("Sütun Bilgileri") |
|
|
buffer = StringIO() |
|
|
df.info(buf=buffer) |
|
|
s = buffer.getvalue() |
|
|
st.text(s) |
|
|
|
|
|
|
|
|
st.header("Veri Görselleştirme") |
|
|
if st.checkbox("Sayısal Değişken Dağılımları"): |
|
|
st.subheader("Sayısal Değişken Dağılımları") |
|
|
for col in ['tenure', 'MonthlyCharges', 'TotalCharges']: |
|
|
fig, ax = plt.subplots() |
|
|
sns.histplot(df[col], kde=True, ax=ax) |
|
|
st.pyplot(fig) |
|
|
|
|
|
if st.checkbox("Kategorik Değişken Dağılımları"): |
|
|
st.subheader("Kategorik Değişken Dağılımları") |
|
|
for col in ['gender', 'SeniorCitizen', 'Partner', 'Dependents', 'PhoneService', 'MultipleLines', |
|
|
'InternetService', 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', |
|
|
'StreamingTV', 'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod', "Churn"]: |
|
|
fig, ax = plt.subplots() |
|
|
sns.countplot(x=col, data=df, ax=ax) |
|
|
st.pyplot(fig) |
|
|
|
|
|
if st.checkbox("Churn Dağılımı"): |
|
|
st.subheader("Churn Dağılımı") |
|
|
fig, ax = plt.subplots() |
|
|
sns.countplot(x='Churn', data=df, ax=ax) |
|
|
st.pyplot(fig) |
|
|
|
|
|
if st.checkbox("Cinsiyete Göre Churn Dağılımı"): |
|
|
st.subheader("Cinsiyete Göre Churn Dağılımı") |
|
|
fig, ax = plt.subplots() |
|
|
sns.countplot(x='gender', hue='Churn', data=df, ax=ax) |
|
|
st.pyplot(fig) |
|
|
|
|
|
|
|
|
elif page == "Model ve Tahmin": |
|
|
st.header("Müşteri Kaybı Tahmini") |
|
|
|
|
|
|
|
|
df_model = df.copy() |
|
|
|
|
|
|
|
|
|
|
|
df_model['TotalCharges'] = pd.to_numeric(df_model['TotalCharges'], errors='coerce') |
|
|
df_model['TotalCharges'].fillna(df_model['TotalCharges'].median(), inplace=True) |
|
|
|
|
|
|
|
|
label_enc = LabelEncoder() |
|
|
for col in df_model.select_dtypes(include=['object']).columns: |
|
|
if col != 'customerID': |
|
|
df_model[col] = label_enc.fit_transform(df_model[col]) |
|
|
|
|
|
|
|
|
|
|
|
def user_input_features(): |
|
|
features = {} |
|
|
col1, col2 = st.columns(2) |
|
|
|
|
|
|
|
|
df['TotalCharges'] = pd.to_numeric(df['TotalCharges'], errors='coerce') |
|
|
df['TotalCharges'] = df['TotalCharges'].fillna(0) |
|
|
|
|
|
with col1: |
|
|
features['gender'] = st.selectbox("Cinsiyet", df['gender'].unique()) |
|
|
features['SeniorCitizen'] = st.selectbox("Yaşlı Mı?", df['SeniorCitizen'].unique()) |
|
|
features['Partner'] = st.selectbox("Partneri Var Mı?", df['Partner'].unique()) |
|
|
features['Dependents'] = st.selectbox("Bağımlı Kişi Var Mı?", df['Dependents'].unique()) |
|
|
features['PhoneService'] = st.selectbox("Telefon Hizmeti Var Mı?", df['PhoneService'].unique()) |
|
|
|
|
|
|
|
|
if features['PhoneService'] == 'Yes': |
|
|
features['MultipleLines'] = st.selectbox("Çoklu Hat Var Mı?", ['Yes', 'No']) |
|
|
else: |
|
|
features['MultipleLines'] = st.selectbox("Çoklu Hat Var Mı?", ['No phone service']) |
|
|
|
|
|
features['OnlineSecurity'] = st.selectbox("Çevrimiçi Güvenlik Var Mı?", df['OnlineSecurity'].unique()) |
|
|
features['OnlineBackup'] = st.selectbox("Çevrimiçi Yedekleme Var Mı?", df['OnlineBackup'].unique()) |
|
|
|
|
|
with col2: |
|
|
features['DeviceProtection'] = st.selectbox("Cihaz Koruması Var Mı?", df['DeviceProtection'].unique()) |
|
|
features['TechSupport'] = st.selectbox("Teknik Destek Var Mı?", df['TechSupport'].unique()) |
|
|
features['StreamingTV'] = st.selectbox("TV Yayını Var Mı?", df['StreamingTV'].unique()) |
|
|
features['StreamingMovies'] = st.selectbox("Film Yayını Var Mı?", df['StreamingMovies'].unique()) |
|
|
features['Contract'] = st.selectbox("Sözleşme Türü", df['Contract'].unique()) |
|
|
features['PaperlessBilling'] = st.selectbox("Kağıtsız Fatura Var Mı?", df['PaperlessBilling'].unique()) |
|
|
features['PaymentMethod'] = st.selectbox("Ödeme Yöntemi", df['PaymentMethod'].unique()) |
|
|
features['tenure'] = st.slider("Müşteri Olma Süresi (Ay)", 0, 72, 12) |
|
|
features['MonthlyCharges'] = st.slider("Aylık Ücret", 0, 150, 50) |
|
|
features['TotalCharges'] = st.slider("Toplam Ücret", 0, int(df['TotalCharges'].max()), int(df['TotalCharges'].median())) |
|
|
|
|
|
|
|
|
features['InternetService'] = st.selectbox("İnternet Servisi", df['InternetService'].unique()) |
|
|
return pd.DataFrame(features, index=[0]) |
|
|
|
|
|
input_df = user_input_features() |
|
|
|
|
|
|
|
|
|
|
|
X = df_model.drop(columns=['Churn', 'customerID']) |
|
|
y = df_model['Churn'] |
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) |
|
|
|
|
|
scaler = StandardScaler() |
|
|
X_train = scaler.fit_transform(X_train) |
|
|
X_test = scaler.transform(X_test) |
|
|
|
|
|
|
|
|
|
|
|
column_order = X.columns |
|
|
|
|
|
|
|
|
for col in input_df.select_dtypes(include=['object']).columns: |
|
|
input_df[col] = input_df[col].astype(str) |
|
|
|
|
|
for col in input_df.columns: |
|
|
if input_df[col].dtype == object or input_df[col].dtype == str : |
|
|
input_df[col] = pd.Categorical(input_df[col], categories=df[col].unique()) |
|
|
input_df[col] = input_df[col].cat.codes |
|
|
|
|
|
|
|
|
input_df = input_df.reindex(columns=column_order) |
|
|
|
|
|
|
|
|
|
|
|
input_df = scaler.transform(input_df) |
|
|
|
|
|
input_df = pd.DataFrame(input_df, columns=column_order) |
|
|
|
|
|
|
|
|
|
|
|
model = LogisticRegression() |
|
|
model.fit(X_train, y_train) |
|
|
|
|
|
if st.button('Tahmin Yap'): |
|
|
prediction = model.predict(input_df) |
|
|
prediction_proba = model.predict_proba(input_df) |
|
|
|
|
|
st.subheader("Tahmin Sonucu:") |
|
|
if prediction[0] == 0: |
|
|
st.success("Bu müşterinin kayıp **OLMAYACAĞI** tahmin ediliyor. :thumbsup:") |
|
|
else: |
|
|
st.error("Bu müşterinin kayıp **OLACAĞI** tahmin ediliyor. :thumbsdown:") |
|
|
|
|
|
st.subheader("Tahmin Olasılıkları:") |
|
|
st.write(f"Kayıp Olmama Olasılığı: **{prediction_proba[0][0]:.2f}**") |
|
|
st.write(f"Kayıp Olma Olasılığı: **{prediction_proba[0][1]:.2f}**") |
|
|
|
|
|
|
|
|
st.header("Model Performansı") |
|
|
y_pred = model.predict(X_test) |
|
|
|
|
|
st.subheader("Sınıflandırma Raporu") |
|
|
st.text(classification_report(y_test, y_pred)) |
|
|
|
|
|
st.subheader("Karışıklık Matrisi") |
|
|
fig, ax = plt.subplots() |
|
|
sns.heatmap(confusion_matrix(y_test, y_pred), annot=True, fmt='d', cmap='Blues', ax=ax) |
|
|
st.pyplot(fig) |
|
|
|
|
|
st.subheader("ROC Eğrisi") |
|
|
y_prob = model.predict_proba(X_test)[:, 1] |
|
|
fpr, tpr, thresholds = roc_curve(y_test, y_prob) |
|
|
roc_auc = auc(fpr, tpr) |
|
|
|
|
|
fig, ax = plt.subplots() |
|
|
ax.plot(fpr, tpr, color='blue', lw=2, label=f"ROC Curve (AUC = {roc_auc:.2f})") |
|
|
ax.plot([0, 1], [0, 1], color='red', lw=2, linestyle='--') |
|
|
ax.set_xlabel("False Positive Rate") |
|
|
ax.set_ylabel("True Positive Rate") |
|
|
ax.set_title("Receiver Operating Characteristic (ROC) Curve") |
|
|
ax.legend(loc="lower right") |
|
|
st.pyplot(fig) |