Articles → SKLEARN → Linear Regression In Sklearn

Linear Regression In Sklearn






Code


import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Step 1: Prepare the data
# Heights (independent variable) and Weights (dependent variable)
X = np.array([150, 160, 170]).reshape(-1, 1)  # reshape for sklearn
y = np.array([50, 56, 63])

# Step 2: Create the model
model = LinearRegression()

# Step 3: Train the model (fit)
model.fit(X, y)

# Step 4: Make predictions
y_pred = model.predict(X)

# Step 5: Print slope and intercept
print(f"Slope (m): {model.coef_[0]:.2f}")
print(f"Intercept (c): {model.intercept_:.2f}")

# Step 6: Plotting the results
plt.scatter(X, y, color='blue', label='Actual data')
plt.plot(X, y_pred, color='red', linewidth=2, label='Regression line')
plt.title('Linear Regression: Height vs Weight')
plt.xlabel('Height (cm)')
plt.ylabel('Weight (kg)')
plt.legend()
plt.grid(True)
plt.show()



Output


Picture showing the output of Linear Regression In Sklearn



Posted By  -  Karan Gupta
 
Posted On  -  Sunday, May 25, 2025

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250