33. Linear Regression in Python with sklearn
33.3 Copy-Run LinearRegression on Fictional Rent
Why. Reading about lines is not enough. You need a short copy-run path: build X and y, split, fit, predict.
What. sklearn.linear_model.LinearRegression learns intercept_ and coef_ from training data. You then call predict on new rows.
How.
Fit a first rent model (fictional)
- Make a small DataFrame of area_sqft and rent_inr.
- Form X (features) and y (label).
- Use train_test_split (Chapter 31 habit).
- Fit LinearRegression on the train set only.
- Predict on the held-out test rows and print guesses vs truth.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
df = pd.DataFrame({
"area_sqft": [450, 520, 600, 680, 750, 820, 900, 980, 1050, 1200],
"rent_inr": [11800, 13200, 15000, 16800, 18500, 20200, 22000, 23800, 25500, 29000],
})
X = df[["area_sqft"]]
y = df["rent_inr"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42
)
model = LinearRegression()
model.fit(X_train, y_train)
preds = model.predict(X_test)
print("Test areas:\n", X_test.values.ravel())
print("True rent:", y_test.values)
print("Pred rent:", preds.round(0))
What you should see. Predicted rents near the true ones on this clean toy set. Real city data is noisier — that is fine; Chapter 37 teaches how to score models properly.
Fictional data
These rents are invented for a classroom notebook, not scraped listings.