import streamlit as st
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
# Set up the main app
def main():
st.title("Advanced Data Analysis App with Outlier Detection")
st.write("""
This app allows you to upload your dataset, perform exploratory data analysis,
visualize your data, and detect outliers using advanced methods.
""")
# Sidebar for navigation
st.sidebar.title("Navigation")
options = ["Upload Data", "EDA", "Visualization", "Outlier Detection"]
choice = st.sidebar.selectbox("Select Option", options)
# Upload Data Section
if choice == "Upload Data":
st.subheader("Upload Your Dataset")
data_file = st.file_uploader("Upload CSV", type=['csv'])
if data_file is not None:
df = load_data(data_file)
st.success("Data Loaded Successfully!")
st.dataframe(df.head())
save_data(df)
else:
st.info("Awaiting for CSV file to be uploaded.")
# Exploratory Data Analysis
elif choice == "EDA":
st.subheader("Exploratory Data Analysis")
df = get_data()
if df is not None:
numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
st.write("**Shape of the dataset:**", df.shape)
st.write("**Summary Statistics:**")
st.write(df.describe())
st.write("**Missing Values:**")
st.write(df.isnull().sum())
else:
st.warning("No data available. Please upload a dataset.")
# Data Visualization
elif choice == "Visualization":
st.subheader("Data Visualization")
df = get_data()
if df is not None:
all_columns = df.columns.tolist()
viz_type = st.selectbox("Select Visualization Type",
["Histogram", "Box Plot", "Correlation Matrix"])
if viz_type == "Histogram":
column = st.selectbox("Select Column", all_columns)
plt.figure(figsize=(10, 4))
sns.histplot(df[column], kde=True)
st.pyplot(plt)
elif viz_type == "Box Plot":
column = st.selectbox("Select Column", all_columns)
plt.figure(figsize=(10, 4))
sns.boxplot(df[column])
st.pyplot(plt)
elif viz_type == "Correlation Matrix":
corr = df.corr()
plt.figure(figsize=(10, 8))
sns.heatmap(corr, annot=True, cmap='coolwarm')
st.pyplot(plt)
else:
st.warning("No data available. Please upload a dataset.")
# Outlier Detection
elif choice == "Outlier Detection":
st.subheader("Outlier Detection Methods")
df = get_data()
if df is not None:
method = st.selectbox("Select Method",
["Z-score Method", "IQR Method",
"Isolation Forest", "Local Outlier Factor"])
if method == "Z-score Method":
z_score_outliers(df)
elif method == "IQR Method":
iqr_outliers(df)
elif method == "Isolation Forest":
isolation_forest_outliers(df)
elif method == "Local Outlier Factor":
local_outlier_factor_outliers(df)
else:
st.warning("No data available. Please upload a dataset.")
# Function to load data
@st.cache_data
def load_data(data_file):
df = pd.read_csv(data_file)
return df
# Function to save data in session state
def save_data(df):
st.session_state['df'] = df
# Function to retrieve data from session state
def get_data():
if 'df' in st.session_state:
return st.session_state['df']
else:
return None
# Z-score Method for Outlier Detection
def z_score_outliers(df):
st.write("**Z-score Method**")
threshold = st.slider("Select Z-score Threshold", 0.0, 5.0, 3.0)
numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
col = st.selectbox("Select Column", numeric_cols)
z_scores = stats.zscore(df[col])
abs_z_scores = np.abs(z_scores)
outlier_indices = np.where(abs_z_scores > threshold)
st.write(f"Number of outliers detected: {len(outlier_indices[0])}")
st.write("Outlier Data Points:")
st.dataframe(df.iloc[outlier_indices])
# IQR Method for Outlier Detection
def iqr_outliers(df):
st.write("**IQR Method**")
numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
col = st.selectbox("Select Column", numeric_cols)
Q1 = df[col].quantile(0.25)
Q3 = df[col].quantile(0.75)
IQR = Q3 - Q1
st.write(f"Q1: {Q1}, Q3: {Q3}, IQR: {IQR}")
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
outliers = df[(df[col] < lower_bound) | (df[col] > upper_bound)]
st.write(f"Number of outliers detected: {outliers.shape[0]}")
st.write("Outlier Data Points:")
st.dataframe(outliers)
# Isolation Forest Method for Outlier Detection
def isolation_forest_outliers(df):
st.write("**Isolation Forest Method**")
contamination = st.slider("Select Contamination Fraction", 0.0, 0.5, 0.05)
numeric_df = df.select_dtypes(include=np.number)
iso_forest = IsolationForest(contamination=contamination, random_state=42)
preds = iso_forest.fit_predict(numeric_df)
df['anomaly'] = preds
outliers = df[df['anomaly'] == -1]
st.write(f"Number of outliers detected: {outliers.shape[0]}")
st.write("Outlier Data Points:")
st.dataframe(outliers.drop('anomaly', axis=1))
# Local Outlier Factor Method for Outlier Detection
def local_outlier_factor_outliers(df):
st.write("**Local Outlier Factor Method**")
n_neighbors = st.slider("Select Number of Neighbors", 5, 50, 20)
contamination = st.slider("Select Contamination Fraction", 0.0, 0.5, 0.05)
numeric_df = df.select_dtypes(include=np.number)
lof = LocalOutlierFactor(n_neighbors=n_neighbors, contamination=contamination)
preds = lof.fit_predict(numeric_df)
df['anomaly'] = preds
outliers = df[df['anomaly'] == -1]
st.write(f"Number of outliers detected: {outliers.shape[0]}")
st.write("Outlier Data Points:")
st.dataframe(outliers.drop('anomaly', axis=1))
if __name__ == "__main__":
main()