graphmaker / app.py
rioanggara's picture
changes
a6fb37c
raw
history blame
1.65 kB
import gradio as gr
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import io
from PIL import Image
def linear_regression(x_values, y_values):
# Convert string inputs to numpy arrays
X = np.array([float(x) for x in x_values.split(',')]).reshape(-1, 1)
y = np.array([float(y) for y in y_values.split(',')])
# Perform linear regression
model = LinearRegression()
model.fit(X, y)
# Make predictions
y_pred = model.predict(X)
# Plotting
plt.figure(figsize=(10, 6))
plt.scatter(X, y, color='blue')
plt.plot(X, y_pred, color='red')
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.title('Linear Regression')
# Save plot to a buffer and convert to PIL Image
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
image = Image.open(buf)
# Regression info
coef_info = f"Coefficient: {model.coef_[0]}\nIntercept: {model.intercept_}"
return image, coef_info
# Gradio interface
iface = gr.Interface(
fn=linear_regression,
inputs=[
gr.components.Textbox(placeholder="Enter X values separated by commas (e.g., 1,2,3)", label="X Values"),
gr.components.Textbox(placeholder="Enter Y values separated by commas (e.g., 2,4,6)", label="Y Values")
],
outputs=[
gr.components.Image(type="pil"),
gr.components.Textbox(label="Regression Info")
],
title="Automatic Linear Regression Modeling",
description="Enter X and Y values as comma-separated lists to perform linear regression."
)
# Launch the app
if __name__ == "__main__":
iface.launch()