Skip to content

[WIP] Adding Local Regression (Fixes #3075) - #19854

Closed
niknow wants to merge 2 commits into
scikit-learn:mainfrom
niknow:local_regression
Closed

niknow wants to merge 2 commits into
scikit-learn:mainfrom
niknow:local_regression

Conversation

@niknow

@niknow niknow commented Apr 9, 2021

Copy link
Copy Markdown

Reference Issues/PRs

Fixes #3075

What does this implement/fix? Explain your changes.

The above issue is that local regression is missing in scikit-learn. This PR addresses this issue by adding an implementation of local regression and expanding the test suite to cover this.

Any other comments?

@haiatn

haiatn commented Jul 29, 2023 •

Copy link
Copy Markdown
Contributor

It would be great if you update your PR to master. Is there anything more you wish to do before making it ready for review?

@adrinjalali

Copy link
Copy Markdown
Member

closing due to inactivity.

@niknow

niknow commented Jul 30, 2023 •

Copy link
Copy Markdown
Author

@adrinjalali Sorry, I just saw @haiatn message this morning asking me to update to master. I've just done that and happy to engage with the reviewers.

@adrinjalali adrinjalali reopened this Jul 30, 2023
@adrinjalali

Copy link
Copy Markdown
Member

@agramfort do you think this should still be included?

@github-actions

github-actions Bot commented Jul 30, 2023 •

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


black

black detected issues. Please run black . locally and push the changes. Here you can see the detected issues. Note that running black might also fix some of the issues which might be detected by ruff. Note that the installed black version is black=23.3.0.

Details

--- /home/runner/work/scikit-learn/scikit-learn/sklearn/linear_model/_local.py	2023-07-30 19:18:48.638674 +0000
+++ /home/runner/work/scikit-learn/scikit-learn/sklearn/linear_model/_local.py	2023-07-30 19:19:10.496526 +0000
@@ -79,34 +79,42 @@
             self.fitted_kernel = None
             self.method = None
         return self._predict_with_method(X, method)
 
     def fit_partial(self, y, bandwidth=None):
-        """ Re-fits only the y values of the regression. Only works if
-            warm_start==True and a previous (full) fit and predict
-            has already been performed.
-        """
-        if self.warm_start and self.fitted_kernel is not None and self.method in ['analytic', 'qr']:
+        """Re-fits only the y values of the regression. Only works if
+        warm_start==True and a previous (full) fit and predict
+        has already been performed.
+        """
+        if (
+            self.warm_start
+            and self.fitted_kernel is not None
+            and self.method in ["analytic", "qr"]
+        ):
             self.y_train = y
             self._set_bandwidth(bandwidth)
         else:
-            raise ValueError("The fit_partial method can only be invoked\
-                if fit and predict have been invoked previously with method \
-                    `analytic´ or `qr` and warm_start is set to True")
+            raise ValueError(
+                "The fit_partial method can only be invoked                if fit and"
+                " predict have been invoked previously with method                    "
+                " `analytic´ or `qr` and warm_start is set to True"
+            )
 
     def predict_partial(self):
-        """ Predicts on the last value of y_train set by fit() or fit_partial()
-            and the last X that has been used for prediction. """
+        """Predicts on the last value of y_train set by fit() or fit_partial()
+        and the last X that has been used for prediction."""
         if self.fitted_kernel is not None and self.method is not None:
             return self._predict_with_method(X=None, method=self.method)
         else:
-            raise ValueError("The method predict_partial requires a full\
-                              prior run of predict with method `analytic´ \
-                              or `qr´.")
+            raise ValueError(
+                "The method predict_partial requires a full                            "
+                "  prior run of predict with method `analytic´                         "
+                "      or `qr´."
+            )
 
     def _set_bandwidth(self, bandwidth):
-        """ Sets the bandwidth in the fitting."""
+        """Sets the bandwidth in the fitting."""
         if bandwidth is None:
             self.bandwidth = self._silverman()
         else:
             self.bandwidth = bandwidth
 
@@ -130,45 +138,49 @@
         :return: scaled kernel function
         """
 
         def kh(z):
             d = self.X_train_.shape[1]
-            return self.kernel(z / self.bandwidth) / self.bandwidth ** d
+            return self.kernel(z / self.bandwidth) / self.bandwidth**d
 
         return kh
 
     def _predict_with_method(self, X, method):
-        """ Performs the prediction based on the `method´ flag.
+        """Performs the prediction based on the `method´ flag.
         :param method: a string chosen from 'analytic', 'leastsq', 'qr'
         """
         self.method = method
         num_dims = self.X_train_.shape[1]
-        if method == 'analytic':
+        if method == "analytic":
             if self.degree == 0:
                 return self._predict_nadaraya_watson(X)
             elif num_dims == 1 and self.degree == 1:
                 return self._predict_locally_linear(X)
             else:
-                raise ValueError('Method `analytic´ is only available if \
-                                  self.degree=0 or self.degree=1 and X.shape[1] == 1.')
-        elif method == 'qr':
+                raise ValueError(
+                    "Method `analytic´ is only available if                            "
+                    "       self.degree=0 or self.degree=1 and X.shape[1] == 1."
+                )
+        elif method == "qr":
             return self._predict_qr(X)
-        elif method == 'leastsq':
+        elif method == "leastsq":
             return self._predict_leastsq(X)
         else:
-            raise ValueError('Parameter `method´ has to be `analytic´ or\
-                `qr´ or `leastsq´ or None, but is currently set to: %s' % method)
+            raise ValueError(
+                "Parameter `method´ has to be `analytic´ or                `qr´ or"
+                " `leastsq´ or None, but is currently set to: %s" % method
+            )
 
     def _determine_method(self):
-        """ Automatically selects the method for prediction based on the dimension
-            of the training data self_X_train_.
+        """Automatically selects the method for prediction based on the dimension
+        of the training data self_X_train_.
         """
         num_dims = self.X_train_.shape[1]
         if self.degree == 0 or (self.degree == 1 and num_dims == 1):
-            return 'analytic'
-        else:
-            return 'qr'
+            return "analytic"
+        else:
+            return "qr"
 
     def _predict_nadaraya_watson(self, X):
         """
         Performs local regression of degree $p=0$ in dimension $d=1$.
         In this case, the cost functional can be minimized analytically
@@ -209,11 +221,11 @@
                 x = X[i]
                 llk = k_h(x - self.X_train_).squeeze()
                 s0 = np.mean(llk)
                 s1 = np.mean((x - X_) * llk)
                 s2 = np.mean((x - X_) ** 2 * llk)
-                s = (s2 - s1 * (x - X_)) / (s2 * s0 - s1 ** 2) / n
+                s = (s2 - s1 * (x - X_)) / (s2 * s0 - s1**2) / n
                 self.fitted_kernel[i, :] = s * llk
         return np.sum(self.fitted_kernel * self.y_train.squeeze(), axis=1)
 
     def _predict_qr(self, X):
         """
@@ -232,11 +244,11 @@
                 m = phi.shape[1]
                 kh = self._scaled_kernel()
                 w = kh(x - self.X_train_)
                 w_mat = np.diag(np.sqrt(w))
                 a = w_mat @ phi
-                q, r = np.linalg.qr(a, mode='complete')
+                q, r = np.linalg.qr(a, mode="complete")
                 r = r[:m, :m]
                 self.fitted_kernel.append((q.transpose() @ w_mat, r))
         n = len(self.fitted_kernel)
         y_pred = np.zeros(n)
         for i in range(n):
@@ -255,23 +267,27 @@
         :param X: a numpy array of dimension (M, d) at which to predict
         :return: a numpy array of dimension (M,) with the M predicted y's
         """
         poly = PolynomialFeatures(degree=self.degree)
         x0 = poly.fit_transform(np.zeros((1, X[0].shape[0])))[0]
-        return np.array([leastsq(func=self._cost_functional(poly, x),
-                                 x0=x0)[0][0] for x in X])
+        return np.array(
+            [leastsq(func=self._cost_functional(poly, x), x0=x0)[0][0] for x in X]
+        )
 
     def _cost_functional(self, poly, x):
         """
         Creates the cost functional $J$ for optimization using the parameters.
         :param poly: an instance of PolynomialFeatures
         :param x: a numpy array of shape (d,)
         :return: cost funtional $J$
         """
 
         def cost(beta):
-            res = np.sum(poly.fit_transform(self.X_train_ - x) * beta, axis=1) - self.y_train
+            res = (
+                np.sum(poly.fit_transform(self.X_train_ - x) * beta, axis=1)
+                - self.y_train
+            )
             kh = self._scaled_kernel()
             w = kh(x - self.X_train_)
             res *= np.sqrt(np.abs(w))
             return res
 
would reformat /home/runner/work/scikit-learn/scikit-learn/sklearn/linear_model/_local.py
--- /home/runner/work/scikit-learn/scikit-learn/sklearn/linear_model/tests/test_local.py	2023-07-30 19:18:48.642674 +0000
+++ /home/runner/work/scikit-learn/scikit-learn/sklearn/linear_model/tests/test_local.py	2023-07-30 19:19:11.641321 +0000
@@ -2,11 +2,10 @@
 from sklearn.linear_model._local import LocalRegression
 import numpy as np
 
 
 class TestLocalRegression(TestCase):
-
     def setUp(self):
         self.n = 10
         self.x = np.linspace(-10, 10, self.n)
         self.X = self.x[:, np.newaxis]
         np.random.seed(1)
@@ -15,40 +14,42 @@
     def test_nw_analytic_vs_qr_vs_leastsq_1d(self):
         self.y = self.x**2 + self.e
         self.nw = LocalRegression(degree=0, warm_start=False)
         self.nw.fit(self.X, self.y)
         X_eval = np.linspace(-10, 10, 2 * self.n)[:, np.newaxis]
-        y_pred_analytic = self.nw.predict(X_eval, method='analytic')
-        y_pred_qr = self.nw.predict(X_eval, method='qr')
-        y_pred_leastsq = self.nw.predict(X_eval, method='leastsq')
+        y_pred_analytic = self.nw.predict(X_eval, method="analytic")
+        y_pred_qr = self.nw.predict(X_eval, method="qr")
+        y_pred_leastsq = self.nw.predict(X_eval, method="leastsq")
         np.testing.assert_almost_equal(y_pred_analytic, y_pred_qr, decimal=6)
         np.testing.assert_almost_equal(y_pred_qr, y_pred_leastsq, decimal=6)
 
     def test_nw_analytic_vs_qr_vs_leastsq_2d(self):
         grid = np.linspace(-10, 10, self.n)
         x1, x2 = np.meshgrid(grid, grid)
         self.X = np.vstack((x1.flatten(), x2.flatten())).T
-        self.y = self.X[:, 0] * self.X[:, 1] + np.random.normal(0, 0.01, self.X.shape[0])
+        self.y = self.X[:, 0] * self.X[:, 1] + np.random.normal(
+            0, 0.01, self.X.shape[0]
+        )
         self.nw = LocalRegression(degree=0, warm_start=False)
         self.nw.fit(self.X, self.y)
         grid_eval = np.linspace(-10, 10, 2 * self.n)[:, np.newaxis]
         x1e, x2e = np.meshgrid(grid_eval, grid_eval)
         X_eval = np.vstack((x1e.flatten(), x2e.flatten())).T
-        y_pred_analytic = self.nw.predict(X_eval, method='analytic')
-        y_pred_qr = self.nw.predict(X_eval, method='qr')
-        y_pred_leastsq = self.nw.predict(X_eval, method='leastsq')
+        y_pred_analytic = self.nw.predict(X_eval, method="analytic")
+        y_pred_qr = self.nw.predict(X_eval, method="qr")
+        y_pred_leastsq = self.nw.predict(X_eval, method="leastsq")
         np.testing.assert_almost_equal(y_pred_qr, y_pred_leastsq, decimal=5)
         np.testing.assert_almost_equal(y_pred_analytic, y_pred_qr, decimal=5)
 
     def test_ll_analytic_vs_cost(self):
         self.y = self.x + self.e
         self.ll = LocalRegression(degree=1, warm_start=False)
         self.ll.fit(self.X, self.y)
         X_eval = np.linspace(-10, 10, 2 * self.n)[:, np.newaxis]
-        y_pred_analytic = self.ll.predict(X_eval, method='analytic')
-        y_pred_qr = self.ll.predict(X_eval, method='qr')
-        y_pred_leastsq = self.ll.predict(X_eval, method='leastsq')
+        y_pred_analytic = self.ll.predict(X_eval, method="analytic")
+        y_pred_qr = self.ll.predict(X_eval, method="qr")
+        y_pred_leastsq = self.ll.predict(X_eval, method="leastsq")
         np.testing.assert_almost_equal(y_pred_analytic, y_pred_qr)
         np.testing.assert_almost_equal(y_pred_qr, y_pred_leastsq)
 
     def test_nw_analytic_loc_const_const_1d(self):
         self.y = np.ones_like(self.x) + self.e
@@ -62,11 +63,11 @@
         self.ll.fit(self.X, self.y)
         np.testing.assert_almost_equal(self.ll.predict(self.X), self.y, decimal=1)
 
     def test_2d_loc_const_const(self):
         n = 5
-        c = 7.
+        c = 7.0
         x = np.linspace(-5, 5, n)
         y = np.linspace(-5, 5, n)
         z = np.array([[c for xx in x] for yy in y])
         x, y = np.meshgrid(x, y)
         X = np.array(list(zip(x.flatten(), y.flatten())))
@@ -94,35 +95,35 @@
 
     def test_2d_least_sq_vs_qr(self):
         n = 5
         x1 = np.linspace(1, 10, n)
         x2 = np.linspace(1, 10, n)
-        y = np.array([[xx1 ** 2 + xx2 ** 2 for xx1 in x1] for xx2 in x2])
+        y = np.array([[xx1**2 + xx2**2 for xx1 in x1] for xx2 in x2])
         x1, x2 = np.meshgrid(x1, x2)
         X = np.array(list(zip(x1.flatten(), x2.flatten())))
         np.random.seed(1)
         e = np.random.normal(0, 0.01, (n, n))
         y = y + e
         locreg3d = LocalRegression(degree=2).fit(X, y.flatten())
-        y_pred_leastsq = locreg3d.predict(X, method='leastsq')
-        y_pred_qr = locreg3d.predict(X, method='qr')
+        y_pred_leastsq = locreg3d.predict(X, method="leastsq")
+        y_pred_qr = locreg3d.predict(X, method="qr")
         np.testing.assert_array_almost_equal(y_pred_leastsq, y_pred_qr)
 
     def test_fit_partial(self):
         self.y = self.x + self.e
         self.ll = LocalRegression(degree=1, warm_start=True)
         self.ll.fit(self.X, self.y)
         X_eval = np.linspace(-10, 10, 2 * self.n)[:, np.newaxis]
-        _ = self.ll.predict(X_eval, method='analytic')
-        self.y = self.x ** 2 + self.e
+        _ = self.ll.predict(X_eval, method="analytic")
+        self.y = self.x**2 + self.e
         h = self.ll.bandwidth
         self.ll.fit_partial(self.y, h)
-        y_pred_partial = self.ll.predict(X_eval, method='analytic')
+        y_pred_partial = self.ll.predict(X_eval, method="analytic")
         self.ll2 = LocalRegression(degree=1, warm_start=False)
         self.ll2.fit(self.X, self.y, h)
-        y_pred = self.ll2.predict(X_eval, method='analytic')
+        y_pred = self.ll2.predict(X_eval, method="analytic")
         np.testing.assert_almost_equal(y_pred, y_pred_partial)
         # test against new instance to validate correct state
         self.ll3 = LocalRegression(degree=1, warm_start=False)
         self.ll3.fit(self.X, self.y, h)
-        y_pred_new = self.ll3.predict(X_eval, method='analytic')
+        y_pred_new = self.ll3.predict(X_eval, method="analytic")
         np.testing.assert_array_almost_equal(y_pred_new, y_pred)
would reformat /home/runner/work/scikit-learn/scikit-learn/sklearn/linear_model/tests/test_local.py

Oh no! 💥 💔 💥
2 files would be reformatted, 909 files would be left unchanged.

ruff

ruff detected issues. Please run ruff --fix --show-source . locally, fix the remaining issues, and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.0.280.

Details

sklearn/linear_model/_local.py:1:1: I001 [*] Import block is un-sorted or un-formatted
   |
 1 | / from scipy.optimize import leastsq
 2 | | import numpy as np
 3 | | from scipy.linalg import solve_triangular
 4 | | 
 5 | | from ._base import RegressorMixin
 6 | | from ..preprocessing import PolynomialFeatures
 7 | | 
 8 | | 
 9 | | def exp_kernel(z):
   | |_^ I001
10 |       """
11 |       Implements the exponential kernel $$ e^{-|z|^2/2}$$
   |
   = help: Organize imports

sklearn/linear_model/_local.py:24:10: W605 [*] Invalid escape sequence: `\i`
   |
22 |     This class performs local polynomial regression of dimension $d$
23 |     and degree $p$, i.e. given a training set $(X,y)$ of $N$ samples
24 |     $x_i \in \R^d$ and $y_i \in \R$, it makes a new prediction at
   |          ^^ W605
25 |     $x \in \R^d$ as $x=\beta^0$, where $\beta$ is the value minimizing
26 |     the cost functional
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:24:14: W605 [*] Invalid escape sequence: `\R`
   |
22 |     This class performs local polynomial regression of dimension $d$
23 |     and degree $p$, i.e. given a training set $(X,y)$ of $N$ samples
24 |     $x_i \in \R^d$ and $y_i \in \R$, it makes a new prediction at
   |              ^^ W605
25 |     $x \in \R^d$ as $x=\beta^0$, where $\beta$ is the value minimizing
26 |     the cost functional
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:24:29: W605 [*] Invalid escape sequence: `\i`
   |
22 |     This class performs local polynomial regression of dimension $d$
23 |     and degree $p$, i.e. given a training set $(X,y)$ of $N$ samples
24 |     $x_i \in \R^d$ and $y_i \in \R$, it makes a new prediction at
   |                             ^^ W605
25 |     $x \in \R^d$ as $x=\beta^0$, where $\beta$ is the value minimizing
26 |     the cost functional
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:24:33: W605 [*] Invalid escape sequence: `\R`
   |
22 |     This class performs local polynomial regression of dimension $d$
23 |     and degree $p$, i.e. given a training set $(X,y)$ of $N$ samples
24 |     $x_i \in \R^d$ and $y_i \in \R$, it makes a new prediction at
   |                                 ^^ W605
25 |     $x \in \R^d$ as $x=\beta^0$, where $\beta$ is the value minimizing
26 |     the cost functional
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:25:8: W605 [*] Invalid escape sequence: `\i`
   |
23 |     and degree $p$, i.e. given a training set $(X,y)$ of $N$ samples
24 |     $x_i \in \R^d$ and $y_i \in \R$, it makes a new prediction at
25 |     $x \in \R^d$ as $x=\beta^0$, where $\beta$ is the value minimizing
   |        ^^ W605
26 |     the cost functional
27 |     \begin{align*}
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:25:12: W605 [*] Invalid escape sequence: `\R`
   |
23 |     and degree $p$, i.e. given a training set $(X,y)$ of $N$ samples
24 |     $x_i \in \R^d$ and $y_i \in \R$, it makes a new prediction at
25 |     $x \in \R^d$ as $x=\beta^0$, where $\beta$ is the value minimizing
   |            ^^ W605
26 |     the cost functional
27 |     \begin{align*}
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:28:23: W605 [*] Invalid escape sequence: `\s`
   |
26 |     the cost functional
27 |     \begin{align*}
28 |         J(\beta) & := \sum_{i=1}^{N}{(y_i - \beta ^0 + j_1(x_i))^2 w_i},
   |                       ^^ W605
29 |         j_1(x_i) & := \sum_{1 \leq |\alpha| \leq p}{(x-x_i)^\alpha}, \\
30 |         w_i & := K_h(x-x_i),
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:29:23: W605 [*] Invalid escape sequence: `\s`
   |
27 |     \begin{align*}
28 |         J(\beta) & := \sum_{i=1}^{N}{(y_i - \beta ^0 + j_1(x_i))^2 w_i},
29 |         j_1(x_i) & := \sum_{1 \leq |\alpha| \leq p}{(x-x_i)^\alpha}, \\
   |                       ^^ W605
30 |         w_i & := K_h(x-x_i),
31 |     \end{align*}
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:29:31: W605 [*] Invalid escape sequence: `\l`
   |
27 |     \begin{align*}
28 |         J(\beta) & := \sum_{i=1}^{N}{(y_i - \beta ^0 + j_1(x_i))^2 w_i},
29 |         j_1(x_i) & := \sum_{1 \leq |\alpha| \leq p}{(x-x_i)^\alpha}, \\
   |                               ^^ W605
30 |         w_i & := K_h(x-x_i),
31 |     \end{align*}
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:29:45: W605 [*] Invalid escape sequence: `\l`
   |
27 |     \begin{align*}
28 |         J(\beta) & := \sum_{i=1}^{N}{(y_i - \beta ^0 + j_1(x_i))^2 w_i},
29 |         j_1(x_i) & := \sum_{1 \leq |\alpha| \leq p}{(x-x_i)^\alpha}, \\
   |                                             ^^ W605
30 |         w_i & := K_h(x-x_i),
31 |     \end{align*}
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:31:5: W605 [*] Invalid escape sequence: `\e`
   |
29 |         j_1(x_i) & := \sum_{1 \leq |\alpha| \leq p}{(x-x_i)^\alpha}, \\
30 |         w_i & := K_h(x-x_i),
31 |     \end{align*}
   |     ^^ W605
32 |     where $K_h$ is a kernel function scaled with bandwith $h$. The minimum
33 |     of the cost function is computed via QR decomposition (or analytically).
   |
   = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:88:89: E501 Line too long (100 > 88 characters)
   |
86 |             has already been performed.
87 |         """
88 |         if self.warm_start and self.fitted_kernel is not None and self.method in ['analytic', 'qr']:
   |                                                                                         ^^^^^^^^^^^^ E501
89 |             self.y_train = y
90 |             self._set_bandwidth(bandwidth)
   |

sklearn/linear_model/_local.py:117:17: W605 [*] Invalid escape sequence: `\B`
    |
115 |         This function implements Silverman's Rule of Thumb
116 |         \begin{align*}
117 |             h = \Big( \frac{4}{3n} \Big)^{\frac{1}{5}} \hat \sigma_Y
    |                 ^^ W605
118 |         \end{align*}
119 |         to estimate the optimal bandwidth of the training data y.
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:117:36: W605 [*] Invalid escape sequence: `\B`
    |
115 |         This function implements Silverman's Rule of Thumb
116 |         \begin{align*}
117 |             h = \Big( \frac{4}{3n} \Big)^{\frac{1}{5}} \hat \sigma_Y
    |                                    ^^ W605
118 |         \end{align*}
119 |         to estimate the optimal bandwidth of the training data y.
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:117:56: W605 [*] Invalid escape sequence: `\h`
    |
115 |         This function implements Silverman's Rule of Thumb
116 |         \begin{align*}
117 |             h = \Big( \frac{4}{3n} \Big)^{\frac{1}{5}} \hat \sigma_Y
    |                                                        ^^ W605
118 |         \end{align*}
119 |         to estimate the optimal bandwidth of the training data y.
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:117:61: W605 [*] Invalid escape sequence: `\s`
    |
115 |         This function implements Silverman's Rule of Thumb
116 |         \begin{align*}
117 |             h = \Big( \frac{4}{3n} \Big)^{\frac{1}{5}} \hat \sigma_Y
    |                                                             ^^ W605
118 |         \end{align*}
119 |         to estimate the optimal bandwidth of the training data y.
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:118:9: W605 [*] Invalid escape sequence: `\e`
    |
116 |         \begin{align*}
117 |             h = \Big( \frac{4}{3n} \Big)^{\frac{1}{5}} \hat \sigma_Y
118 |         \end{align*}
    |         ^^ W605
119 |         to estimate the optimal bandwidth of the training data y.
120 |         :return: bandwidth h
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:175:24: W605 [*] Invalid escape sequence: `\i`
    |
173 |         Performs local regression of degree $p=0$ in dimension $d=1$.
174 |         In this case, the cost functional can be minimized analytically
175 |         and for any $x \in \R$, the estimate $y$ is given by
    |                        ^^ W605
176 |         \begin{align*}
177 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:175:28: W605 [*] Invalid escape sequence: `\R`
    |
173 |         Performs local regression of degree $p=0$ in dimension $d=1$.
174 |         In this case, the cost functional can be minimized analytically
175 |         and for any $x \in \R$, the estimate $y$ is given by
    |                            ^^ W605
176 |         \begin{align*}
177 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:177:18: W605 [*] Invalid escape sequence: `\s`
    |
175 |         and for any $x \in \R$, the estimate $y$ is given by
176 |         \begin{align*}
177 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
    |                  ^^ W605
178 |             W^0_i(x) &= \frac{K_h(x - x_i)}{\sum_{j=1}^N{K_h(x - x_j)}}
179 |         \end{align*}
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:178:45: W605 [*] Invalid escape sequence: `\s`
    |
176 |         \begin{align*}
177 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
178 |             W^0_i(x) &= \frac{K_h(x - x_i)}{\sum_{j=1}^N{K_h(x - x_j)}}
    |                                             ^^ W605
179 |         \end{align*}
180 |         :param X: a numpy array of dimension (M, d) at which to predict
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:179:9: W605 [*] Invalid escape sequence: `\e`
    |
177 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
178 |             W^0_i(x) &= \frac{K_h(x - x_i)}{\sum_{j=1}^N{K_h(x - x_j)}}
179 |         \end{align*}
    |         ^^ W605
180 |         :param X: a numpy array of dimension (M, d) at which to predict
181 |         :return: a numpy array of dimension (M,) with the M predicted y's
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:193:24: W605 [*] Invalid escape sequence: `\i`
    |
191 |         Performs local regression of degree $p=1$ in dimension $d=1$.
192 |         In this case, the cost functional can be minimized analytically
193 |         and for any $x \in \R$, the estimate $y$ is given by
    |                        ^^ W605
194 |         \begin{align*}
195 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:193:28: W605 [*] Invalid escape sequence: `\R`
    |
191 |         Performs local regression of degree $p=1$ in dimension $d=1$.
192 |         In this case, the cost functional can be minimized analytically
193 |         and for any $x \in \R$, the estimate $y$ is given by
    |                            ^^ W605
194 |         \begin{align*}
195 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:195:18: W605 [*] Invalid escape sequence: `\s`
    |
193 |         and for any $x \in \R$, the estimate $y$ is given by
194 |         \begin{align*}
195 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
    |                  ^^ W605
196 |             W^1_i(x) &:= \frac{K_h(x-x_i)}{N}\frac{s_2(x)-s_1(x)(x-x_i)}{x_2(x)s_0(x)} \\
197 |             s_r(x) &:= \frac{1}{N} \sum_{i=1}^N{(x-x_i)^rK_h(x-x_i)}.
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:196:89: E501 Line too long (89 > 88 characters)
    |
194 |         \begin{align*}
195 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
196 |             W^1_i(x) &:= \frac{K_h(x-x_i)}{N}\frac{s_2(x)-s_1(x)(x-x_i)}{x_2(x)s_0(x)} \\
    |                                                                                         ^ E501
197 |             s_r(x) &:= \frac{1}{N} \sum_{i=1}^N{(x-x_i)^rK_h(x-x_i)}.
198 |         \end{align*}
    |

sklearn/linear_model/_local.py:197:36: W605 [*] Invalid escape sequence: `\s`
    |
195 |             y &= \sum_{i=1}^{N}{W^i_h(x) y_i}, \\
196 |             W^1_i(x) &:= \frac{K_h(x-x_i)}{N}\frac{s_2(x)-s_1(x)(x-x_i)}{x_2(x)s_0(x)} \\
197 |             s_r(x) &:= \frac{1}{N} \sum_{i=1}^N{(x-x_i)^rK_h(x-x_i)}.
    |                                    ^^ W605
198 |         \end{align*}
199 |         :param X: a numpy array of dimension (M, d) at which to predict
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:198:9: W605 [*] Invalid escape sequence: `\e`
    |
196 |             W^1_i(x) &:= \frac{K_h(x-x_i)}{N}\frac{s_2(x)-s_1(x)(x-x_i)}{x_2(x)s_0(x)} \\
197 |             s_r(x) &:= \frac{1}{N} \sum_{i=1}^N{(x-x_i)^rK_h(x-x_i)}.
198 |         \end{align*}
    |         ^^ W605
199 |         :param X: a numpy array of dimension (M, d) at which to predict
200 |         :return: a numpy array of dimension (M,) with the M predicted y's
    |
    = help: Add backslash to escape sequence

sklearn/linear_model/_local.py:272:89: E501 Line too long (93 > 88 characters)
    |
271 |         def cost(beta):
272 |             res = np.sum(poly.fit_transform(self.X_train_ - x) * beta, axis=1) - self.y_train
    |                                                                                         ^^^^^ E501
273 |             kh = self._scaled_kernel()
274 |             w = kh(x - self.X_train_)
    |

sklearn/linear_model/tests/test_local.py:1:1: I001 [*] Import block is un-sorted or un-formatted
  |
1 | / from unittest import TestCase
2 | | from sklearn.linear_model._local import LocalRegression
3 | | import numpy as np
4 | | 
5 | | 
6 | | class TestLocalRegression(TestCase):
  | |_^ I001
7 |   
8 |       def setUp(self):
  |
  = help: Organize imports

sklearn/linear_model/tests/test_local.py:30:89: E501 Line too long (89 > 88 characters)
   |
28 |         x1, x2 = np.meshgrid(grid, grid)
29 |         self.X = np.vstack((x1.flatten(), x2.flatten())).T
30 |         self.y = self.X[:, 0] * self.X[:, 1] + np.random.normal(0, 0.01, self.X.shape[0])
   |                                                                                         ^ E501
31 |         self.nw = LocalRegression(degree=0, warm_start=False)
32 |         self.nw.fit(self.X, self.y)
   |

Found 32 errors.
[*] 28 potentially fixable with the --fix option.

Generated for commit: 14efbe6. Link to the linter CI: here

@agramfort

Copy link
Copy Markdown
Member

no strong feeling but looking at the diff there is quiet some work to be done here.
Also I don't think this should land in linear_model.

To me this method is referred to as KernelRegression https://en.wikipedia.org/wiki/Kernel_regression
and I know it as Nadaraya-Watson regression.

@niknow

niknow commented Aug 2, 2023

Copy link
Copy Markdown
Author

@agramfort Thanks for your feedback.

  1. The Wikipedia page on Kernel Regression you refer to primarily contains a documentation on Nadaraya-Watson regression. This is a indeed special case of Local Regression, which assumes that the degree $p$ of the Taylor polynomial used in the local regression is $p=0$. In this case, the resulting equations can be solved analytically and in fact the code in the commit does exactly that. I think because this case is the most famous, the method is sometimes called Kernel Regression. Given that one uses a local approximation as well as a kernel, both names seem appropriate and I have no strong feeling for one over the other. ;-)
    You can find a full mathematical description of the method and the context on my examples page.
    Happy to build a chapter for the documentation out of it if there is interest?
  2. You say that linear_model is not the right place for this method. To be honest, when I put it there I wasn't fully sure myself. Do you have any suggestion where else to put it?
  3. Besides fixing the errors above reported by the CI (I can look into the linter errors etc.), could you elaborate what you mean by "diff"?

@adrinjalali

Copy link
Copy Markdown
Member

also tagging @lorentzenchr since I think he'd also know more about these methods.

@lorentzenchr

lorentzenchr commented Aug 4, 2023 •

Copy link
Copy Markdown
Member

I also know it by Nadaraya-Watson. I think it is out of scope for 2 reasons:

  1. It needs to save the whole training X as it is used at prediction time.
  2. Its use case is more for interpolation with uncertainty estimates. IMHO, that fits better in statsmodels or scipy. Often used in plots.

@adrinjalali adrinjalali added the Needs Decision - Include Feature Requires decision regarding including feature label Aug 7, 2023
@agramfort

agramfort commented Aug 8, 2023 via email

Copy link
Copy Markdown
Member

@niknow

niknow commented Aug 12, 2023

Copy link
Copy Markdown
Author

@agramfort I'll try my best. ;-) I understand you want to make a determination on whether or not local regression is in scope of scikit, but I'm not sure I fully understand the criterions. Maybe it helps to clarify a few points mentioned so far:

  1. Interpolation: If you use local regression on a set $(x_i, y_i)$, then in general the resulting predictor $\hat F$ will not satisfy $\hat F(x_i) = y_i$. While the Taylor polynomial does have that property, $\hat F$ does not due to the weights chosen in the cost function. Hence, local regression is not an interpolator.
  2. Fitting & Predicting: It is correct that the fit function of this regressor has to store the training set. In fact, besides some parameter tweaking, this is all it needs to do. Hence, it requires more memory and less computational effort than the fit of linear regression. Conversely, the predict part of local regression needs more computational effort than that of linear regression. This is precisely what 'local' means. I know this is different from many other models and I was hesitant to put it in that shape at first too, but doing so is formally not wrong and practically very convenient for the user. You are also correct in pointing out that methods like KNN share this property with local regression.
  3. Other methods: I'd say local regression is particularly useful in situations where (global) linear regression is unlikely to yield good results because the true functional form between $x$ and $y$ is too non-linear, but still differentiable. The behavior of Gaussian Process Regression depends of course on the chosen kernel and as illustrated in the appendix of this notebook you might get back a form of linear regression. I'd say the increased computational effort of Gaussian process regression is particularly worth it, if you need confidence bounds around your point estimates. I don't think I can easily give a general answer to the big question, which model is best though. ;-) It depends on the concrete situation. And that is precisely

My case (usability): The scope of scikit (admittedly my subjective perception of it) is that it provides reference implementations of standard techniques in predictive modelling in a common interface. Whenever you are faced with a concrete problem and you want to give a practical answer to your very question, i.e. "which model should I choose" (linear regression, local regression, Gaussain regression etc.), a pragmatic strategy is to simply try it out. Having a common interface in form of this instantiate-fit-predict pattern is incredibly convenient for the user and makes it easy to do that with consistent clean code. From a user perspective it is much more important to have this common interface than what computation or memory operations go on under the hood during the fit and the predict.

Local regression is one of the few standard techniques that is not available in scikit. In particular the special case of Nadaraya-Watson is relevant to many areas of modelling though, for example in the financial domain. Having that available in the same instatiate-fit-predict interface than all the other models in scikit will make it a lot simpler for many end users to try this technique.

This is by the way the origin story of this code: While writing this paper we benefitted a lot from the convenience of having every other standard technique easily available in scikit - just local regression was missing. Thus, I wrote it myself, found it very convenient to use in the scikit interface, and hence would I'd be happy to give this back to the community for others to benefit from it as well.

@agramfort

Copy link
Copy Markdown
Member

@niknow thanks for the detailed answer. Regarding inclusion criterions you can read https://scikit-learn.org/stable/faq.html#what-are-the-inclusion-criteria-for-new-algorithms

At this point I would suggest to put this code in gist at http://gist.github.com so people can easily reuse your work which I think should be the first objective.

We have now many "tricks" to get non-linear regression models (Kernel Ridge, GaussianProcessed, PolynomialFeatures, pipeline of Spline or KBinsDiscretizer with Ridge etc.). To me, the case that you would need to be make would be to show at least on one convincing example (on real data) that this new estimator is better in some way (compute time, prediction accuracy, reduced variance, easy model selection etc.)

my 2c

@niknow

niknow commented Aug 17, 2023

Copy link
Copy Markdown
Author

@agramfort The example in the notebook referenced above that compares local regression against PolynomialFeatures of any degree in case $y_i = \sin(x_i) + \varepsilon_i$ is the one that convinced me. ;-) I'd need to look into all these other methods in more detail to be in a position to comment.

Could you clarify one thing for me though: According to #3075 it is regarded as an issue that this method is missing. Yet, you sound like that it is more of an issue if it were not missing. This cannot both be true.

What do you suggest is needed to close this issue?

@lorentzenchr

Copy link
Copy Markdown
Member

@niknow Having the plots rendered and an out-of-sample score would be nice (we don’t care too much about training loss/score).
For the sin-case, I would compare to Ridge with periodic splines. A comparison to the local regression in the true extrapolation regime would then be interesting.

@lorentzenchr

Copy link
Copy Markdown
Member

@niknow Thanks for this PR.
I close as explained in #3075 (comment).

On top, this PR puts the heavy computation (what is the complexity in n_sampels and n_features?) in predict instead of the fit function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module:linear_model Needs Decision - Include Feature Requires decision regarding including feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Local Regression is Missing

5 participants