{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from sklearn.datasets import load_boston\n", "from sklearn.model_selection import KFold as skKFold" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class KFold():\n", " def __init__(self, n_splits=5, shuffle=False, random_state=0):\n", " self.n_splits = n_splits\n", " self.shuffle = shuffle\n", " self.random_state = random_state\n", "\n", " def _iter_test_indices(self, X, y):\n", " indices = np.arange(X.shape[0])\n", " if self.shuffle:\n", " rng = np.random.RandomState(self.random_state)\n", " rng.shuffle(indices)\n", " fold_sizes = np.full(self.n_splits, X.shape[0] // self.n_splits)\n", " fold_sizes[:X.shape[0] % self.n_splits] += 1\n", " current = 0\n", " for fold_size in fold_sizes:\n", " yield indices[current:current + fold_size]\n", " current += fold_size\n", "\n", " def _iter_test_masks(self, X, y):\n", " for test_index in self._iter_test_indices(X, y):\n", " test_mask = np.zeros(X.shape[0], dtype=bool)\n", " test_mask[test_index] = True\n", " yield test_mask\n", "\n", " def split(self, X, y):\n", " indices = np.arange(X.shape[0])\n", " for test_index in self._iter_test_masks(X, y):\n", " yield indices[~test_index], indices[test_index]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "X, y = load_boston(return_X_y=True)\n", "cv1 = KFold(n_splits=5)\n", "cv2 = skKFold(n_splits=5)\n", "for (train1, test1), (train2, test2) in zip(cv1.split(X, y), cv2.split(X, y)):\n", " assert np.array_equal(train1, train2)\n", " assert np.array_equal(test1, test2)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "X, y = load_boston(return_X_y=True)\n", "cv1 = KFold(n_splits=5, shuffle=True, random_state=0)\n", "cv2 = skKFold(n_splits=5, shuffle=True, random_state=0)\n", "for (train1, test1), (train2, test2) in zip(cv1.split(X, y), cv2.split(X, y)):\n", " assert np.array_equal(train1, train2)\n", " assert np.array_equal(test1, test2)" ] } ], "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 }