{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from copy import deepcopy\n", "from sklearn.datasets import load_boston\n", "from sklearn.ensemble import VotingRegressor as skVotingRegressor\n", "from sklearn.linear_model import LinearRegression\n", "from sklearn.ensemble import RandomForestRegressor" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class VotingRegressor():\n", " def __init__(self, estimators):\n", " self.estimators = estimators\n", "\n", " def fit(self, X, y):\n", " self.estimators_ = [deepcopy(est).fit(X, y) for _, est in self.estimators]\n", " return self\n", "\n", " def transform(self, X):\n", " prob = np.array([est.predict(X) for est in self.estimators_]).T\n", " return prob\n", "\n", " def predict(self, X):\n", " prob = self.transform(X)\n", " return np.mean(prob, axis=1)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "X, y = load_boston(return_X_y=True)\n", "clf1 = LinearRegression()\n", "clf2 = RandomForestRegressor(n_estimators=100, random_state=0)\n", "eclf1 = VotingRegressor(estimators=[('lr', clf1), ('rf', clf2)]).fit(X, y)\n", "eclf2 = skVotingRegressor(estimators=[('lr', clf1), ('rf', clf2)]).fit(X, y)\n", "prob1 = eclf1.transform(X)\n", "prob2 = eclf2.transform(X)\n", "assert np.allclose(prob1, prob2)\n", "pred1 = eclf1.predict(X)\n", "pred2 = eclf2.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 }