{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from sklearn.base import clone\n", "from sklearn.datasets import load_boston, load_iris\n", "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n", "from sklearn.model_selection import KFold, StratifiedKFold\n", "from sklearn.model_selection import cross_val_predict as skcross_val_predict" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def cross_val_predict(estimator, X, y, method=\"predict\"):\n", " if estimator._estimator_type == \"regressor\":\n", " cv = KFold()\n", " else: # estimator._estimator_type == \"classifier\"\n", " cv = StratifiedKFold()\n", " predictions = []\n", " indices = []\n", " for train, test in cv.split(X, y):\n", " est = clone(estimator)\n", " est.fit(X[train], y[train])\n", " predictions.extend(getattr(est, method)(X[test]))\n", " indices.extend(test)\n", " inv_indices = np.empty(len(indices), dtype=np.int)\n", " inv_indices[indices] = np.arange(len(indices))\n", " return np.array(predictions)[inv_indices]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# regression\n", "X, y = load_boston(return_X_y=True)\n", "clf = RandomForestRegressor(random_state=0)\n", "ans1 = cross_val_predict(clf, X, y)\n", "ans2 = skcross_val_predict(clf, X, y)\n", "assert np.allclose(ans1, ans2)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# classification\n", "X, y = load_iris(return_X_y=True)\n", "clf = RandomForestClassifier(random_state=0)\n", "ans1 = cross_val_predict(clf, X, y)\n", "ans2 = skcross_val_predict(clf, X, y)\n", "assert np.array_equal(ans1, ans2)\n", "ans1 = cross_val_predict(clf, X, y, method=\"predict_proba\")\n", "ans2 = skcross_val_predict(clf, X, y, method=\"predict_proba\")\n", "assert np.allclose(ans1, ans2)" ] } ], "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 }