import streamlit as st import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error, r2_score # Function for linear regression def perform_linear_regression(X, Y): X = np.array(X).reshape(-1, 1) # Reshape for sklearn Y = np.array(Y) model = LinearRegression() model.fit(X, Y) return model # Streamlit interface st.title("Linear Regression Visualization") st.subheader("Please input vectors X and Y and see the points on the graph") st.subheader("Observe slope and intercept values below") st.subheader("Developed by Dr. Hemprasad Yashwant Patil, SENSE, VIT Vellore") st.subheader("Enter 3 values of X and corresponding Y") # Create two columns col1, col2 = st.columns(2) # Input fields for vectors X and Y in the first column with col1: x_input = st.text_input("X values (comma-separated)", "0, 0, 0") y_input = st.text_input("Y values (comma-separated)", "0, 0, 0") # Parse the input strings into lists of floats try: x_values = [float(val.strip()) for val in x_input.split(",")] y_values = [float(val.strip()) for val in y_input.split(",")] except ValueError: st.write("Please provide valid numeric inputs.") x_values, y_values = [], [] # Proceed only if both vectors are valid and have 3 elements each if len(x_values) == 3 and len(y_values) == 3: model = perform_linear_regression(x_values, y_values) slope = round(model.coef_[0], 2) intercept = round(model.intercept_, 2) st.write(f"Slope: {slope}") st.write(f"Intercept: {intercept}") # Display graph in the second column with col2: plt.figure(figsize=(8, 6)) plt.scatter(x_values, y_values, color='red', label='Data Points') x_range = np.linspace(min(x_values), max(x_values), 100) y_range = slope * x_range + intercept plt.plot(x_range, y_range, color='blue', label='Regression Line') plt.xlabel("X") plt.ylabel("Y") plt.legend() plt.title("Linear Regression Visualization") st.pyplot(plt) # Prompt for a test value of X and predict its corresponding Y test_x_input = st.number_input("Enter a test value for X", value=0.0) # Performance metrics X = np.array(x_values).reshape(-1, 1) Y = np.array(y_values) y_predicted = model.predict(X) mse = mean_squared_error(Y, y_predicted) r2 = r2_score(Y, y_predicted) mse = round(mse, 1) r2 = round(r2, 1) st.write(f"Mean Squared Error: {mse}") st.write(f"R^2 Score: {r2}") if test_x_input: predicted_y = model.predict(np.array([[test_x_input]]))[0] predicted_y = round(predicted_y, 1) st.write(f"Predicted Y for X = {test_x_input} for the above model is {predicted_y}") else: st.write("Please provide valid inputs with 3 values each.")