{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Out-of-core classification of text documents\n\nThis is an example showing how scikit-learn can be used for classification\nusing an out-of-core approach: learning from data that doesn't fit into main\nmemory. We make use of an online classifier, i.e., one that supports the\npartial_fit method, that will be fed with batches of examples. To guarantee\nthat the features space remains the same over time we leverage a\nHashingVectorizer that will project each example into the same feature space.\nThis is especially useful in the case of text classification where new\nfeatures (words) may appear in each batch.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport itertools\nimport re\nimport sys\nimport tarfile\nimport time\nfrom hashlib import sha256\nfrom html.parser import HTMLParser\nfrom pathlib import Path\nfrom urllib.request import urlretrieve\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import rcParams\n\nfrom sklearn.datasets import get_data_home\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import Perceptron, SGDClassifier\nfrom sklearn.naive_bayes import MultinomialNB\n\n\ndef _not_in_sphinx():\n    # Hack to detect whether we are running by the sphinx builder\n    return \"__file__\" in globals()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Reuters Dataset related routines\n\nThe dataset used in this example is Reuters-21578 as provided by the UCI ML\nrepository. It will be automatically downloaded and uncompressed on first\nrun.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class ReutersParser(HTMLParser):\n    \"\"\"Utility class to parse a SGML file and yield documents one at a time.\"\"\"\n\n    def __init__(self, encoding=\"latin-1\"):\n        HTMLParser.__init__(self)\n        self._reset()\n        self.encoding = encoding\n\n    def handle_starttag(self, tag, attrs):\n        method = \"start_\" + tag\n        getattr(self, method, lambda x: None)(attrs)\n\n    def handle_endtag(self, tag):\n        method = \"end_\" + tag\n        getattr(self, method, lambda: None)()\n\n    def _reset(self):\n        self.in_title = 0\n        self.in_body = 0\n        self.in_topics = 0\n        self.in_topic_d = 0\n        self.title = \"\"\n        self.body = \"\"\n        self.topics = []\n        self.topic_d = \"\"\n\n    def parse(self, fd):\n        self.docs = []\n        for chunk in fd:\n            self.feed(chunk.decode(self.encoding))\n            for doc in self.docs:\n                yield doc\n            self.docs = []\n        self.close()\n\n    def handle_data(self, data):\n        if self.in_body:\n            self.body += data\n        elif self.in_title:\n            self.title += data\n        elif self.in_topic_d:\n            self.topic_d += data\n\n    def start_reuters(self, attributes):\n        pass\n\n    def end_reuters(self):\n        self.body = re.sub(r\"\\s+\", r\" \", self.body)\n        self.docs.append(\n            {\"title\": self.title, \"body\": self.body, \"topics\": self.topics}\n        )\n        self._reset()\n\n    def start_title(self, attributes):\n        self.in_title = 1\n\n    def end_title(self):\n        self.in_title = 0\n\n    def start_body(self, attributes):\n        self.in_body = 1\n\n    def end_body(self):\n        self.in_body = 0\n\n    def start_topics(self, attributes):\n        self.in_topics = 1\n\n    def end_topics(self):\n        self.in_topics = 0\n\n    def start_d(self, attributes):\n        self.in_topic_d = 1\n\n    def end_d(self):\n        self.in_topic_d = 0\n        self.topics.append(self.topic_d)\n        self.topic_d = \"\"\n\n\ndef stream_reuters_documents(data_path=None):\n    \"\"\"Iterate over documents of the Reuters dataset.\n\n    The Reuters archive will automatically be downloaded and uncompressed if\n    the `data_path` directory does not exist.\n\n    Documents are represented as dictionaries with 'body' (str),\n    'title' (str), 'topics' (list(str)) keys.\n\n    \"\"\"\n\n    DOWNLOAD_URL = \"https://kdd.ics.uci.edu/databases/reuters21578/reuters21578.tar.gz\"\n    ARCHIVE_SHA256 = \"3bae43c9b14e387f76a61b6d82bf98a4fb5d3ef99ef7e7075ff2ccbcf59f9d30\"\n    ARCHIVE_FILENAME = \"reuters21578.tar.gz\"\n\n    if data_path is None:\n        data_path = Path(get_data_home()) / \"reuters\"\n    else:\n        data_path = Path(data_path)\n    if not data_path.exists():\n        \"\"\"Download the dataset.\"\"\"\n        print(\"downloading dataset (once and for all) into %s\" % data_path)\n        data_path.mkdir(parents=True, exist_ok=True)\n\n        def progress(blocknum, bs, size):\n            total_sz_mb = \"%.2f MB\" % (size / 1e6)\n            current_sz_mb = \"%.2f MB\" % ((blocknum * bs) / 1e6)\n            if _not_in_sphinx():\n                sys.stdout.write(\"\\rdownloaded %s / %s\" % (current_sz_mb, total_sz_mb))\n\n        archive_path = data_path / ARCHIVE_FILENAME\n\n        urlretrieve(DOWNLOAD_URL, filename=archive_path, reporthook=progress)\n        if _not_in_sphinx():\n            sys.stdout.write(\"\\r\")\n\n        # Check that the archive was not tampered:\n        assert sha256(archive_path.read_bytes()).hexdigest() == ARCHIVE_SHA256\n\n        print(\"untarring Reuters dataset...\")\n        with tarfile.open(archive_path, \"r:gz\") as fp:\n            fp.extractall(data_path, filter=\"data\")\n        print(\"done.\")\n\n    parser = ReutersParser()\n    for filename in data_path.glob(\"*.sgm\"):\n        for doc in parser.parse(open(filename, \"rb\")):\n            yield doc"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Main\n\nCreate the vectorizer and limit the number of features to a reasonable\nmaximum\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "vectorizer = HashingVectorizer(\n    decode_error=\"ignore\", n_features=2**18, alternate_sign=False\n)\n\n\n# Iterator over parsed Reuters SGML files.\ndata_stream = stream_reuters_documents()\n\n# We learn a binary classification between the \"acq\" class and all the others.\n# \"acq\" was chosen as it is more or less evenly distributed in the Reuters\n# files. For other datasets, one should take care of creating a test set with\n# a realistic portion of positive instances.\nall_classes = np.array([0, 1])\npositive_class = \"acq\"\n\n# Here are some classifiers that support the `partial_fit` method\npartial_fit_classifiers = {\n    \"SGD\": SGDClassifier(max_iter=5),\n    \"Perceptron\": Perceptron(),\n    \"NB Multinomial\": MultinomialNB(alpha=0.01),\n    \"Passive-Aggressive\": SGDClassifier(\n        loss=\"hinge\", penalty=None, learning_rate=\"pa1\", eta0=1.0\n    ),\n}\n\n\ndef get_minibatch(doc_iter, size, pos_class=positive_class):\n    \"\"\"Extract a minibatch of examples, return a tuple X_text, y.\n\n    Note: size is before excluding invalid docs with no topics assigned.\n\n    \"\"\"\n    data = [\n        (\"{title}\\n\\n{body}\".format(**doc), pos_class in doc[\"topics\"])\n        for doc in itertools.islice(doc_iter, size)\n        if doc[\"topics\"]\n    ]\n    if not len(data):\n        return np.asarray([], dtype=int), np.asarray([], dtype=int)\n    X_text, y = zip(*data)\n    return X_text, np.asarray(y, dtype=int)\n\n\ndef iter_minibatches(doc_iter, minibatch_size):\n    \"\"\"Generator of minibatches.\"\"\"\n    X_text, y = get_minibatch(doc_iter, minibatch_size)\n    while len(X_text):\n        yield X_text, y\n        X_text, y = get_minibatch(doc_iter, minibatch_size)\n\n\n# test data statistics\ntest_stats = {\"n_test\": 0, \"n_test_pos\": 0}\n\n# First we hold out a number of examples to estimate accuracy\nn_test_documents = 1000\ntick = time.time()\nX_test_text, y_test = get_minibatch(data_stream, 1000)\nparsing_time = time.time() - tick\ntick = time.time()\nX_test = vectorizer.transform(X_test_text)\nvectorizing_time = time.time() - tick\ntest_stats[\"n_test\"] += len(y_test)\ntest_stats[\"n_test_pos\"] += sum(y_test)\nprint(\"Test set is %d documents (%d positive)\" % (len(y_test), sum(y_test)))\n\n\ndef progress(cls_name, stats):\n    \"\"\"Report progress information, return a string.\"\"\"\n    duration = time.time() - stats[\"t0\"]\n    s = \"%20s classifier : \\t\" % cls_name\n    s += \"%(n_train)6d train docs (%(n_train_pos)6d positive) \" % stats\n    s += \"%(n_test)6d test docs (%(n_test_pos)6d positive) \" % test_stats\n    s += \"accuracy: %(accuracy).3f \" % stats\n    s += \"in %.2fs (%5d docs/s)\" % (duration, stats[\"n_train\"] / duration)\n    return s\n\n\ncls_stats = {}\n\nfor cls_name in partial_fit_classifiers:\n    stats = {\n        \"n_train\": 0,\n        \"n_train_pos\": 0,\n        \"accuracy\": 0.0,\n        \"accuracy_history\": [(0, 0)],\n        \"t0\": time.time(),\n        \"runtime_history\": [(0, 0)],\n        \"total_fit_time\": 0.0,\n    }\n    cls_stats[cls_name] = stats\n\nget_minibatch(data_stream, n_test_documents)\n# Discard test set\n\n# We will feed the classifier with mini-batches of 1000 documents; this means\n# we have at most 1000 docs in memory at any time.  The smaller the document\n# batch, the bigger the relative overhead of the partial fit methods.\nminibatch_size = 1000\n\n# Create the data_stream that parses Reuters SGML files and iterates on\n# documents as a stream.\nminibatch_iterators = iter_minibatches(data_stream, minibatch_size)\ntotal_vect_time = 0.0\n\n# Main loop : iterate on mini-batches of examples\nfor i, (X_train_text, y_train) in enumerate(minibatch_iterators):\n    tick = time.time()\n    X_train = vectorizer.transform(X_train_text)\n    total_vect_time += time.time() - tick\n\n    for cls_name, cls in partial_fit_classifiers.items():\n        tick = time.time()\n        # update estimator with examples in the current mini-batch\n        cls.partial_fit(X_train, y_train, classes=all_classes)\n\n        # accumulate test accuracy stats\n        cls_stats[cls_name][\"total_fit_time\"] += time.time() - tick\n        cls_stats[cls_name][\"n_train\"] += X_train.shape[0]\n        cls_stats[cls_name][\"n_train_pos\"] += sum(y_train)\n        tick = time.time()\n        cls_stats[cls_name][\"accuracy\"] = cls.score(X_test, y_test)\n        cls_stats[cls_name][\"prediction_time\"] = time.time() - tick\n        acc_history = (cls_stats[cls_name][\"accuracy\"], cls_stats[cls_name][\"n_train\"])\n        cls_stats[cls_name][\"accuracy_history\"].append(acc_history)\n        run_history = (\n            cls_stats[cls_name][\"accuracy\"],\n            total_vect_time + cls_stats[cls_name][\"total_fit_time\"],\n        )\n        cls_stats[cls_name][\"runtime_history\"].append(run_history)\n\n        if i % 3 == 0:\n            print(progress(cls_name, cls_stats[cls_name]))\n    if i % 3 == 0:\n        print(\"\\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Plot results\n\nThe plot represents the learning curve of the classifier: the evolution\nof classification accuracy over the course of the mini-batches. Accuracy is\nmeasured on the first 1000 samples, held out as a validation set.\n\nTo limit the memory consumption, we queue examples up to a fixed amount\nbefore feeding them to the learner.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def plot_accuracy(x, y, x_legend):\n    \"\"\"Plot accuracy as a function of x.\"\"\"\n    x = np.array(x)\n    y = np.array(y)\n    plt.title(\"Classification accuracy as a function of %s\" % x_legend)\n    plt.xlabel(\"%s\" % x_legend)\n    plt.ylabel(\"Accuracy\")\n    plt.grid(True)\n    plt.plot(x, y)\n\n\nrcParams[\"legend.fontsize\"] = 10\ncls_names = list(sorted(cls_stats.keys()))\n\n# Plot accuracy evolution\nplt.figure()\nfor _, stats in sorted(cls_stats.items()):\n    # Plot accuracy evolution with #examples\n    accuracy, n_examples = zip(*stats[\"accuracy_history\"])\n    plot_accuracy(n_examples, accuracy, \"training examples (#)\")\n    ax = plt.gca()\n    ax.set_ylim((0.8, 1))\nplt.legend(cls_names, loc=\"best\")\n\nplt.figure()\nfor _, stats in sorted(cls_stats.items()):\n    # Plot accuracy evolution with runtime\n    accuracy, runtime = zip(*stats[\"runtime_history\"])\n    plot_accuracy(runtime, accuracy, \"runtime (s)\")\n    ax = plt.gca()\n    ax.set_ylim((0.8, 1))\nplt.legend(cls_names, loc=\"best\")\n\n# Plot fitting times\nplt.figure()\nfig = plt.gcf()\ncls_runtime = [stats[\"total_fit_time\"] for cls_name, stats in sorted(cls_stats.items())]\n\ncls_runtime.append(total_vect_time)\ncls_names.append(\"Vectorization\")\nbar_colors = [\"b\", \"g\", \"r\", \"c\", \"m\", \"y\"]\n\nax = plt.subplot(111)\nrectangles = plt.bar(range(len(cls_names)), cls_runtime, width=0.5, color=bar_colors)\n\nax.set_xticks(np.linspace(0, len(cls_names) - 1, len(cls_names)))\nax.set_xticklabels(cls_names, fontsize=10)\nymax = max(cls_runtime) * 1.2\nax.set_ylim((0, ymax))\nax.set_ylabel(\"runtime (s)\")\nax.set_title(\"Training Times\")\n\n\ndef autolabel(rectangles):\n    \"\"\"attach some text vi autolabel on rectangles.\"\"\"\n    for rect in rectangles:\n        height = rect.get_height()\n        ax.text(\n            rect.get_x() + rect.get_width() / 2.0,\n            1.05 * height,\n            \"%.4f\" % height,\n            ha=\"center\",\n            va=\"bottom\",\n        )\n        plt.setp(plt.xticks()[1], rotation=30)\n\n\nautolabel(rectangles)\nplt.tight_layout()\nplt.show()\n\n# Plot prediction times\nplt.figure()\ncls_runtime = []\ncls_names = list(sorted(cls_stats.keys()))\nfor cls_name, stats in sorted(cls_stats.items()):\n    cls_runtime.append(stats[\"prediction_time\"])\ncls_runtime.append(parsing_time)\ncls_names.append(\"Read/Parse\\n+Feat.Extr.\")\ncls_runtime.append(vectorizing_time)\ncls_names.append(\"Hashing\\n+Vect.\")\n\nax = plt.subplot(111)\nrectangles = plt.bar(range(len(cls_names)), cls_runtime, width=0.5, color=bar_colors)\n\nax.set_xticks(np.linspace(0, len(cls_names) - 1, len(cls_names)))\nax.set_xticklabels(cls_names, fontsize=8)\nplt.setp(plt.xticks()[1], rotation=30)\nymax = max(cls_runtime) * 1.2\nax.set_ylim((0, ymax))\nax.set_ylabel(\"runtime (s)\")\nax.set_title(\"Prediction Times (%d instances)\" % n_test_documents)\nautolabel(rectangles)\nplt.tight_layout()\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "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.11.14"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}