V8055/2ndproject
0
1# app.py2import streamlit as st3import numpy as np4import pandas as pd5import matplotlib.pyplot as plt6from sklearn.model_selection import train_test_split7from sklearn.linear_model import LinearRegression8from sklearn.metrics import mean_squared_error, r2_score9import io10import base6411 12def generate_sample_data():13 np.random.seed(42)14 X = np.random.rand(100, 1) * 1015 y = 2 * X + 1 + np.random.randn(100, 1) * 216 return pd.DataFrame({'X': X.flatten(), 'y': y.flatten()})17 18def train_model(df):19 X = df[['X']]20 y = df['y']21 22 # Split the data23 X_train, X_test, y_train, y_test = train_test_split(24 X, y, test_size=0.2, random_state=4225 )26 27 # Create and train the model28 model = LinearRegression()29 model.fit(X_train, y_train)30 31 # Make predictions32 y_train_pred = model.predict(X_train)33 y_test_pred = model.predict(X_test)34 35 return {36 'model': model,37 'X_train': X_train, 'X_test': X_test,38 'y_train': y_train, 'y_test': y_test,39 'y_train_pred': y_train_pred, 'y_test_pred': y_test_pred40 }41 42def plot_regression(results):43 fig, ax = plt.subplots(figsize=(10, 6))44 45 # Plot training data46 ax.scatter(results['X_train'], results['y_train'], 47 color='blue', alpha=0.5, label='Training Data')48 # Plot test data49 ax.scatter(results['X_test'], results['y_test'], 50 color='green', alpha=0.5, label='Test Data')51 52 # Plot regression line53 X_line = np.linspace(0, 10, 100).reshape(-1, 1)54 y_line = results['model'].predict(X_line)55 ax.plot(X_line, y_line, color='red', label='Regression Line')56 57 ax.set_xlabel('X')58 ax.set_ylabel('y')59 ax.set_title('Linear Regression: Training and Test Data with Regression Line')60 ax.legend()61 ax.grid(True, alpha=0.3)62 63 return fig64 65def main():66 st.title("Linear Regression Demo")67 st.write("""68 This app demonstrates simple Linear Regression using scikit-learn.69 You can either use the sample dataset or upload your own CSV file.70 """)71 72 # Data selection73 data_option = st.radio(74 "Choose data source:",75 ("Use sample data", "Upload CSV file")76 )77 78 if data_option == "Use sample data":79 df = generate_sample_data()80 else:81 uploaded_file = st.file_uploader("Choose a CSV file", type="csv")82 if uploaded_file is not None:83 try:84 df = pd.read_csv(uploaded_file)85 if len(df.columns) != 2:86 st.error("Please upload a CSV file with exactly 2 columns (X and y)")87 return88 df.columns = ['X', 'y']89 except Exception as e:90 st.error(f"Error reading file: {str(e)}")91 return92 else:93 st.info("Please upload a CSV file")94 return95 96 # Display sample of the data97 st.subheader("Data Preview")98 st.write(df.head())99 100 # Train model and display results101 results = train_model(df)102 model = results['model']103 104 # Model metrics105 train_mse = mean_squared_error(results['y_train'], results['y_train_pred'])106 test_mse = mean_squared_error(results['y_test'], results['y_test_pred'])107 train_r2 = r2_score(results['y_train'], results['y_train_pred'])108 test_r2 = r2_score(results['y_test'], results['y_test_pred'])109 110 st.subheader("Model Performance Metrics")111 col1, col2 = st.columns(2)112 with col1:113 st.metric("Training MSE", f"{train_mse:.4f}")114 st.metric("Training R²", f"{train_r2:.4f}")115 with col2:116 st.metric("Test MSE", f"{test_mse:.4f}")117 st.metric("Test R²", f"{test_r2:.4f}")118 119 st.write(f"Model Equation: y = {model.coef_[0]:.4f}x + {model.intercept_:.4f}")120 121 # Plot122 st.subheader("Regression Plot")123 fig = plot_regression(results)124 st.pyplot(fig)125 126 # Prediction interface127 st.subheader("Make Predictions")128 x_input = st.number_input("Enter a value for X:", value=5.0)129 prediction = model.predict([[x_input]])[0]130 st.write(f"Predicted y: {prediction:.4f}")131 132if __name__ == "__main__":133 main()134 135 136 137 