File size: 7,736 Bytes
27c8e1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import streamlit as st
import pandas as pd
import numpy as np
import io
from sklearn import datasets

def load_example_data(dataset_name):
    """
    Load example datasets for demonstration
    
    Parameters:
    -----------
    dataset_name : str
        Name of the example dataset to load
        
    Returns:
    --------
    DataFrame: The loaded dataset as a pandas DataFrame
    """
    if dataset_name == "iris":
        data = datasets.load_iris()
        df = pd.DataFrame(data.data, columns=data.feature_names)
        df['species'] = pd.Categorical.from_codes(data.target, data.target_names)
        return df
    
    elif dataset_name == "boston":
        data = datasets.fetch_openml(name='boston', version=1, as_frame=True)
        return data.frame
    
    elif dataset_name == "titanic":
        data = datasets.fetch_openml(name='titanic', version=1, as_frame=True)
        return data.frame
    
    elif dataset_name == "wine":
        data = datasets.load_wine()
        df = pd.DataFrame(data.data, columns=data.feature_names)
        df['wine_type'] = pd.Categorical.from_codes(data.target, data.target_names)
        return df
    
    return None

def display_dataset_info(df):
    """Display information about the dataset."""
    st.subheader("Dataset Information")
    
    # Basic info
    st.markdown(f"**Rows:** {df.shape[0]}")
    st.markdown(f"**Columns:** {df.shape[1]}")
    
    # Missing values
    missing_values = df.isnull().sum().sum()
    st.markdown(f"**Missing Values:** {missing_values}")
    
    # Data types overview
    dtypes = df.dtypes.value_counts().to_dict()
    st.markdown("**Data Types:**")
    for dtype, count in dtypes.items():
        st.markdown(f"- {dtype}: {count} columns")
    
    # Basic statistics
    st.subheader("Summary Statistics")
    
    numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
    if len(numeric_cols) > 0:
        st.dataframe(df[numeric_cols].describe(), use_container_width=True)
    else:
        st.info("No numeric columns found for summary statistics.")

def get_numeric_columns(df):
    """Return list of numeric columns in the dataframe."""
    return df.select_dtypes(include=['int64', 'float64']).columns.tolist()

def get_categorical_columns(df):
    """Return list of categorical columns in the dataframe."""
    return df.select_dtypes(include=['object', 'category', 'bool']).columns.tolist()

def get_datetime_columns(df):
    """Return list of datetime columns in the dataframe."""
    return df.select_dtypes(include=['datetime64']).columns.tolist()

def filter_dataframe(df, column_filters):
    """
    Filter dataframe based on provided filters
    
    Parameters:
    -----------
    df : pandas.DataFrame
        DataFrame to filter
    column_filters : dict
        Dictionary of column names and filter values
    
    Returns:
    --------
    pandas.DataFrame: Filtered dataframe
    """
    filtered_df = df.copy()
    for column, filter_value in column_filters.items():
        if filter_value:
            if column in get_numeric_columns(df):
                min_val, max_val = filter_value
                filtered_df = filtered_df[(filtered_df[column] >= min_val) & 
                                          (filtered_df[column] <= max_val)]
            elif column in get_categorical_columns(df):
                if not isinstance(filter_value, list):
                    filter_value = [filter_value]
                filtered_df = filtered_df[filtered_df[column].isin(filter_value)]
    
    return filtered_df

def download_dataframe(df, filename="data.csv"):
    """
    Generate a download link for the dataframe
    
    Parameters:
    -----------
    df : pandas.DataFrame
        DataFrame to download
    filename : str
        Filename for download
    
    Returns:
    --------
    str: HTML link for download
    """
    csv = df.to_csv(index=False)
    b64 = io.StringIO()
    b64.write(csv)
    return b64.getvalue()

def explain_correlation():
    """Return educational text about correlation."""
    return """
    ### Understanding Correlation
    
    Correlation measures the statistical relationship between two variables. The correlation coefficient ranges from -1 to 1:
    
    - **1**: Perfect positive correlation (as one variable increases, the other increases)
    - **0**: No correlation (variables are not related)
    - **-1**: Perfect negative correlation (as one variable increases, the other decreases)
    
    **Interpreting correlation strength:**
    - 0.00-0.19: Very weak
    - 0.20-0.39: Weak
    - 0.40-0.59: Moderate
    - 0.60-0.79: Strong
    - 0.80-1.00: Very strong
    
    **Important note:** Correlation does not imply causation. Two variables may be correlated without one causing the other.
    """

def explain_hypothesis_testing():
    """Return educational text about hypothesis testing."""
    return """
    ### Understanding Hypothesis Testing
    
    Hypothesis testing is a statistical method to make decisions about a population based on sample data.
    
    **Key components:**
    
    1. **Null hypothesis (H₀)**: Assumes no effect or no difference (status quo)
    2. **Alternative hypothesis (H₁)**: Contradicts the null hypothesis
    3. **p-value**: Probability of observing results at least as extreme as the current data, assuming H₀ is true
    4. **Significance level (α)**: Threshold for rejecting H₀ (commonly 0.05)
    
    **Decision rule:** If p-value < α, reject H₀
    
    **Common tests:**
    - **t-test**: Compares means between groups
    - **ANOVA**: Compares means across multiple groups
    - **Chi-square**: Tests relationships between categorical variables
    """

def explain_data_cleaning():
    """Return educational text about data cleaning."""
    return """
    ### Data Cleaning Basics
    
    Data cleaning is an essential step in the data science workflow. Clean data leads to more accurate analysis and models.
    
    **Common data issues:**
    
    1. **Missing values**: Data points that are not recorded
    2. **Duplicates**: Identical records that can skew analysis
    3. **Outliers**: Extreme values that may or may not represent errors
    4. **Inconsistent formats**: Dates, currencies, or text in different formats
    5. **Data type issues**: Numbers stored as text, etc.
    
    **Common cleaning approaches:**
    
    - **Missing data**: Remove or impute with mean, median, or predicted values
    - **Outliers**: Remove, transform, or analyze separately
    - **Standardization**: Convert data to consistent formats and scales
    """

def explain_machine_learning():
    """Return educational text about machine learning basics."""
    return """
    ### Machine Learning Fundamentals
    
    Machine learning algorithms learn patterns from data to make predictions or decisions without being explicitly programmed.
    
    **Main types of machine learning:**
    
    1. **Supervised Learning**: Learn from labeled data to predict outcomes
       - **Classification**: Predict categories (e.g., spam detection)
       - **Regression**: Predict continuous values (e.g., house prices)
    
    2. **Unsupervised Learning**: Find patterns in unlabeled data
       - **Clustering**: Group similar data points (e.g., customer segmentation)
       - **Dimensionality Reduction**: Simplify data while preserving information
    
    3. **Reinforcement Learning**: Learn through trial and error with rewards/penalties
    
    **Machine Learning Workflow:**
    1. Data preparation (cleaning, feature engineering)
    2. Model selection and training
    3. Evaluation (using metrics like accuracy, precision, recall)
    4. Deployment and monitoring
    """