Reading history

Robust Regression with Huber and RANSAC

6 min read 1 views

Learn robust regression in Python: see how outliers break linear regression and fix it with HuberRegressor and RANSACRegressor.

One typing mistake, such as an extra zero in a rent value, can drag an ordinary regression line far away from the truth. Robust regression methods are built to resist such outliers. In this lesson you will break a linear regression with five bad rows, then fix it with HuberRegressor and RANSACRegressor.

In this lesson you will learn

  • Why squared error makes linear regression sensitive to outliers
  • How the Huber loss limits the pull of large errors
  • How RANSAC finds a line using only trusted points
  • How to find which rows were treated as outliers
  • Which method to choose for different kinds of bad data

You should know linear regression and MAE and MSE.

Why Outliers Pull So Hard

Ordinary linear regression picks the line with the smallest squared error. Squaring makes big errors count far more than small ones. An error of 10 counts as 100, and an error of 50 counts as 2,500. So the line will bend a lot just to get a little closer to one wild point.

Our data has 40 flats. The true rule is rent = 15 x size + 2,000 taka. Then we multiply five rents by 10, as if someone typed an extra zero.

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, HuberRegressor, RANSACRegressor

# Flat size (square feet) vs monthly rent (taka). True rule: rent = 15 * size + 2000
rng = np.random.default_rng(3)
size = rng.uniform(500, 1500, 40)
rent = 15 * size + 2000 + rng.normal(0, 1500, 40)

# Five typing mistakes: an extra zero was added to the rent of 5 random flats
bad = rng.choice(40, 5, replace=False)
rent[bad] *= 10
X = size.reshape(-1, 1)

models = {
    "LinearRegression": LinearRegression(),
    "HuberRegressor": HuberRegressor(max_iter=1000),
    "RANSACRegressor": RANSACRegressor(random_state=0),
}
test = np.array([[800], [1200]])
print(f"{'model':<17} rent@800  rent@1200")
print(f"{'true rule':<17} {15*800+2000:>8} {15*1200+2000:>9}")
for name, m in models.items():
    pipe = make_pipeline(StandardScaler(), m).fit(X, rent)   # Huber needs scaled inputs
    p = pipe.predict(test)
    print(f"{name:<17} {p[0]:>8.0f} {p[1]:>9.0f}")

ransac = make_pipeline(StandardScaler(), RANSACRegressor(random_state=0)).fit(X, rent)
print("RANSAC outlier rows:", np.where(~ransac[-1].inlier_mask_)[0])
print("rows we corrupted  :", np.sort(bad))

Output

model             rent@800  rent@1200
true rule            14000     20000
LinearRegression     24953     53431
HuberRegressor       13964     20404
RANSACRegressor      13770     19761
RANSAC outlier rows: [11 14 18 22 33]
rows we corrupted  : [11 14 18 22 33]
5007501,0001,2501,5000k50k100k150k200k250kFlat size (square feet)Rent (taka)5 rows with an extra zeroLinearRegressionHuberRegressor (dashed)RANSACRegressor
  • Plain linear regression is badly off. For a 1,200 square foot flat it predicts about 53,000 taka instead of 20,000.
  • Huber and RANSAC both land close to the true rule, even though 1 row in 8 is wrong.
  • RANSAC also tells us which rows it ignored, and they are exactly the five rows we broke.
  • We put a StandardScaler in front of each model. HuberRegressor in particular can stop early and give a poor answer if the inputs are on a large scale.

Huber: Squared for Small Errors, Straight for Big Ones

The Huber loss is a mix of two losses. For small errors it behaves like squared error, which is smooth and precise. Past a limit called epsilon (1.35 by default, measured in units of the typical error), it grows in a straight line instead. A huge error then pulls only a bit harder than a medium one.

# Squared loss vs Huber loss for errors of different sizes (epsilon = 1.35)
eps = 1.35
print("error   squared   huber")
for e in (0.5, 1, 2, 5, 10, 50):
    sq = e ** 2
    hub = e ** 2 if abs(e) <= eps else 2 * eps * abs(e) - eps ** 2
    print(f"{e:>5} {sq:>9.1f} {hub:>7.1f}")

Output

error   squared   huber
  0.5       0.2     0.2
    1       1.0     1.0
    2       4.0     3.6
    5      25.0    11.7
   10     100.0    25.2
   50    2500.0   133.2

An error of 50 costs 2,500 under squared loss but only about 133 under Huber. That is why one bad row cannot take over the fit. After fitting, huber.outliers_ marks the rows that fell into the straight-line part.

RANSAC: Fit on a Trusted Subset

RANSAC stands for RANdom SAmple Consensus. It works like this:

  1. Pick a small random subset of points and fit a line to them.
  2. Count how many points lie close to that line. These are the inliers.
  3. Repeat many times and keep the line with the most inliers.
  4. Refit the final model on those inliers only.

Outliers simply never get a vote in the final fit. You can read inlier_mask_ to see which rows were kept.

Outliers at the Edge

A point far out at the edge of the inputs has more leverage: it can tilt the line like a long lever. Here the five mistakes are on the five biggest flats.

import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression, HuberRegressor, RANSACRegressor

rng = np.random.default_rng(3)
size = rng.uniform(500, 1500, 40)
rent = 15 * size + 2000 + rng.normal(0, 1500, 40)
X = size.reshape(-1, 1)

# Harder case: the mistakes are on the 5 BIGGEST flats, at the edge of the data
bad = np.argsort(size)[-5:]
rent[bad] *= 10

test = np.array([[800], [1200]])
print(f"{'model':<17} rent@800  rent@1200")
print(f"{'true rule':<17} {14000:>8} {20000:>9}")
for name, m in [("LinearRegression", LinearRegression()),
                ("HuberRegressor", HuberRegressor(max_iter=1000)),
                ("RANSACRegressor", RANSACRegressor(random_state=0))]:
    p = make_pipeline(StandardScaler(), m).fit(X, rent).predict(test)
    print(f"{name:<17} {p[0]:>8.0f} {p[1]:>9.0f}")

Output

model             rent@800  rent@1200
true rule            14000     20000
LinearRegression     13083     79577
HuberRegressor       13693     20975
RANSACRegressor      13731     19611
  • Plain regression is wrecked: about 80,000 taka for a 1,200 square foot flat.
  • Huber is much better but a little high at 1,200, because the edge points still have some pull.
  • RANSAC is closest, because the edge points are thrown out completely.

Which One to Use?

MethodGood forWatch out for
LinearRegressionClean dataAny outlier
HuberRegressorA few outliers in the targetNeeds scaled inputs; edge outliers still pull
RANSACRegressorMany or extreme outliersRandom results; needs a sensible residual_threshold
QuantileRegressorPredicting the medianSlower on big data

For the median approach, see quantile regression.

Common Mistakes

  1. Deleting outliers by hand without checking them. Some “outliers” are real and important. Look at the rows first, then decide.
  2. Judging the fit by R squared on dirty data. The outliers also spoil the score. Compare predictions on clean, trusted rows.
  3. Forgetting to scale inputs for Huber. Put a StandardScaler in the pipeline.
  4. Not fixing a random state for RANSAC. Without it, the line can change from run to run.

Practice Exercises

Exercise 1. Using the Huber formula with epsilon 1.35, why does an error of 1 cost the same under both losses?

Show answer

1 is smaller than epsilon (1.35), so the Huber loss is still in its squared part. Both losses give 1 x 1 = 1. The two only differ once the error passes 1.35.

Exercise 2. In rr1.py, corrupt 20 rows instead of 5. Which model would you expect to fail first, and why?

Show answer

Huber fails first. With 15 bad rows it already predicts over 50,000 taka for an 800 square foot flat, because the outliers together outweigh the good rows. RANSAC still holds at 15. At 20 bad rows it fails too: the bad rows all follow the same “times 10” line, so they form a group as big as the good rows, and RANSAC picks the wrong group. No method can save data when the mistakes outnumber or match the good rows.

Frequently Asked Questions

What is robust regression?

Robust regression is any regression method designed so that a few bad rows cannot pull the model far from the true pattern. Huber regression and RANSAC are two common examples.

Should I remove outliers or use robust regression?

If you know a row is a mistake, fix or remove it. If you cannot check every row, a robust method protects you automatically and also shows which rows look suspicious.

Summary

  • Squared error lets a few large mistakes control a linear regression.
  • Huber loss grows in a straight line for big errors, so outliers pull less.
  • RANSAC fits on the largest group of points that agree and ignores the rest.
  • Edge outliers have high leverage; RANSAC handles them best.

Next: Topic Modelling with NMF and LDA.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *