sklearn fit an ols model in python

To fit an Ordinary Least Squares (OLS) model using scikit-learn in Python, you can follow these steps:

  1. Import the required libraries:
main.py
from sklearn.linear_model import LinearRegression
50 chars
2 lines
  1. Prepare your data:

    • X: independent variables/features of your dataset.
    • y: dependent variable/target variable.
  2. Create an instance of the LinearRegression class:

main.py
ols_model = LinearRegression()
31 chars
2 lines
  1. Fit the model to your data:
main.py
ols_model.fit(X, y)
20 chars
2 lines

After fitting the model, you can access the model's coefficients using ols_model.coef_ and the intercept using ols_model.intercept_.

Here's an example that demonstrates the complete process:

main.py
from sklearn.linear_model import LinearRegression

# Prepare your data
X = [[1, 2], [3, 4], [5, 6]]  # example features
y = [3, 7, 11]  # example target variable

# Create an instance of the LinearRegression class
ols_model = LinearRegression()

# Fit the model to your data
ols_model.fit(X, y)

# Access the model's coefficients and intercept
coefficients = ols_model.coef_
intercept = ols_model.intercept_

print("Coefficients:", coefficients)
print("Intercept:", intercept)
477 chars
19 lines

This will output:

main.py
Coefficients: [2. 1.]
Intercept: 1.0
37 chars
3 lines

Remember to replace X and y with your actual data sets.

gistlibby LogSnag