| | |
| | import streamlit as st |
| | import pandas as pd |
| | import numpy as np |
| | import matplotlib.pyplot as plt |
| | import seaborn as sns |
| | from sklearn.linear_model import LinearRegression |
| | from sklearn.ensemble import RandomForestRegressor |
| | from sklearn.preprocessing import StandardScaler |
| | from sklearn.model_selection import train_test_split |
| |
|
| | |
| | st.set_page_config(page_title="Data Analysis Platform", layout="wide") |
| |
|
| | |
| | if 'data' not in st.session_state: |
| | |
| | np.random.seed(42) |
| | dates = pd.date_range('2023-01-01', periods=100, freq='D') |
| | st.session_state.data = pd.DataFrame({ |
| | 'date': dates, |
| | 'sales': np.random.normal(1000, 200, 100), |
| | 'visitors': np.random.normal(500, 100, 100), |
| | 'conversion_rate': np.random.uniform(0.01, 0.05, 100), |
| | 'customer_satisfaction': np.random.normal(4.2, 0.5, 100), |
| | 'region': np.random.choice(['North', 'South', 'East', 'West'], 100) |
| | }) |
| |
|
| | |
| | st.sidebar.title("Data Analytics Platform") |
| | page = st.sidebar.radio("Navigation", ["Home", "Data Explorer", "Visualization", "Predictions"]) |
| |
|
| | |
| | if page == "Home": |
| | st.title("Data Analysis Platform") |
| | st.markdown(""" |
| | Welcome to the Data Analysis Platform. Explore your data with powerful |
| | visualizations and machine learning insights. |
| | """) |
| | |
| | col1, col2 = st.columns(2) |
| | |
| | with col1: |
| | st.subheader("Upload Your Dataset") |
| | uploaded_file = st.file_uploader("Choose a CSV file", type="csv") |
| | if uploaded_file is not None: |
| | try: |
| | st.session_state.data = pd.read_csv(uploaded_file) |
| | st.success("Data uploaded successfully!") |
| | except Exception as e: |
| | st.error(f"Error uploading file: {e}") |
| | |
| | with col2: |
| | st.subheader("Dataset Overview") |
| | st.write(st.session_state.data.describe()) |
| |
|
| | |
| | elif page == "Data Explorer": |
| | st.title("Data Explorer") |
| | |
| | |
| | st.subheader("Dataset Summary") |
| | st.write(f"Shape: {st.session_state.data.shape[0]} rows, {st.session_state.data.shape[1]} columns") |
| | |
| | |
| | st.subheader("Data Preview") |
| | st.dataframe(st.session_state.data.head()) |
| | |
| | |
| | st.subheader("Column Analysis") |
| | col1, col2 = st.columns(2) |
| | |
| | with col1: |
| | column = st.selectbox("Select column to analyze:", st.session_state.data.columns) |
| | |
| | with col2: |
| | if pd.api.types.is_numeric_dtype(st.session_state.data[column]): |
| | analysis_type = st.selectbox( |
| | "Analysis type:", |
| | ["Distribution", "Time Series"] if "date" in column.lower() else ["Distribution"] |
| | ) |
| | else: |
| | analysis_type = st.selectbox("Analysis type:", ["Value Counts"]) |
| | |
| | |
| | if pd.api.types.is_numeric_dtype(st.session_state.data[column]): |
| | st.write(f"**Min:** {st.session_state.data[column].min():.2f}") |
| | st.write(f"**Max:** {st.session_state.data[column].max():.2f}") |
| | st.write(f"**Mean:** {st.session_state.data[column].mean():.2f}") |
| | st.write(f"**Median:** {st.session_state.data[column].median():.2f}") |
| | st.write(f"**Std Dev:** {st.session_state.data[column].std():.2f}") |
| | |
| | fig, ax = plt.subplots(figsize=(10, 6)) |
| | sns.histplot(st.session_state.data[column], ax=ax, kde=True) |
| | ax.set_title(f"Distribution of {column}") |
| | st.pyplot(fig) |
| | else: |
| | value_counts = st.session_state.data[column].value_counts() |
| | st.write(f"**Unique Values:** {len(value_counts)}") |
| | st.write(f"**Most Common:** {value_counts.index[0]} ({value_counts.iloc[0]} occurrences)") |
| | |
| | fig, ax = plt.subplots(figsize=(10, 6)) |
| | value_counts.plot(kind='bar', ax=ax) |
| | ax.set_title(f"Value counts for {column}") |
| | st.pyplot(fig) |
| |
|
| | |
| | elif page == "Visualization": |
| | st.title("Data Visualization") |
| | |
| | chart_type = st.selectbox( |
| | "Select chart type:", |
| | ["Bar Chart", "Line Chart", "Scatter Plot", "Heatmap"] |
| | ) |
| | |
| | if chart_type in ["Bar Chart", "Line Chart"]: |
| | col1, col2 = st.columns(2) |
| | with col1: |
| | x_column = st.selectbox("X-axis:", st.session_state.data.columns) |
| | with col2: |
| | y_column = st.selectbox("Y-axis:", |
| | [col for col in st.session_state.data.columns |
| | if pd.api.types.is_numeric_dtype(st.session_state.data[col])]) |
| | |
| | |
| | if not pd.api.types.is_numeric_dtype(st.session_state.data[x_column]): |
| | agg_data = st.session_state.data.groupby(x_column)[y_column].mean().reset_index() |
| | |
| | fig, ax = plt.subplots(figsize=(10, 6)) |
| | if chart_type == "Bar Chart": |
| | sns.barplot(x=x_column, y=y_column, data=agg_data, ax=ax) |
| | else: |
| | sns.lineplot(x=x_column, y=y_column, data=agg_data, ax=ax, marker='o') |
| | ax.set_title(f"{y_column} by {x_column}") |
| | st.pyplot(fig) |
| | else: |
| | fig, ax = plt.subplots(figsize=(10, 6)) |
| | if chart_type == "Bar Chart": |
| | sns.barplot(x=x_column, y=y_column, data=st.session_state.data, ax=ax) |
| | else: |
| | sns.lineplot(x=x_column, y=y_column, data=st.session_state.data, ax=ax) |
| | ax.set_title(f"{y_column} vs {x_column}") |
| | st.pyplot(fig) |
| | |
| | elif chart_type == "Scatter Plot": |
| | col1, col2 = st.columns(2) |
| | with col1: |
| | x_column = st.selectbox("X-axis:", |
| | [col for col in st.session_state.data.columns |
| | if pd.api.types.is_numeric_dtype(st.session_state.data[col])]) |
| | with col2: |
| | y_column = st.selectbox("Y-axis:", |
| | [col for col in st.session_state.data.columns |
| | if pd.api.types.is_numeric_dtype(st.session_state.data[col]) and col != x_column]) |
| | |
| | fig, ax = plt.subplots(figsize=(10, 6)) |
| | sns.scatterplot(x=x_column, y=y_column, data=st.session_state.data, ax=ax) |
| | ax.set_title(f"{y_column} vs {x_column}") |
| | st.pyplot(fig) |
| | |
| | elif chart_type == "Heatmap": |
| | numeric_cols = st.session_state.data.select_dtypes(include=['number']).columns.tolist() |
| | correlation = st.session_state.data[numeric_cols].corr() |
| | |
| | fig, ax = plt.subplots(figsize=(10, 8)) |
| | sns.heatmap(correlation, annot=True, cmap='coolwarm', ax=ax) |
| | ax.set_title("Correlation Heatmap") |
| | st.pyplot(fig) |
| |
|
| | |
| | elif page == "Predictions": |
| | st.title("ML Predictions") |
| | |
| | numeric_cols = st.session_state.data.select_dtypes(include=['number']).columns.tolist() |
| | |
| | st.subheader("Train a Model") |
| | col1, col2 = st.columns(2) |
| | |
| | with col1: |
| | target_column = st.selectbox("Target variable:", numeric_cols) |
| | |
| | with col2: |
| | model_type = st.selectbox("Model type:", ["Linear Regression", "Random Forest"]) |
| | |
| | |
| | feature_cols = [col for col in numeric_cols if col != target_column] |
| | selected_features = st.multiselect("Select features:", feature_cols, default=feature_cols) |
| | |
| | if st.button("Train Model"): |
| | if len(selected_features) > 0: |
| | |
| | X = st.session_state.data[selected_features] |
| | y = st.session_state.data[target_column] |
| | |
| | |
| | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) |
| | |
| | |
| | scaler = StandardScaler() |
| | X_train_scaled = scaler.fit_transform(X_train) |
| | X_test_scaled = scaler.transform(X_test) |
| | |
| | |
| | if model_type == "Linear Regression": |
| | model = LinearRegression() |
| | else: |
| | model = RandomForestRegressor(n_estimators=100, random_state=42) |
| | |
| | model.fit(X_train_scaled, y_train) |
| | |
| | |
| | train_score = model.score(X_train_scaled, y_train) |
| | test_score = model.score(X_test_scaled, y_test) |
| | |
| | st.session_state.model = model |
| | st.session_state.scaler = scaler |
| | st.session_state.features = selected_features |
| | |
| | st.success("Model trained successfully!") |
| | st.write(f"Training R² score: {train_score:.4f}") |
| | st.write(f"Testing R² score: {test_score:.4f}") |
| | |
| | |
| | if model_type == "Random Forest": |
| | importance = pd.DataFrame({ |
| | 'Feature': selected_features, |
| | 'Importance': model.feature_importances_ |
| | }).sort_values('Importance', ascending=False) |
| | |
| | fig, ax = plt.subplots(figsize=(10, 6)) |
| | sns.barplot(x='Importance', y='Feature', data=importance, ax=ax) |
| | ax.set_title("Feature Importance") |
| | st.pyplot(fig) |
| | else: |
| | st.error("Please select at least one feature") |
| | |
| | |
| | st.subheader("Make Predictions") |
| | if 'model' in st.session_state: |
| | input_data = {} |
| | |
| | |
| | for feature in st.session_state.features: |
| | min_val = float(st.session_state.data[feature].min()) |
| | max_val = float(st.session_state.data[feature].max()) |
| | mean_val = float(st.session_state.data[feature].mean()) |
| | |
| | input_data[feature] = st.slider( |
| | f"Input {feature}:", |
| | min_value=min_val, |
| | max_value=max_val, |
| | value=mean_val |
| | ) |
| | |
| | if st.button("Predict"): |
| | |
| | input_df = pd.DataFrame([input_data]) |
| | input_scaled = st.session_state.scaler.transform(input_df) |
| | |
| | |
| | prediction = st.session_state.model.predict(input_scaled)[0] |
| | |
| | st.success(f"Predicted {target_column}: {prediction:.2f}") |
| | else: |
| | st.info("Train a model first to make predictions") |