{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from scipy.linalg import svd\n", "from sklearn.datasets import load_boston\n", "from sklearn.linear_model import RidgeCV as skRidgeCV" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Implementation 1\n", "- based on svd\n", "- only support fit_intercept=False\n", "- similar to scikit-learn gcv_mode='svd'" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class RidgeCV():\n", " def __init__(self, alphas=[0.1, 1.0, 10]):\n", " self.alphas = alphas\n", "\n", " def fit(self, X, y):\n", " U, S, VT = svd(X, full_matrices=False)\n", " cv_values = np.zeros((X.shape[0], len(self.alphas)))\n", " best_score, best_coef, best_alpha = None, None, None\n", " for i, alpha in enumerate(self.alphas):\n", " w = (S ** 2 + alpha) ** -1 - alpha ** -1\n", " G_inv = np.dot(U * w[np.newaxis, :], U.T) + np.eye(X.shape[0]) * alpha ** -1\n", " c = np.dot(G_inv, y)\n", " looe = c / np.diag(G_inv)\n", " errors = looe ** 2\n", " cv_values[:, i] = errors\n", " score = -np.mean(errors)\n", " if best_score is None or best_score < score:\n", " best_score = score\n", " best_coef = c\n", " best_alpha = alpha\n", " self.cv_values_ = cv_values\n", " self.best_score = best_score\n", " self.coef_ = np.dot(X.T, best_coef)\n", " self.alpha_ = best_alpha\n", " return self\n", "\n", " def predict(self, X):\n", " return np.dot(X, self.coef_)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "X, y = load_boston(return_X_y=True)\n", "X -= X.mean(axis=0)\n", "y -= y.mean()\n", "alpha = [0.1, 1, 10]\n", "reg1 = RidgeCV().fit(X, y)\n", "reg2 = skRidgeCV(fit_intercept=False, store_cv_values=True).fit(X, y)\n", "assert np.allclose(reg1.cv_values_, reg2.cv_values_)\n", "assert np.allclose(reg1.coef_, reg2.coef_)\n", "assert np.allclose(reg1.alpha_, reg2.alpha_)\n", "pred1 = reg1.predict(X)\n", "pred2 = reg2.predict(X)\n", "assert np.allclose(pred1, pred2)" ] } ], "metadata": { "kernelspec": { "display_name": "dev", "language": "python", "name": "dev" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }