.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/neural_networks/plot_rbm_logistic_classification.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end <sphx_glr_download_auto_examples_neural_networks_plot_rbm_logistic_classification.py>` to download the full example code or to run this example in your browser via JupyterLite or Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_neural_networks_plot_rbm_logistic_classification.py: ============================================================== Restricted Boltzmann Machine features for digit classification ============================================================== For greyscale image data where pixel values can be interpreted as degrees of blackness on a white background, like handwritten digit recognition, the Bernoulli Restricted Boltzmann machine model (:class:`BernoulliRBM <sklearn.neural_network.BernoulliRBM>`) can perform effective non-linear feature extraction. .. GENERATED FROM PYTHON SOURCE LINES 13-17 .. code-block:: Python # Authors: Yann N. Dauphin, Vlad Niculae, Gabriel Synnaeve # License: BSD .. GENERATED FROM PYTHON SOURCE LINES 18-24 Generate data ------------- In order to learn good latent representations from a small dataset, we artificially generate more labeled data by perturbing the training data with linear shifts of 1 pixel in each direction. .. GENERATED FROM PYTHON SOURCE LINES 24-62 .. code-block:: Python import numpy as np from scipy.ndimage import convolve from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import minmax_scale def nudge_dataset(X, Y): """ This produces a dataset 5 times bigger than the original one, by moving the 8x8 images in X around by 1px to left, right, down, up """ direction_vectors = [ [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 1, 0]], ] def shift(x, w): return convolve(x.reshape((8, 8)), mode="constant", weights=w).ravel() X = np.concatenate( [X] + [np.apply_along_axis(shift, 1, X, vector) for vector in direction_vectors] ) Y = np.concatenate([Y for _ in range(5)], axis=0) return X, Y X, y = datasets.load_digits(return_X_y=True) X = np.asarray(X, "float32") X, Y = nudge_dataset(X, y) X = minmax_scale(X, feature_range=(0, 1)) # 0-1 scaling X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0) .. GENERATED FROM PYTHON SOURCE LINES 63-69 Models definition ----------------- We build a classification pipeline with a BernoulliRBM feature extractor and a :class:`LogisticRegression <sklearn.linear_model.LogisticRegression>` classifier. .. GENERATED FROM PYTHON SOURCE LINES 69-79 .. code-block:: Python from sklearn import linear_model from sklearn.neural_network import BernoulliRBM from sklearn.pipeline import Pipeline logistic = linear_model.LogisticRegression(solver="newton-cg", tol=1) rbm = BernoulliRBM(random_state=0, verbose=True) rbm_features_classifier = Pipeline(steps=[("rbm", rbm), ("logistic", logistic)]) .. GENERATED FROM PYTHON SOURCE LINES 80-86 Training -------- The hyperparameters of the entire model (learning rate, hidden layer size, regularization) were optimized by grid search, but the search is not reproduced here because of runtime constraints. .. GENERATED FROM PYTHON SOURCE LINES 86-108 .. code-block:: Python from sklearn.base import clone # Hyper-parameters. These were set by cross-validation, # using a GridSearchCV. Here we are not performing cross-validation to # save time. rbm.learning_rate = 0.06 rbm.n_iter = 10 # More components tend to give better prediction performance, but larger # fitting time rbm.n_components = 100 logistic.C = 6000 # Training RBM-Logistic Pipeline rbm_features_classifier.fit(X_train, Y_train) # Training the Logistic regression classifier directly on the pixel raw_pixel_classifier = clone(logistic) raw_pixel_classifier.C = 100.0 raw_pixel_classifier.fit(X_train, Y_train) .. rst-class:: sphx-glr-script-out .. code-block:: none [BernoulliRBM] Iteration 1, pseudo-likelihood = -25.57, time = 0.09s [BernoulliRBM] Iteration 2, pseudo-likelihood = -23.68, time = 0.13s [BernoulliRBM] Iteration 3, pseudo-likelihood = -22.88, time = 0.13s [BernoulliRBM] Iteration 4, pseudo-likelihood = -21.91, time = 0.13s [BernoulliRBM] Iteration 5, pseudo-likelihood = -21.79, time = 0.13s [BernoulliRBM] Iteration 6, pseudo-likelihood = -20.96, time = 0.13s [BernoulliRBM] Iteration 7, pseudo-likelihood = -20.88, time = 0.13s [BernoulliRBM] Iteration 8, pseudo-likelihood = -20.50, time = 0.14s [BernoulliRBM] Iteration 9, pseudo-likelihood = -20.34, time = 0.12s [BernoulliRBM] Iteration 10, pseudo-likelihood = -20.21, time = 0.12s .. raw:: html <div class="output_subarea output_html rendered_html output_result"> <style>#sk-container-id-59 { /* Definition of color scheme common for light and dark mode */ --sklearn-color-text: black; --sklearn-color-line: gray; /* Definition of color scheme for unfitted estimators */ --sklearn-color-unfitted-level-0: #fff5e6; --sklearn-color-unfitted-level-1: #f6e4d2; --sklearn-color-unfitted-level-2: #ffe0b3; --sklearn-color-unfitted-level-3: chocolate; /* Definition of color scheme for fitted estimators */ --sklearn-color-fitted-level-0: #f0f8ff; --sklearn-color-fitted-level-1: #d4ebff; --sklearn-color-fitted-level-2: #b3dbfd; --sklearn-color-fitted-level-3: cornflowerblue; /* Specific color for light theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black))); --sklearn-color-icon: #696969; @media (prefers-color-scheme: dark) { /* Redefinition of color scheme for dark theme */ --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111))); --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white))); --sklearn-color-icon: #878787; } } #sk-container-id-59 { color: var(--sklearn-color-text); } #sk-container-id-59 pre { padding: 0; } #sk-container-id-59 input.sk-hidden--visually { border: 0; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } #sk-container-id-59 div.sk-dashed-wrapped { border: 1px dashed var(--sklearn-color-line); margin: 0 0.4em 0.5em 0.4em; box-sizing: border-box; padding-bottom: 0.4em; background-color: var(--sklearn-color-background); } #sk-container-id-59 div.sk-container { /* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */ display: inline-block !important; position: relative; } #sk-container-id-59 div.sk-text-repr-fallback { display: none; } div.sk-parallel-item, div.sk-serial, div.sk-item { /* draw centered vertical line to link estimators */ background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background)); background-size: 2px 100%; background-repeat: no-repeat; background-position: center center; } /* Parallel-specific style estimator block */ #sk-container-id-59 div.sk-parallel-item::after { content: ""; width: 100%; border-bottom: 2px solid var(--sklearn-color-text-on-default-background); flex-grow: 1; } #sk-container-id-59 div.sk-parallel { display: flex; align-items: stretch; justify-content: center; background-color: var(--sklearn-color-background); position: relative; } #sk-container-id-59 div.sk-parallel-item { display: flex; flex-direction: column; } #sk-container-id-59 div.sk-parallel-item:first-child::after { align-self: flex-end; width: 50%; } #sk-container-id-59 div.sk-parallel-item:last-child::after { align-self: flex-start; width: 50%; } #sk-container-id-59 div.sk-parallel-item:only-child::after { width: 0; } /* Serial-specific style estimator block */ #sk-container-id-59 div.sk-serial { display: flex; flex-direction: column; align-items: center; background-color: var(--sklearn-color-background); padding-right: 1em; padding-left: 1em; } /* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is clickable and can be expanded/collapsed. - Pipeline and ColumnTransformer use this feature and define the default style - Estimators will overwrite some part of the style using the `sk-estimator` class */ /* Pipeline and ColumnTransformer style (default) */ #sk-container-id-59 div.sk-toggleable { /* Default theme specific background. It is overwritten whether we have a specific estimator or a Pipeline/ColumnTransformer */ background-color: var(--sklearn-color-background); } /* Toggleable label */ #sk-container-id-59 label.sk-toggleable__label { cursor: pointer; display: block; width: 100%; margin-bottom: 0; padding: 0.5em; box-sizing: border-box; text-align: center; } #sk-container-id-59 label.sk-toggleable__label-arrow:before { /* Arrow on the left of the label */ content: "▸"; float: left; margin-right: 0.25em; color: var(--sklearn-color-icon); } #sk-container-id-59 label.sk-toggleable__label-arrow:hover:before { color: var(--sklearn-color-text); } /* Toggleable content - dropdown */ #sk-container-id-59 div.sk-toggleable__content { max-height: 0; max-width: 0; overflow: hidden; text-align: left; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-59 div.sk-toggleable__content.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-59 div.sk-toggleable__content pre { margin: 0.2em; border-radius: 0.25em; color: var(--sklearn-color-text); /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-59 div.sk-toggleable__content.fitted pre { /* unfitted */ background-color: var(--sklearn-color-fitted-level-0); } #sk-container-id-59 input.sk-toggleable__control:checked~div.sk-toggleable__content { /* Expand drop-down */ max-height: 200px; max-width: 100%; overflow: auto; } #sk-container-id-59 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before { content: "▾"; } /* Pipeline/ColumnTransformer-specific style */ #sk-container-id-59 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-59 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: var(--sklearn-color-fitted-level-2); } /* Estimator-specific style */ /* Colorize estimator box */ #sk-container-id-59 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-59 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } #sk-container-id-59 div.sk-label label.sk-toggleable__label, #sk-container-id-59 div.sk-label label { /* The background is the default theme color */ color: var(--sklearn-color-text-on-default-background); } /* On hover, darken the color of the background */ #sk-container-id-59 div.sk-label:hover label.sk-toggleable__label { color: var(--sklearn-color-text); background-color: var(--sklearn-color-unfitted-level-2); } /* Label box, darken color on hover, fitted */ #sk-container-id-59 div.sk-label.fitted:hover label.sk-toggleable__label.fitted { color: var(--sklearn-color-text); background-color: var(--sklearn-color-fitted-level-2); } /* Estimator label */ #sk-container-id-59 div.sk-label label { font-family: monospace; font-weight: bold; display: inline-block; line-height: 1.2em; } #sk-container-id-59 div.sk-label-container { text-align: center; } /* Estimator-specific */ #sk-container-id-59 div.sk-estimator { font-family: monospace; border: 1px dotted var(--sklearn-color-border-box); border-radius: 0.25em; box-sizing: border-box; margin-bottom: 0.5em; /* unfitted */ background-color: var(--sklearn-color-unfitted-level-0); } #sk-container-id-59 div.sk-estimator.fitted { /* fitted */ background-color: var(--sklearn-color-fitted-level-0); } /* on hover */ #sk-container-id-59 div.sk-estimator:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-2); } #sk-container-id-59 div.sk-estimator.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-2); } /* Specification for estimator info (e.g. "i" and "?") */ /* Common style for "i" and "?" */ .sk-estimator-doc-link, a:link.sk-estimator-doc-link, a:visited.sk-estimator-doc-link { float: right; font-size: smaller; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1em; height: 1em; width: 1em; text-decoration: none !important; margin-left: 1ex; /* unfitted */ border: var(--sklearn-color-unfitted-level-1) 1pt solid; color: var(--sklearn-color-unfitted-level-1); } .sk-estimator-doc-link.fitted, a:link.sk-estimator-doc-link.fitted, a:visited.sk-estimator-doc-link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ div.sk-estimator:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover, div.sk-label-container:hover .sk-estimator-doc-link:hover, .sk-estimator-doc-link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover, div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover, .sk-estimator-doc-link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } /* Span, style for the box shown on hovering the info icon */ .sk-estimator-doc-link span { display: none; z-index: 9999; position: relative; font-weight: normal; right: .2ex; padding: .5ex; margin: .5ex; width: min-content; min-width: 20ex; max-width: 50ex; color: var(--sklearn-color-text); box-shadow: 2pt 2pt 4pt #999; /* unfitted */ background: var(--sklearn-color-unfitted-level-0); border: .5pt solid var(--sklearn-color-unfitted-level-3); } .sk-estimator-doc-link.fitted span { /* fitted */ background: var(--sklearn-color-fitted-level-0); border: var(--sklearn-color-fitted-level-3); } .sk-estimator-doc-link:hover span { display: block; } /* "?"-specific style due to the `<a>` HTML tag */ #sk-container-id-59 a.estimator_doc_link { float: right; font-size: 1rem; line-height: 1em; font-family: monospace; background-color: var(--sklearn-color-background); border-radius: 1rem; height: 1rem; width: 1rem; text-decoration: none; /* unfitted */ color: var(--sklearn-color-unfitted-level-1); border: var(--sklearn-color-unfitted-level-1) 1pt solid; } #sk-container-id-59 a.estimator_doc_link.fitted { /* fitted */ border: var(--sklearn-color-fitted-level-1) 1pt solid; color: var(--sklearn-color-fitted-level-1); } /* On hover */ #sk-container-id-59 a.estimator_doc_link:hover { /* unfitted */ background-color: var(--sklearn-color-unfitted-level-3); color: var(--sklearn-color-background); text-decoration: none; } #sk-container-id-59 a.estimator_doc_link.fitted:hover { /* fitted */ background-color: var(--sklearn-color-fitted-level-3); } </style><div id="sk-container-id-59" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>LogisticRegression(C=100.0, solver='newton-cg', tol=1)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class="sk-container" hidden><div class="sk-item"><div class="sk-estimator fitted sk-toggleable"><input class="sk-toggleable__control sk-hidden--visually" id="sk-estimator-id-243" type="checkbox" checked><label for="sk-estimator-id-243" class="sk-toggleable__label fitted sk-toggleable__label-arrow fitted"> LogisticRegression<a class="sk-estimator-doc-link fitted" rel="noreferrer" target="_blank" href="https://scikit-learn.org/1.4/modules/generated/sklearn.linear_model.LogisticRegression.html">?<span>Documentation for LogisticRegression</span></a><span class="sk-estimator-doc-link fitted">i<span>Fitted</span></span></label><div class="sk-toggleable__content fitted"><pre>LogisticRegression(C=100.0, solver='newton-cg', tol=1)</pre></div> </div></div></div></div> </div> <br /> <br /> .. GENERATED FROM PYTHON SOURCE LINES 109-111 Evaluation ---------- .. GENERATED FROM PYTHON SOURCE LINES 111-120 .. code-block:: Python from sklearn import metrics Y_pred = rbm_features_classifier.predict(X_test) print( "Logistic regression using RBM features:\n%s\n" % (metrics.classification_report(Y_test, Y_pred)) ) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/circleci/project/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior. /home/circleci/project/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior. /home/circleci/project/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior. Logistic regression using RBM features: precision recall f1-score support 0 0.10 1.00 0.18 174 1 0.00 0.00 0.00 184 2 0.00 0.00 0.00 166 3 0.00 0.00 0.00 194 4 0.00 0.00 0.00 186 5 0.00 0.00 0.00 181 6 0.00 0.00 0.00 207 7 0.00 0.00 0.00 154 8 0.00 0.00 0.00 182 9 0.00 0.00 0.00 169 accuracy 0.10 1797 macro avg 0.01 0.10 0.02 1797 weighted avg 0.01 0.10 0.02 1797 .. GENERATED FROM PYTHON SOURCE LINES 121-127 .. code-block:: Python Y_pred = raw_pixel_classifier.predict(X_test) print( "Logistic regression using raw pixel features:\n%s\n" % (metrics.classification_report(Y_test, Y_pred)) ) .. rst-class:: sphx-glr-script-out .. code-block:: none /home/circleci/project/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior. /home/circleci/project/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior. /home/circleci/project/sklearn/metrics/_classification.py:1509: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior. Logistic regression using raw pixel features: precision recall f1-score support 0 0.10 1.00 0.18 174 1 0.00 0.00 0.00 184 2 0.00 0.00 0.00 166 3 0.00 0.00 0.00 194 4 0.00 0.00 0.00 186 5 0.00 0.00 0.00 181 6 0.00 0.00 0.00 207 7 0.00 0.00 0.00 154 8 0.00 0.00 0.00 182 9 0.00 0.00 0.00 169 accuracy 0.10 1797 macro avg 0.01 0.10 0.02 1797 weighted avg 0.01 0.10 0.02 1797 .. GENERATED FROM PYTHON SOURCE LINES 128-130 The features extracted by the BernoulliRBM help improve the classification accuracy with respect to the logistic regression on raw pixels. .. GENERATED FROM PYTHON SOURCE LINES 132-134 Plotting -------- .. GENERATED FROM PYTHON SOURCE LINES 134-147 .. code-block:: Python import matplotlib.pyplot as plt plt.figure(figsize=(4.2, 4)) for i, comp in enumerate(rbm.components_): plt.subplot(10, 10, i + 1) plt.imshow(comp.reshape((8, 8)), cmap=plt.cm.gray_r, interpolation="nearest") plt.xticks(()) plt.yticks(()) plt.suptitle("100 components extracted by RBM", fontsize=16) plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23) plt.show() .. image-sg:: /auto_examples/neural_networks/images/sphx_glr_plot_rbm_logistic_classification_001.png :alt: 100 components extracted by RBM :srcset: /auto_examples/neural_networks/images/sphx_glr_plot_rbm_logistic_classification_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 2.779 seconds) .. _sphx_glr_download_auto_examples_neural_networks_plot_rbm_logistic_classification.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/scikit-learn/scikit-learn/1.4.X?urlpath=lab/tree/notebooks/auto_examples/neural_networks/plot_rbm_logistic_classification.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../../lite/lab/?path=auto_examples/neural_networks/plot_rbm_logistic_classification.ipynb :alt: Launch JupyterLite :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_rbm_logistic_classification.ipynb <plot_rbm_logistic_classification.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_rbm_logistic_classification.py <plot_rbm_logistic_classification.py>` .. include:: plot_rbm_logistic_classification.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_