File size: 6,819 Bytes
bf715cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

# Aplikasi Streamlit
st.set_page_config(page_title="Regression Analysis App", layout="wide")

# Header Aplikasi
st.title("📈 Regression Analysis App")
st.markdown("""
Upload your dataset, select variables for regression analysis, and gain insights into your data with detailed analysis and interpretation.
""")

# Sidebar: Upload data
st.sidebar.header("📂 Upload Your Data")
uploaded_file = st.sidebar.file_uploader("Upload a CSV file", type=["csv"])

if uploaded_file:
    try:
        # Membaca data
        data = pd.read_csv(uploaded_file)
        st.sidebar.success("Data uploaded successfully!")
        st.write("### Dataset Preview")
        st.dataframe(data)

        # Sidebar: Variable selection
        st.sidebar.header("🔧 Select Variables")
        numeric_cols = data.select_dtypes(include=["float64", "int64"]).columns

        if len(numeric_cols) < 2:
            st.error("Dataset needs at least two numeric columns for regression.")
        else:
            x_var1 = st.sidebar.selectbox("Select X1 (Mandatory)", numeric_cols, key="x1")
            x_var2 = st.sidebar.selectbox("Select X2 (Optional)", ["None"] + list(numeric_cols), key="x2")
            x_var3 = st.sidebar.selectbox("Select X3 (Optional)", ["None"] + list(numeric_cols), key="x3")
            y_var = st.sidebar.selectbox("Select Y (Target Variable)", numeric_cols, key="y")

            # Pastikan setidaknya X1 dan Y dipilih
            if x_var1 and y_var and x_var1 != y_var:
                # Variabel yang dipilih
                selected_features = [x_var1]
                if x_var2 != "None":
                    selected_features.append(x_var2)
                if x_var3 != "None":
                    selected_features.append(x_var3)

                st.write(f"### Regression Analysis: {y_var} vs {', '.join(selected_features)}")

                # Menyiapkan data
                X = data[selected_features].values
                y = data[y_var].values
                X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

                # Model regresi
                model = LinearRegression()
                model.fit(X_train, y_train)
                y_pred = model.predict(X_test)

                # Metrics
                mse = mean_squared_error(y_test, y_pred)
                r2 = r2_score(y_test, y_pred)

                # Menampilkan metrik dalam dua kolom
                col1, col2 = st.columns(2)
                with col1:
                    st.metric("Mean Squared Error (MSE)", f"{mse:.2f}")
                with col2:
                    st.metric("R² Score", f"{r2:.2f}")
                
                # Interpretasi berbasis R² dan MSE
                st.write("#### Analysis Explanation")
                if r2 > 0.8:
                    st.success(f"""
                    The model explains **{r2*100:.2f}%** of the variance in {y_var}.  
                    The low MSE value of **{mse:.2f}** suggests the model predictions are highly accurate.
                    This indicates a **strong relationship** between the independent and dependent variables.
                    """)
                elif 0.5 <= r2 <= 0.8:
                    st.warning(f"""
                    The model explains **{r2*100:.2f}%** of the variance in {y_var}, which is a moderate level.  
                    The MSE of **{mse:.2f}** suggests there is room for improvement in prediction accuracy.
                    Consider exploring additional predictors or non-linear relationships to improve the model.
                    """)
                else:
                    st.error(f"""
                    The model explains only **{r2*100:.2f}%** of the variance in {y_var}.  
                    The high MSE of **{mse:.2f}** indicates significant prediction errors.  
                    This suggests a **weak relationship** between the selected variables, and additional factors should be investigated.
                    """)

                # Menampilkan persamaan regresi
                coefficients = model.coef_
                intercept = model.intercept_
                equation_terms = [f"({coef:.2f} × {var})" for coef, var in zip(coefficients, selected_features)]
                equation = f"{y_var} = {intercept:.2f} + " + " + ".join(equation_terms)

                st.write("#### Regression Equation")
                st.latex(f"{y_var} = {intercept:.2f} + " + " + ".join([f"{coef:.2f}({var})" for coef, var in zip(coefficients, selected_features)]))
                # st.markdown(f"**Equation:** {equation}")

                # Penjelasan persamaan
                st.write("#### How to Interpret the Equation")
                st.markdown(f"""
                - The intercept (**{intercept:.2f}**) is the predicted value of **{y_var}** when all independent variables are zero.
                - Each coefficient represents the expected change in **{y_var}** for a one-unit increase in the respective variable, holding all other variables constant:
                """)
                for var, coef in zip(selected_features, coefficients):
                    st.markdown(f"  - For **{var}**, a one-unit increase leads to a **{coef:.2f}** change in **{y_var}**, assuming other variables remain constant.")

                

                # Scatterplot jika hanya satu X dipilih
                if len(selected_features) == 1:
                    st.write("#### Scatterplot with Regression Line")
                    fig, ax = plt.subplots(figsize=(8, 5))
                    sns.scatterplot(x=data[selected_features[0]], y=data[y_var], ax=ax, label="Data")
                    sns.lineplot(x=data[selected_features[0]], y=model.predict(data[selected_features]), color="red", label="Regression Line", ax=ax)
                    plt.xlabel(selected_features[0])
                    plt.ylabel(y_var)
                    plt.legend()
                    plt.title(f"{y_var} vs {selected_features[0]} with Regression Line")
                    st.pyplot(fig)
                else:
                    st.info("Since multiple independent variables were selected, the regression line cannot be visualized, but the analysis is based on multivariate regression.")
            else:
                st.sidebar.warning("Please select at least one independent variable (X1) and a distinct dependent variable (Y).")
    except Exception as e:
        st.sidebar.error(f"Error reading file: {e}")
else:
    st.info("Awaiting CSV file upload. Please upload a file to proceed.")