there are a few different methods. Lets take a look at them.
This is probably the simplest to implement.
import numpy as np
# Create some sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 4, 5, 6]
# Compute the line of best fit
coefficients = np.polyfit(x, y, 1)
# Print the coefficients
print(coefficients)
This will output a NumPy array of coefficients that represent the line of best fit. The first element of the array is the y-intercept and the second element is the slope of the line.
One can use the LinearRegression class from scikit-learn to compute the line of best fit.
from sklearn.linear_model import LinearRegression
# Create some sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 4, 5, 6]
# Convert lists to 2D arrays
x = [[i] for i in x]
y = [[i] for i in y]
# Create a linear regression model
model = LinearRegression()
# Fit the model to the data
model.fit(x, y)
# Print the coefficients
print(model.intercept_)
print(model.coef_)
This will output the y-intercept and the slope of the line.
One can use the statsmodels.regression.linear_model.OLS (Ordinary Least Squares) class to perform linear regression and get the intercept and slope.
import statsmodels.api as sm
# Create some sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 4, 5, 6]
# Add a column of 1s to the x data to include the intercept term
x = sm.add_constant(x)
# Create an OLS model
model = sm.OLS(y, x)
# Fit the model
results = model.fit()
# Print the coefficients
print(results.params)
This will output an array of coefficients that represent the line of best fit. The first element of the array is the y-intercept and the second element is the slope of the line.