{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Lasso on dense and sparse data\n\n\nWe show that linear_model.Lasso provides the same results for dense and sparse\ndata and that in the case of sparse data the speed is improved.\n\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "print(__doc__)\n\nfrom time import time\nfrom scipy import sparse\nfrom scipy import linalg\n\nfrom sklearn.datasets.samples_generator import make_regression\nfrom sklearn.linear_model import Lasso\n\n\n# #############################################################################\n# The two Lasso implementations on Dense data\nprint(\"--- Dense matrices\")\n\nX, y = make_regression(n_samples=200, n_features=5000, random_state=0)\nX_sp = sparse.coo_matrix(X)\n\nalpha = 1\nsparse_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=1000)\ndense_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=1000)\n\nt0 = time()\nsparse_lasso.fit(X_sp, y)\nprint(\"Sparse Lasso done in %fs\" % (time() - t0))\n\nt0 = time()\ndense_lasso.fit(X, y)\nprint(\"Dense Lasso done in %fs\" % (time() - t0))\n\nprint(\"Distance between coefficients : %s\"\n      % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_))\n\n# #############################################################################\n# The two Lasso implementations on Sparse data\nprint(\"--- Sparse matrices\")\n\nXs = X.copy()\nXs[Xs < 2.5] = 0.0\nXs = sparse.coo_matrix(Xs)\nXs = Xs.tocsc()\n\nprint(\"Matrix density : %s %%\" % (Xs.nnz / float(X.size) * 100))\n\nalpha = 0.1\nsparse_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=10000)\ndense_lasso = Lasso(alpha=alpha, fit_intercept=False, max_iter=10000)\n\nt0 = time()\nsparse_lasso.fit(Xs, y)\nprint(\"Sparse Lasso done in %fs\" % (time() - t0))\n\nt0 = time()\ndense_lasso.fit(Xs.toarray(), y)\nprint(\"Dense Lasso done in %fs\" % (time() - t0))\n\nprint(\"Distance between coefficients : %s\"\n      % linalg.norm(sparse_lasso.coef_ - dense_lasso.coef_))"
      ]
    }
  ],
  "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.6.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}