|
15 | 15 | "cell_type": "markdown",
|
16 | 16 | "metadata": {},
|
17 | 17 | "source": [
|
18 |
| - "\n# Restricted Boltzmann Machine features for digit classification\n\nFor greyscale image data where pixel values can be interpreted as degrees of\nblackness on a white background, like handwritten digit recognition, the\nBernoulli Restricted Boltzmann machine model (:class:`BernoulliRBM\n<sklearn.neural_network.BernoulliRBM>`) can perform effective non-linear\nfeature extraction.\n\nIn order to learn good latent representations from a small dataset, we\nartificially generate more labeled data by perturbing the training data with\nlinear shifts of 1 pixel in each direction.\n\nThis example shows how to build a classification pipeline with a BernoulliRBM\nfeature extractor and a :class:`LogisticRegression\n<sklearn.linear_model.LogisticRegression>` classifier. The hyperparameters\nof the entire model (learning rate, hidden layer size, regularization)\nwere optimized by grid search, but the search is not reproduced here because\nof runtime constraints.\n\nLogistic regression on raw pixel values is presented for comparison. The\nexample shows that the features extracted by the BernoulliRBM help improve the\nclassification accuracy.\n" |
| 18 | + "\n# Restricted Boltzmann Machine features for digit classification\n\nFor greyscale image data where pixel values can be interpreted as degrees of\nblackness on a white background, like handwritten digit recognition, the\nBernoulli Restricted Boltzmann machine model (:class:`BernoulliRBM\n<sklearn.neural_network.BernoulliRBM>`) can perform effective non-linear\nfeature extraction.\n" |
19 | 19 | ]
|
20 | 20 | },
|
21 | 21 | {
|
|
26 | 26 | },
|
27 | 27 | "outputs": [],
|
28 | 28 | "source": [
|
29 |
| - "# Authors: Yann N. Dauphin, Vlad Niculae, Gabriel Synnaeve\n# License: BSD\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy.ndimage import convolve\nfrom sklearn import linear_model, datasets, metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import BernoulliRBM\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import minmax_scale\nfrom sklearn.base import clone\n\n\n# #############################################################################\n# Setting up\n\n\ndef nudge_dataset(X, Y):\n \"\"\"\n This produces a dataset 5 times bigger than the original one,\n by moving the 8x8 images in X around by 1px to left, right, down, up\n \"\"\"\n direction_vectors = [\n [[0, 1, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [1, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 1], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 1, 0]],\n ]\n\n def shift(x, w):\n return convolve(x.reshape((8, 8)), mode=\"constant\", weights=w).ravel()\n\n X = np.concatenate(\n [X] + [np.apply_along_axis(shift, 1, X, vector) for vector in direction_vectors]\n )\n Y = np.concatenate([Y for _ in range(5)], axis=0)\n return X, Y\n\n\n# Load Data\nX, y = datasets.load_digits(return_X_y=True)\nX = np.asarray(X, \"float32\")\nX, Y = nudge_dataset(X, y)\nX = minmax_scale(X, feature_range=(0, 1)) # 0-1 scaling\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)\n\n# Models we will use\nlogistic = linear_model.LogisticRegression(solver=\"newton-cg\", tol=1)\nrbm = BernoulliRBM(random_state=0, verbose=True)\n\nrbm_features_classifier = Pipeline(steps=[(\"rbm\", rbm), (\"logistic\", logistic)])\n\n# #############################################################################\n# Training\n\n# Hyper-parameters. These were set by cross-validation,\n# using a GridSearchCV. Here we are not performing cross-validation to\n# save time.\nrbm.learning_rate = 0.06\nrbm.n_iter = 10\n# More components tend to give better prediction performance, but larger\n# fitting time\nrbm.n_components = 100\nlogistic.C = 6000\n\n# Training RBM-Logistic Pipeline\nrbm_features_classifier.fit(X_train, Y_train)\n\n# Training the Logistic regression classifier directly on the pixel\nraw_pixel_classifier = clone(logistic)\nraw_pixel_classifier.C = 100.0\nraw_pixel_classifier.fit(X_train, Y_train)\n\n# #############################################################################\n# Evaluation\n\nY_pred = rbm_features_classifier.predict(X_test)\nprint(\n \"Logistic regression using RBM features:\\n%s\\n\"\n % (metrics.classification_report(Y_test, Y_pred))\n)\n\nY_pred = raw_pixel_classifier.predict(X_test)\nprint(\n \"Logistic regression using raw pixel features:\\n%s\\n\"\n % (metrics.classification_report(Y_test, Y_pred))\n)\n\n# #############################################################################\n# Plotting\n\nplt.figure(figsize=(4.2, 4))\nfor i, comp in enumerate(rbm.components_):\n plt.subplot(10, 10, i + 1)\n plt.imshow(comp.reshape((8, 8)), cmap=plt.cm.gray_r, interpolation=\"nearest\")\n plt.xticks(())\n plt.yticks(())\nplt.suptitle(\"100 components extracted by RBM\", fontsize=16)\nplt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)\n\nplt.show()" |
| 29 | + "# Authors: Yann N. Dauphin, Vlad Niculae, Gabriel Synnaeve\n# License: BSD" |
| 30 | + ] |
| 31 | + }, |
| 32 | + { |
| 33 | + "cell_type": "markdown", |
| 34 | + "metadata": {}, |
| 35 | + "source": [ |
| 36 | + "## Generate data\n\nIn order to learn good latent representations from a small dataset, we\nartificially generate more labeled data by perturbing the training data with\nlinear shifts of 1 pixel in each direction.\n\n" |
| 37 | + ] |
| 38 | + }, |
| 39 | + { |
| 40 | + "cell_type": "code", |
| 41 | + "execution_count": null, |
| 42 | + "metadata": { |
| 43 | + "collapsed": false |
| 44 | + }, |
| 45 | + "outputs": [], |
| 46 | + "source": [ |
| 47 | + "import numpy as np\n\nfrom scipy.ndimage import convolve\n\nfrom sklearn import datasets\nfrom sklearn.preprocessing import minmax_scale\n\nfrom sklearn.model_selection import train_test_split\n\n\ndef nudge_dataset(X, Y):\n \"\"\"\n This produces a dataset 5 times bigger than the original one,\n by moving the 8x8 images in X around by 1px to left, right, down, up\n \"\"\"\n direction_vectors = [\n [[0, 1, 0], [0, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [1, 0, 0], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 1], [0, 0, 0]],\n [[0, 0, 0], [0, 0, 0], [0, 1, 0]],\n ]\n\n def shift(x, w):\n return convolve(x.reshape((8, 8)), mode=\"constant\", weights=w).ravel()\n\n X = np.concatenate(\n [X] + [np.apply_along_axis(shift, 1, X, vector) for vector in direction_vectors]\n )\n Y = np.concatenate([Y for _ in range(5)], axis=0)\n return X, Y\n\n\nX, y = datasets.load_digits(return_X_y=True)\nX = np.asarray(X, \"float32\")\nX, Y = nudge_dataset(X, y)\nX = minmax_scale(X, feature_range=(0, 1)) # 0-1 scaling\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)" |
| 48 | + ] |
| 49 | + }, |
| 50 | + { |
| 51 | + "cell_type": "markdown", |
| 52 | + "metadata": {}, |
| 53 | + "source": [ |
| 54 | + "## Models definition\n\nWe build a classification pipeline with a BernoulliRBM feature extractor and\na :class:`LogisticRegression <sklearn.linear_model.LogisticRegression>`\nclassifier.\n\n" |
| 55 | + ] |
| 56 | + }, |
| 57 | + { |
| 58 | + "cell_type": "code", |
| 59 | + "execution_count": null, |
| 60 | + "metadata": { |
| 61 | + "collapsed": false |
| 62 | + }, |
| 63 | + "outputs": [], |
| 64 | + "source": [ |
| 65 | + "from sklearn import linear_model\nfrom sklearn.neural_network import BernoulliRBM\nfrom sklearn.pipeline import Pipeline\n\nlogistic = linear_model.LogisticRegression(solver=\"newton-cg\", tol=1)\nrbm = BernoulliRBM(random_state=0, verbose=True)\n\nrbm_features_classifier = Pipeline(steps=[(\"rbm\", rbm), (\"logistic\", logistic)])" |
| 66 | + ] |
| 67 | + }, |
| 68 | + { |
| 69 | + "cell_type": "markdown", |
| 70 | + "metadata": {}, |
| 71 | + "source": [ |
| 72 | + "## Training\n\nThe hyperparameters of the entire model (learning rate, hidden layer size,\nregularization) were optimized by grid search, but the search is not\nreproduced here because of runtime constraints.\n\n" |
| 73 | + ] |
| 74 | + }, |
| 75 | + { |
| 76 | + "cell_type": "code", |
| 77 | + "execution_count": null, |
| 78 | + "metadata": { |
| 79 | + "collapsed": false |
| 80 | + }, |
| 81 | + "outputs": [], |
| 82 | + "source": [ |
| 83 | + "from sklearn.base import clone\n\n# Hyper-parameters. These were set by cross-validation,\n# using a GridSearchCV. Here we are not performing cross-validation to\n# save time.\nrbm.learning_rate = 0.06\nrbm.n_iter = 10\n\n# More components tend to give better prediction performance, but larger\n# fitting time\nrbm.n_components = 100\nlogistic.C = 6000\n\n# Training RBM-Logistic Pipeline\nrbm_features_classifier.fit(X_train, Y_train)\n\n# Training the Logistic regression classifier directly on the pixel\nraw_pixel_classifier = clone(logistic)\nraw_pixel_classifier.C = 100.0\nraw_pixel_classifier.fit(X_train, Y_train)" |
| 84 | + ] |
| 85 | + }, |
| 86 | + { |
| 87 | + "cell_type": "markdown", |
| 88 | + "metadata": {}, |
| 89 | + "source": [ |
| 90 | + "## Evaluation\n\n" |
| 91 | + ] |
| 92 | + }, |
| 93 | + { |
| 94 | + "cell_type": "code", |
| 95 | + "execution_count": null, |
| 96 | + "metadata": { |
| 97 | + "collapsed": false |
| 98 | + }, |
| 99 | + "outputs": [], |
| 100 | + "source": [ |
| 101 | + "from sklearn import metrics\n\nY_pred = rbm_features_classifier.predict(X_test)\nprint(\n \"Logistic regression using RBM features:\\n%s\\n\"\n % (metrics.classification_report(Y_test, Y_pred))\n)" |
| 102 | + ] |
| 103 | + }, |
| 104 | + { |
| 105 | + "cell_type": "code", |
| 106 | + "execution_count": null, |
| 107 | + "metadata": { |
| 108 | + "collapsed": false |
| 109 | + }, |
| 110 | + "outputs": [], |
| 111 | + "source": [ |
| 112 | + "Y_pred = raw_pixel_classifier.predict(X_test)\nprint(\n \"Logistic regression using raw pixel features:\\n%s\\n\"\n % (metrics.classification_report(Y_test, Y_pred))\n)" |
| 113 | + ] |
| 114 | + }, |
| 115 | + { |
| 116 | + "cell_type": "markdown", |
| 117 | + "metadata": {}, |
| 118 | + "source": [ |
| 119 | + "The features extracted by the BernoulliRBM help improve the classification\naccuracy with respect to the logistic regression on raw pixels.\n\n" |
| 120 | + ] |
| 121 | + }, |
| 122 | + { |
| 123 | + "cell_type": "markdown", |
| 124 | + "metadata": {}, |
| 125 | + "source": [ |
| 126 | + "## Plotting\n\n" |
| 127 | + ] |
| 128 | + }, |
| 129 | + { |
| 130 | + "cell_type": "code", |
| 131 | + "execution_count": null, |
| 132 | + "metadata": { |
| 133 | + "collapsed": false |
| 134 | + }, |
| 135 | + "outputs": [], |
| 136 | + "source": [ |
| 137 | + "import matplotlib.pyplot as plt\n\nplt.figure(figsize=(4.2, 4))\nfor i, comp in enumerate(rbm.components_):\n plt.subplot(10, 10, i + 1)\n plt.imshow(comp.reshape((8, 8)), cmap=plt.cm.gray_r, interpolation=\"nearest\")\n plt.xticks(())\n plt.yticks(())\nplt.suptitle(\"100 components extracted by RBM\", fontsize=16)\nplt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)\n\nplt.show()" |
30 | 138 | ]
|
31 | 139 | }
|
32 | 140 | ],
|
|
0 commit comments