{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "from sklearn.datasets import load_iris\n", "from sklearn.feature_selection import VarianceThreshold as skVarianceThreshold" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "class VarianceThreshold():\n", " def __init__(self, threshold=0):\n", " self.threshold = threshold\n", "\n", " def fit(self, X):\n", " self.variances_ = np.var(X, axis=0)\n", " return self\n", "\n", " def transform(self, X):\n", " return X[:, self.variances_ > self.threshold]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "X, _ = load_iris(return_X_y=True)\n", "X[:, [0, 2]] = 0\n", "est1 = VarianceThreshold().fit(X)\n", "est2 = skVarianceThreshold().fit(X)\n", "assert np.allclose(est1.variances_, est2.variances_)\n", "Xt1 = est1.transform(X)\n", "Xt2 = est2.transform(X)\n", "assert np.allclose(Xt1, Xt2)" ] } ], "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 }