Online Statsmodels Compiler

Python statsmodels example for performing linear regression

Python
# Performing simple linear regression with statsmodels

import numpy as np
import statsmodels.api as sm

# Sample data: Hours studied and Exam scores
hours_studied = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
exam_scores = np.array([51, 55, 60, 68, 72, 75, 78, 82, 85, 88, 90, 92, 94, 96, 97, 98, 99, 100, 101, 102])

# Adding a constant for the intercept term
X = sm.add_constant(hours_studied)

# Creating the model
model = sm.OLS(exam_scores, X)

# Fitting the model
results = model.fit()

# Making predictions
hours = 10  # Predicting the exam score for someone who studied 10 hours
predicted_score = results.predict([1, hours])  # The first element is the constant term
print(f"Predicted exam score for someone who studied {hours} hours: {predicted_score[0]}\n")

# Printing the summary of the model
print(results.summary())
CTRL + ENTER to send