Repository: scikit-learn/scikit-learn
Pull request: DOC simpler block delimitation in sphinx-gallery examples
Closes https://github.com/scikit-learn/scikit-learn/issues/17063

On Linux,
```
find examples/ -name "*.py" -exec sed -i 's/#\s*#\{5,100\}/# %%/g' {} +
```
(the syntax is slightly different for sed version installed on MacOS cf [SO](https://unix.stackexchange.com/a/36805)) 

cc @thomasjpfan 

Problem statement:
Replace "######" separators by "# %%" in gallery
Just noticed this was a feature in sphinx-gallery, I think I prefer the `# %%` over the `######`:


```py
###############################################################################
# Using the prediction pipeline in a grid search
```

vs 

```py
# %%
# Using the prediction pipeline in a grid search
```

Hints from issue discussion:
Yes, I think it would make reading examples in text format much nicer! Made a PR in https://github.com/scikit-learn/scikit-learn/pull/17068

Commit message: Fix merge conflict

Patch to review:
diff --git a/examples/applications/plot_face_recognition.py b/examples/applications/plot_face_recognition.py
index 64a18601cd710..1bb8d8ae9d94d 100644
--- a/examples/applications/plot_face_recognition.py
+++ b/examples/applications/plot_face_recognition.py
@@ -72,7 +72,7 @@
 
 # #############################################################################
 # Split into a training set and a test set using a stratified k fold
-
+#
 # split into a training and testing set
 X_train, X_test, y_train, y_test = train_test_split(
     X, y, test_size=0.25, random_state=42)
diff --git a/examples/applications/plot_out_of_core_classification.py b/examples/applications/plot_out_of_core_classification.py
index 0c89a31a64b0b..14fb2d260a61f 100644
--- a/examples/applications/plot_out_of_core_classification.py
+++ b/examples/applications/plot_out_of_core_classification.py
@@ -43,7 +43,7 @@ def _not_in_sphinx():
     # Hack to detect whether we are running by the sphinx builder
     return '__file__' in globals()
 
-###############################################################################
+# %%
 # Reuters Dataset related routines
 # --------------------------------
 #
@@ -178,7 +178,7 @@ def progress(blocknum, bs, size):
             yield doc
 
 
-###############################################################################
+# %%
 # Main
 # ----
 #
@@ -311,7 +311,7 @@ def progress(cls_name, stats):
         print('\n')
 
 
-###############################################################################
+# %%
 # Plot results
 # ------------
 #
diff --git a/examples/applications/plot_outlier_detection_wine.py b/examples/applications/plot_outlier_detection_wine.py
index 6f245b7e6c1cb..d649cd18a3a84 100644
--- a/examples/applications/plot_outlier_detection_wine.py
+++ b/examples/applications/plot_outlier_detection_wine.py
@@ -94,7 +94,7 @@
 
 plt.show()
 
-##############################################################################
+# %%
 # Second example
 # --------------
 # The second example shows the ability of the Minimum Covariance Determinant
diff --git a/examples/applications/plot_stock_market.py b/examples/applications/plot_stock_market.py
index f7c3569d15808..7c39bf209ee77 100644
--- a/examples/applications/plot_stock_market.py
+++ b/examples/applications/plot_stock_market.py
@@ -78,7 +78,7 @@
 
 # #############################################################################
 # Retrieve the data from Internet
-
+#
 # The data is from 2003 - 2008. This is reasonably calm: (not too long ago so
 # that we get high-tech firms, and before the 2008 crash). This kind of
 # historical data can be obtained for from APIs like the quandl.com and
@@ -164,6 +164,7 @@
 # Learn a graphical structure from the correlations
 edge_model = covariance.GraphicalLassoCV()
 
+# %%
 # standardize the time series: using correlations rather than covariance
 # is more efficient for structure recovery
 X = variation.copy().T
@@ -182,7 +183,7 @@
 # #############################################################################
 # Find a low-dimension embedding for visualization: find the best position of
 # the nodes (the stocks) on a 2D plane
-
+#
 # We use a dense eigen_solver to achieve reproducibility (arpack is
 # initiated with random vectors that we don't control). In addition, we
 # use a large number of neighbors to capture the large-scale structure.
@@ -223,6 +224,7 @@
 lc.set_linewidths(15 * values)
 ax.add_collection(lc)
 
+# %%
 # Add a label to each node. The challenge here is that we want to
 # position the labels to avoid overlap with other labels
 for index, (name, label, (x, y)) in enumerate(
diff --git a/examples/cluster/plot_coin_segmentation.py b/examples/cluster/plot_coin_segmentation.py
index bda1d717b2479..18213148a92aa 100644
--- a/examples/cluster/plot_coin_segmentation.py
+++ b/examples/cluster/plot_coin_segmentation.py
@@ -66,7 +66,7 @@
 # installed)
 N_REGIONS = 25
 
-#############################################################################
+# %%
 # Visualize the resulting regions
 
 for assign_labels in ('kmeans', 'discretize'):
diff --git a/examples/cluster/plot_linkage_comparison.py b/examples/cluster/plot_linkage_comparison.py
index 471132a0f222f..81e1c8201b883 100644
--- a/examples/cluster/plot_linkage_comparison.py
+++ b/examples/cluster/plot_linkage_comparison.py
@@ -35,7 +35,7 @@
 
 np.random.seed(0)
 
-######################################################################
+# %%
 # Generate datasets. We choose the size big enough to see the scalability
 # of the algorithms, but not too big to avoid too long running times
 
@@ -58,9 +58,9 @@
                              cluster_std=[1.0, 2.5, 0.5],
                              random_state=random_state)
 
-######################################################################
+# %%
 # Run the clustering and plot
-
+#
 # Set up cluster parameters
 plt.figure(figsize=(9 * 1.3 + 2, 14.5))
 plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05,
diff --git a/examples/cluster/plot_mean_shift.py b/examples/cluster/plot_mean_shift.py
index dce7b35503232..8d869c642ecd4 100644
--- a/examples/cluster/plot_mean_shift.py
+++ b/examples/cluster/plot_mean_shift.py
@@ -23,7 +23,7 @@
 
 # #############################################################################
 # Compute clustering with MeanShift
-
+#
 # The following bandwidth can be automatically detected using
 bandwidth = estimate_bandwidth(X, quantile=0.2, n_samples=500)
 
diff --git a/examples/compose/plot_column_transformer_mixed_types.py b/examples/compose/plot_column_transformer_mixed_types.py
index 1c79c4bb1d607..cb8e1979ae21e 100644
--- a/examples/compose/plot_column_transformer_mixed_types.py
+++ b/examples/compose/plot_column_transformer_mixed_types.py
@@ -44,9 +44,9 @@
 # X = titanic.frame.drop('survived', axis=1)
 # y = titanic.frame['survived']
 
-###############################################################################
+# %%
 # Use ``ColumnTransformer`` by selecting column by names
-###############################################################################
+# %%
 # We will train our classifier with the following features:
 #
 # Numeric Features:
@@ -87,9 +87,9 @@
 clf.fit(X_train, y_train)
 print("model score: %.3f" % clf.score(X_test, y_test))
 
-###############################################################################
+# %%
 # Use ``ColumnTransformer`` by selecting column by data types
-###############################################################################
+# %%
 # When dealing with a cleaned dataset, the preprocessing can be automatic by
 # using the data types of the column to decide whether to treat a column as a
 # numerical or categorical feature.
@@ -100,19 +100,19 @@
 subset_feature = ['embarked', 'sex', 'pclass', 'age', 'fare']
 X = X[subset_feature]
 
-###############################################################################
+# %%
 # Then, we introspect the information regarding each column data type.
 
 X.info()
 
-###############################################################################
+# %%
 # We can observe that the `embarked` and `sex` columns were tagged as
 # `category` columns when loading the data with ``fetch_openml``. Therefore, we
 # can use this information to dispatch the categorical columns to the
 # ``categorical_transformer`` and the remaining columns to the
 # ``numerical_transformer``.
 
-###############################################################################
+# %%
 # .. note:: In practice, you will have to handle yourself the column data type.
 #    If you want some columns to be considered as `category`, you will have to
 #    convert them into categorical columns. If you are using pandas, you can
@@ -132,9 +132,9 @@
 clf.fit(X_train, y_train)
 print("model score: %.3f" % clf.score(X_test, y_test))
 
-###############################################################################
+# %%
 # Using the prediction pipeline in a grid search
-###############################################################################
+# %%
 # Grid search can also be performed on the different preprocessing steps
 # defined in the ``ColumnTransformer`` object, together with the classifier's
 # hyperparameters as part of the ``Pipeline``.
diff --git a/examples/compose/plot_compare_reduction.py b/examples/compose/plot_compare_reduction.py
index af9f7b2eb8832..dc38f2f9f1b20 100755
--- a/examples/compose/plot_compare_reduction.py
+++ b/examples/compose/plot_compare_reduction.py
@@ -20,9 +20,9 @@
 Note that the use of ``memory`` to enable caching becomes interesting when the
 fitting of a transformer is costly.
 
-###############################################################################
+# %%
 Illustration of ``Pipeline`` and ``GridSearchCV``
-###############################################################################
+# %%
 
 This section illustrates the use of a ``Pipeline`` with ``GridSearchCV``
 """
@@ -89,9 +89,9 @@
 
 plt.show()
 
-###############################################################################
+# %%
 # Caching transformers within a ``Pipeline``
-###############################################################################
+# %%
 # It is sometimes worthwhile storing the state of a specific transformer
 # since it could be used again. Using a pipeline in ``GridSearchCV`` triggers
 # such situations. Therefore, we use the argument ``memory`` to enable caching.
@@ -119,7 +119,7 @@
 memory.clear(warn=False)
 rmtree(location)
 
-###############################################################################
+# %%
 # The ``PCA`` fitting is only computed at the evaluation of the first
 # configuration of the ``C`` parameter of the ``LinearSVC`` classifier. The
 # other configurations of ``C`` will trigger the loading of the cached ``PCA``
diff --git a/examples/compose/plot_transformed_target.py b/examples/compose/plot_transformed_target.py
index 120948e9d685c..93dfe179d4890 100755
--- a/examples/compose/plot_transformed_target.py
+++ b/examples/compose/plot_transformed_target.py
@@ -25,9 +25,9 @@
 
 print(__doc__)
 
-###############################################################################
+# %%
 # Synthetic example
-###############################################################################
+# %%
 
 from sklearn.datasets import make_regression
 from sklearn.model_selection import train_test_split
@@ -42,7 +42,7 @@
 else:
     density_param = {'normed': True}
 
-###############################################################################
+# %%
 # A synthetic random regression problem is generated. The targets ``y`` are
 # modified by: (i) translating all targets such that all entries are
 # non-negative and (ii) applying an exponential function to obtain non-linear
@@ -56,7 +56,7 @@
 y = np.exp((y + abs(y.min())) / 200)
 y_trans = np.log1p(y)
 
-###############################################################################
+# %%
 # The following illustrate the probability density functions of the target
 # before and after applying the logarithmic functions.
 
@@ -78,7 +78,7 @@
 
 X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
 
-###############################################################################
+# %%
 # At first, a linear model will be applied on the original targets. Due to the
 # non-linearity, the model trained will not be precise during the
 # prediction. Subsequently, a logarithmic function is used to linearize the
@@ -120,11 +120,11 @@
 f.suptitle("Synthetic data", y=0.035)
 f.tight_layout(rect=[0.05, 0.05, 0.95, 0.95])
 
-###############################################################################
+# %%
 # Real-world data set
-###############################################################################
+# %%
 
-###############################################################################
+# %%
 # In a similar manner, the boston housing data set is used to show the impact
 # of transforming the targets before learning a model. In this example, the
 # targets to be predicted corresponds to the weighted distances to the five
@@ -142,7 +142,7 @@
                              output_distribution='normal',
                              copy=True).squeeze()
 
-###############################################################################
+# %%
 # A :class:`sklearn.preprocessing.QuantileTransformer` is used such that the
 # targets follows a normal distribution before applying a
 # :class:`sklearn.linear_model.RidgeCV` model.
@@ -164,7 +164,7 @@
 
 X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)
 
-###############################################################################
+# %%
 # The effect of the transformer is weaker than on the synthetic data. However,
 # the transform induces a decrease of the MAE.
 
diff --git a/examples/covariance/plot_covariance_estimation.py b/examples/covariance/plot_covariance_estimation.py
index d33b77d68a438..a94fcff404b57 100644
--- a/examples/covariance/plot_covariance_estimation.py
+++ b/examples/covariance/plot_covariance_estimation.py
@@ -66,7 +66,7 @@
 
 # #############################################################################
 # Compute the likelihood on test data
-
+#
 # spanning a range of possible shrinkage coefficient values
 shrinkages = np.logspace(-2, 0, 30)
 negative_logliks = [-ShrunkCovariance(shrinkage=s).fit(X_train).score(X_test)
@@ -80,7 +80,7 @@
 
 # #############################################################################
 # Compare different approaches to setting the parameter
-
+#
 # GridSearch for an optimal shrinkage coefficient
 tuned_parameters = [{'shrinkage': shrinkages}]
 cv = GridSearchCV(ShrunkCovariance(), tuned_parameters)
diff --git a/examples/covariance/plot_lw_vs_oas.py b/examples/covariance/plot_lw_vs_oas.py
index 04506917b524e..f9cd11bbb81b4 100644
--- a/examples/covariance/plot_lw_vs_oas.py
+++ b/examples/covariance/plot_lw_vs_oas.py
@@ -29,7 +29,7 @@
 from sklearn.covariance import LedoitWolf, OAS
 
 np.random.seed(0)
-###############################################################################
+# %%
 n_features = 100
 # simulation covariance matrix (AR(1) process)
 r = 0.1
diff --git a/examples/cross_decomposition/plot_compare_cross_decomposition.py b/examples/cross_decomposition/plot_compare_cross_decomposition.py
index 04c44f1721805..8703fc2f300b4 100644
--- a/examples/cross_decomposition/plot_compare_cross_decomposition.py
+++ b/examples/cross_decomposition/plot_compare_cross_decomposition.py
@@ -48,7 +48,7 @@
 
 # #############################################################################
 # Canonical (symmetric) PLS
-
+#
 # Transform data
 # ~~~~~~~~~~~~~~
 plsca = PLSCanonical(n_components=2)
@@ -56,6 +56,7 @@
 X_train_r, Y_train_r = plsca.transform(X_train, Y_train)
 X_test_r, Y_test_r = plsca.transform(X_test, Y_test)
 
+# %%
 # Scatter plot of scores
 # ~~~~~~~~~~~~~~~~~~~~~~
 # 1) On diagonal plot X vs Y scores on each components
diff --git a/examples/ensemble/plot_gradient_boosting_early_stopping.py b/examples/ensemble/plot_gradient_boosting_early_stopping.py
index 0ffa36cd0b154..660346e0bb589 100644
--- a/examples/ensemble/plot_gradient_boosting_early_stopping.py
+++ b/examples/ensemble/plot_gradient_boosting_early_stopping.py
@@ -91,7 +91,7 @@
 index = np.arange(0, n * bar_width, bar_width) * 2.5
 index = index[0:n]
 
-#######################################################################
+# %%
 # Compare scores with and without early stopping
 # ----------------------------------------------
 
@@ -129,7 +129,7 @@ def autolabel(rects, n_estimators):
 plt.show()
 
 
-#######################################################################
+# %%
 # Compare fit times with and without early stopping
 # -------------------------------------------------
 
diff --git a/examples/ensemble/plot_gradient_boosting_regression.py b/examples/ensemble/plot_gradient_boosting_regression.py
index 860bb14687534..c95aa82df86a1 100644
--- a/examples/ensemble/plot_gradient_boosting_regression.py
+++ b/examples/ensemble/plot_gradient_boosting_regression.py
@@ -28,7 +28,7 @@
 from sklearn.metrics import mean_squared_error
 from sklearn.model_selection import train_test_split
 
-##############################################################################
+# %%
 # Load the data
 # -------------------------------------
 #
@@ -37,7 +37,7 @@
 diabetes = datasets.load_diabetes()
 X, y = diabetes.data, diabetes.target
 
-##############################################################################
+# %%
 # Data preprocessing
 # -------------------------------------
 #
@@ -69,7 +69,7 @@
           'learning_rate': 0.01,
           'loss': 'ls'}
 
-##############################################################################
+# %%
 # Fit regression model
 # -------------------------------------
 #
@@ -82,7 +82,7 @@
 mse = mean_squared_error(y_test, reg.predict(X_test))
 print("The mean squared error (MSE) on test set: {:.4f}".format(mse))
 
-##############################################################################
+# %%
 # Plot training deviance
 # -------------------------------------
 #
@@ -106,7 +106,7 @@
 fig.tight_layout()
 plt.show()
 
-##############################################################################
+# %%
 # Plot feature importance
 # -------------------------------------
 #
diff --git a/examples/ensemble/plot_stack_predictors.py b/examples/ensemble/plot_stack_predictors.py
index 3d2ff4a38ddd7..f9107cd5aae1c 100644
--- a/examples/ensemble/plot_stack_predictors.py
+++ b/examples/ensemble/plot_stack_predictors.py
@@ -22,9 +22,9 @@
 # License: BSD 3 clause
 
 
-###############################################################################
+# %%
 # Download the dataset
-###############################################################################
+# %%
 #
 # We will use `Ames Housing`_ dataset which was first compiled by Dean De Cock
 # and became better known after it was used in Kaggle challenge. It is a set
@@ -68,9 +68,9 @@ def load_ames_housing():
 X, y = load_ames_housing()
 
 
-###############################################################################
+# %%
 # Make pipeline to preprocess the data
-###############################################################################
+# %%
 #
 # Before we can use Ames dataset we still need to do some preprocessing.
 # First, the dataset has many missing values. To impute them, we will exchange
@@ -136,9 +136,9 @@ def load_ames_housing():
     remainder='passthrough')
 
 
-###############################################################################
+# %%
 # Stack of predictors on a single data set
-###############################################################################
+# %%
 #
 # It is sometimes tedious to find the model which will best perform on a given
 # dataset. Stacking provide an alternative by combining the outputs of several
@@ -181,9 +181,9 @@ def load_ames_housing():
                                        final_estimator=RidgeCV())
 
 
-###############################################################################
+# %%
 # Measure and plot the results
-###############################################################################
+# %%
 #
 # Now we can use Ames Housing dataset to make the predictions. We check the
 # performance of each individual predictor as well as of the stack of the
@@ -250,7 +250,7 @@ def plot_regression_results(ax, y_true, y_pred, title, scores, elapsed_time):
 plt.subplots_adjust(top=0.9)
 plt.show()
 
-###############################################################################
+# %%
 # The stacked regressor will combine the strengths of the different regressors.
 # However, we also see that training the stacked regressor is much more
 # computationally expensive.
diff --git a/examples/ensemble/plot_voting_regressor.py b/examples/ensemble/plot_voting_regressor.py
index 2587dee4352e9..106efbac2461d 100644
--- a/examples/ensemble/plot_voting_regressor.py
+++ b/examples/ensemble/plot_voting_regressor.py
@@ -32,7 +32,7 @@
 from sklearn.linear_model import LinearRegression
 from sklearn.ensemble import VotingRegressor
 
-##############################################################################
+# %%
 # Training classifiers
 # --------------------------------
 #
@@ -54,7 +54,7 @@
 ereg = VotingRegressor([('gb', reg1), ('rf', reg2), ('lr', reg3)])
 ereg.fit(X, y)
 
-##############################################################################
+# %%
 # Making predictions
 # --------------------------------
 #
@@ -67,7 +67,7 @@
 pred3 = reg3.predict(xt)
 pred4 = ereg.predict(xt)
 
-##############################################################################
+# %%
 # Plot the results
 # --------------------------------
 #
diff --git a/examples/exercises/plot_cv_diabetes.py b/examples/exercises/plot_cv_diabetes.py
index d71abd8fe6455..27762c3023038 100644
--- a/examples/exercises/plot_cv_diabetes.py
+++ b/examples/exercises/plot_cv_diabetes.py
@@ -53,7 +53,7 @@
 
 # #############################################################################
 # Bonus: how much can you trust the selection of alpha?
-
+#
 # To answer this question we use the LassoCV object that sets its alpha
 # parameter automatically from the data by internal cross-validation (i.e. it
 # performs cross-validation on the training data it receives).
diff --git a/examples/feature_selection/plot_feature_selection.py b/examples/feature_selection/plot_feature_selection.py
index 1e4ef6a81bba8..0cb6c449acc7b 100644
--- a/examples/feature_selection/plot_feature_selection.py
+++ b/examples/feature_selection/plot_feature_selection.py
@@ -33,7 +33,7 @@
 
 # #############################################################################
 # Import some data to play with
-
+#
 # The iris dataset
 X, y = load_iris(return_X_y=True)
 
diff --git a/examples/feature_selection/plot_select_from_model_diabetes.py b/examples/feature_selection/plot_select_from_model_diabetes.py
index 0a7e46448a22c..f44669cfc4317 100644
--- a/examples/feature_selection/plot_select_from_model_diabetes.py
+++ b/examples/feature_selection/plot_select_from_model_diabetes.py
@@ -31,7 +31,7 @@
 from sklearn.feature_selection import SelectFromModel
 from sklearn.linear_model import LassoCV
 
-##############################################################################
+# %%
 # Load the data
 # ---------------------------------------------------------
 #
@@ -47,7 +47,7 @@
 feature_names = diabetes.feature_names
 print(feature_names)
 
-##############################################################################
+# %%
 # Find importance of the features
 # ---------------------------------------------------------
 #
@@ -59,7 +59,7 @@
 importance = np.abs(clf.coef_)
 print(importance)
 
-##############################################################################
+# %%
 # Select from the model features with the higest score
 # ---------------------------------------------------------
 #
@@ -82,7 +82,7 @@
 
 n_features = sfm.transform(X).shape[1]
 
-##############################################################################
+# %%
 # Plot the two most important features
 # ---------------------------------------------------------
 #
diff --git a/examples/impute/plot_missing_values.py b/examples/impute/plot_missing_values.py
index 2ba7dc05d16b6..ca7f1e2d59289 100644
--- a/examples/impute/plot_missing_values.py
+++ b/examples/impute/plot_missing_values.py
@@ -32,9 +32,9 @@
 # Authors: Maria Telenczuk  <https://github.com/maikia>
 # License: BSD 3 clause
 
-###############################################################################
+# %%
 # Download the data and make missing values sets
-################################################
+# %%
 #
 # First we download the two datasets. Diabetes dataset is shipped with
 # scikit-learn. It has 442 entries, each with 10 features. California Housing
@@ -83,7 +83,7 @@ def add_missing_values(X_full, y_full):
     X_diabetes, y_diabetes)
 
 
-###############################################################################
+# %%
 # Impute the missing data and score
 # #################################
 # Now we will write a function which will score the results on the differently
@@ -104,7 +104,7 @@ def add_missing_values(X_full, y_full):
 N_SPLITS = 5
 regressor = RandomForestRegressor(random_state=0)
 
-###############################################################################
+# %%
 # Missing information
 # -------------------
 # In addition to imputing the missing values, the imputers have an
@@ -132,7 +132,7 @@ def get_scores_for_imputer(imputer, X_missing, y_missing):
 mses_diabetes = np.zeros(5)
 stds_diabetes = np.zeros(5)
 
-###############################################################################
+# %%
 # Estimate the score
 # ------------------
 # First, we want to estimate the score on the original data:
@@ -151,7 +151,7 @@ def get_full_score(X_full, y_full):
 mses_diabetes[0], stds_diabetes[0] = get_full_score(X_diabetes, y_diabetes)
 
 
-###############################################################################
+# %%
 # Replace missing values by 0
 # ---------------------------
 #
@@ -174,7 +174,7 @@ def get_impute_zero_score(X_missing, y_missing):
                                                            y_miss_diabetes)
 
 
-###############################################################################
+# %%
 # kNN-imputation of the missing values
 # ------------------------------------
 #
@@ -193,7 +193,7 @@ def get_impute_knn_score(X_missing, y_missing):
                                                           y_miss_diabetes)
 
 
-###############################################################################
+# %%
 # Impute missing values with mean
 # -------------------------------
 #
@@ -211,7 +211,7 @@ def get_impute_mean(X_missing, y_missing):
                                                      y_miss_diabetes)
 
 
-###############################################################################
+# %%
 # Iterative imputation of the missing values
 # ------------------------------------------
 #
@@ -241,7 +241,7 @@ def get_impute_iterative(X_missing, y_missing):
 mses_diabetes = mses_diabetes * -1
 mses_california = mses_california * -1
 
-###############################################################################
+# %%
 # Plot the results
 # ################
 #
diff --git a/examples/inspection/plot_linear_model_coefficient_interpretation.py b/examples/inspection/plot_linear_model_coefficient_interpretation.py
index 7583bfa0a052f..93a5b430a3542 100644
--- a/examples/inspection/plot_linear_model_coefficient_interpretation.py
+++ b/examples/inspection/plot_linear_model_coefficient_interpretation.py
@@ -36,7 +36,7 @@
 import matplotlib.pyplot as plt
 import seaborn as sns
 
-#############################################################################
+# %%
 # The dataset: wages
 # ------------------
 #
@@ -48,27 +48,27 @@
 
 survey = fetch_openml(data_id=534, as_frame=True)
 
-##############################################################################
+# %%
 # Then, we identify features `X` and targets `y`: the column WAGE is our
 # target variable (i.e., the variable which we want to predict).
 #
 X = survey.data[survey.feature_names]
 X.describe(include="all")
 
-##############################################################################
+# %%
 # Note that the dataset contains categorical and numerical variables.
 # We will need to take this into account when preprocessing the dataset
 # thereafter.
 
 X.head()
 
-##############################################################################
+# %%
 # Our target for prediction: the wage.
 # Wages are described as floating-point number in dollars per hour.
 y = survey.target.values.ravel()
 survey.target.head()
 
-###############################################################################
+# %%
 # We split the sample into a train and a test dataset.
 # Only the train dataset will be used in the following exploratory analysis.
 # This is a way to emulate a real situation where predictions are performed on
@@ -81,7 +81,7 @@
     X, y, random_state=42
 )
 
-##############################################################################
+# %%
 # First, let's get some insights by looking at the variable distributions and
 # at the pairwise relationships between them. Only numerical
 # variables will be used. In the following plot, each dot represents a sample.
@@ -92,7 +92,7 @@
 train_dataset.insert(0, "WAGE", y_train)
 _ = sns.pairplot(train_dataset, kind='reg', diag_kind='kde')
 
-##############################################################################
+# %%
 # Looking closely at the WAGE distribution reveals that it has a
 # long tail. For this reason, we should take its logarithm
 # to turn it approximately into a normal distribution (linear models such
@@ -115,7 +115,7 @@
 
 survey.data.info()
 
-#############################################################################
+# %%
 # As seen previously, the dataset contains columns with different data types
 # and we need to apply a specific preprocessing for each data types.
 # In particular categorical variables cannot be included in linear model if not
@@ -140,7 +140,7 @@
     remainder='passthrough'
 )
 
-##############################################################################
+# %%
 # To describe the dataset as a linear model we use a ridge regressor
 # with a very small regularization and to model the logarithm of the WAGE.
 
@@ -158,7 +158,7 @@
     )
 )
 
-##############################################################################
+# %%
 # Processing the dataset
 # ----------------------
 #
@@ -166,7 +166,7 @@
 
 _ = model.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # Then we check the performance of the computed model plotting its predictions
 # on the test set and computing,
 # for example, the median absolute error of the model.
@@ -190,7 +190,7 @@
 plt.xlim([0, 27])
 _ = plt.ylim([0, 27])
 
-##############################################################################
+# %%
 # The model learnt is far from being a good model making accurate predictions:
 # this is obvious when looking at the plot above, where good predictions
 # should lie on the red line.
@@ -219,7 +219,7 @@
 
 coefs
 
-##############################################################################
+# %%
 # The AGE coefficient is expressed in "dollars/hour per living years" while the
 # EDUCATION one is expressed in "dollars/hour per years of education". This
 # representation of the coefficients has the benefit of making clear the
@@ -238,7 +238,7 @@
 plt.axvline(x=0, color='.5')
 plt.subplots_adjust(left=.3)
 
-###############################################################################
+# %%
 # Indeed, from the plot above the most important factor in determining WAGE
 # appears to be the
 # variable UNION, even if our intuition might tell us that variables
@@ -260,7 +260,7 @@
 plt.title('Features std. dev.')
 plt.subplots_adjust(left=.3)
 
-###############################################################################
+# %%
 # Multiplying the coefficients by the standard deviation of the related
 # feature would reduce all the coefficients to the same unit of measure.
 # As we will see :ref:`after<scaling_num>` this is equivalent to normalize
@@ -282,7 +282,7 @@
 plt.axvline(x=0, color='.5')
 plt.subplots_adjust(left=.3)
 
-###############################################################################
+# %%
 # Now that the coefficients have been scaled, we can safely compare them.
 #
 # .. warning::
@@ -332,7 +332,7 @@
 plt.title('Coefficient importance and its variability')
 plt.subplots_adjust(left=.3)
 
-###############################################################################
+# %%
 # The problem of correlated variables
 # -----------------------------------
 #
@@ -355,7 +355,7 @@
 _ = plt.title('Co-variations of coefficients for AGE and EXPERIENCE '
               'across folds')
 
-###############################################################################
+# %%
 # Two regions are populated: when the EXPERIENCE coefficient is
 # positive the AGE one is negative and viceversa.
 #
@@ -383,7 +383,7 @@
 plt.xlabel('Coefficient importance')
 plt.subplots_adjust(left=.3)
 
-###############################################################################
+# %%
 # The estimation of the EXPERIENCE coefficient is now less variable and
 # remain important for all models trained during cross-validation.
 #
@@ -407,7 +407,7 @@
     remainder='passthrough'
 )
 
-###############################################################################
+# %%
 # The model will stay unchanged.
 
 model = make_pipeline(
@@ -421,7 +421,7 @@
 
 _ = model.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # Again, we check the performance of the computed
 # model using, for example, the median absolute error of the model and the R
 # squared coefficient.
@@ -444,7 +444,7 @@
 plt.xlim([0, 27])
 _ = plt.ylim([0, 27])
 
-##############################################################################
+# %%
 # For the coefficient analysis, scaling is not needed this time.
 
 coefs = pd.DataFrame(
@@ -456,7 +456,7 @@
 plt.axvline(x=0, color='.5')
 plt.subplots_adjust(left=.3)
 
-##############################################################################
+# %%
 # We now inspect the coefficients across several cross-validation folds.
 
 cv_model = cross_validate(
@@ -475,7 +475,7 @@
 plt.title('Coefficient variability')
 plt.subplots_adjust(left=.3)
 
-##############################################################################
+# %%
 # The result is quite similar to the non-normalized case.
 #
 # Linear models with regularization
@@ -503,12 +503,12 @@
 
 _ = model.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # First we check which value of :math:`\alpha` has been selected.
 
 model[-1].regressor_.alpha_
 
-##############################################################################
+# %%
 # Then we check the quality of the predictions.
 
 y_pred = model.predict(X_train)
@@ -530,7 +530,7 @@
 plt.xlim([0, 27])
 _ = plt.ylim([0, 27])
 
-##############################################################################
+# %%
 # The ability to reproduce the data of the regularized model is similar to
 # the one of the non-regularized model.
 
@@ -543,7 +543,7 @@
 plt.axvline(x=0, color='.5')
 plt.subplots_adjust(left=.3)
 
-##############################################################################
+# %%
 # The coefficients are significantly different.
 # AGE and EXPERIENCE coefficients are both positive but they now have less
 # influence on the prediction.
@@ -578,7 +578,7 @@
 _ = plt.title('Co-variations of coefficients for AGE and EXPERIENCE '
               'across folds')
 
-##############################################################################
+# %%
 # Linear models with sparse coefficients
 # --------------------------------------
 #
@@ -604,12 +604,12 @@
 
 _ = model.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # First we verify which value of :math:`\alpha` has been selected.
 
 model[-1].regressor_.alpha_
 
-##############################################################################
+# %%
 # Then we check the quality of the predictions.
 
 y_pred = model.predict(X_train)
@@ -631,7 +631,7 @@
 plt.xlim([0, 27])
 _ = plt.ylim([0, 27])
 
-##############################################################################
+# %%
 # For our dataset, again the model is not very predictive.
 
 coefs = pd.DataFrame(
@@ -643,7 +643,7 @@
 plt.axvline(x=0, color='.5')
 plt.subplots_adjust(left=.3)
 
-#############################################################################
+# %%
 # A Lasso model identifies the correlation between
 # AGE and EXPERIENCE and suppresses one of them for the sake of the prediction.
 #
diff --git a/examples/inspection/plot_partial_dependence.py b/examples/inspection/plot_partial_dependence.py
index d74c6363dec06..6ec316192b835 100644
--- a/examples/inspection/plot_partial_dependence.py
+++ b/examples/inspection/plot_partial_dependence.py
@@ -46,7 +46,7 @@
 from sklearn.datasets import fetch_california_housing
 
 
-##############################################################################
+# %%
 # California Housing data preprocessing
 # -------------------------------------
 #
@@ -63,7 +63,7 @@
 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1,
                                                     random_state=0)
 
-##############################################################################
+# %%
 # Partial Dependence computation for multi-layer perceptron
 # ---------------------------------------------------------
 #
@@ -80,7 +80,7 @@
 print("done in {:.3f}s".format(time() - tic))
 print("Test R2 score: {:.2f}".format(est.score(X_test, y_test)))
 
-##############################################################################
+# %%
 # We configured a pipeline to scale the numerical input features and tuned the
 # neural network size and learning rate to get a reasonable compromise between
 # training time and predictive performance on a test set.
@@ -114,7 +114,7 @@
              'for the California housing dataset, with MLPRegressor')
 fig.subplots_adjust(hspace=0.3)
 
-##############################################################################
+# %%
 # Partial Dependence computation for Gradient Boosting
 # ----------------------------------------------------
 #
@@ -128,7 +128,7 @@
 print("done in {:.3f}s".format(time() - tic))
 print("Test R2 score: {:.2f}".format(est.score(X_test, y_test)))
 
-##############################################################################
+# %%
 # Here, we used the default hyperparameters for the gradient boosting model
 # without any preprocessing as tree-based models are naturally robust to
 # monotonic transformations of numerical features.
@@ -155,7 +155,7 @@
 fig.subplots_adjust(wspace=0.4, hspace=0.3)
 
 
-##############################################################################
+# %%
 # Analysis of the plots
 # ---------------------
 #
@@ -185,7 +185,7 @@
 # nearly independent of the house age, whereas for values less than two there
 # is a strong dependence on age.
 
-##############################################################################
+# %%
 # 3D interaction plots
 # --------------------
 #
diff --git a/examples/inspection/plot_permutation_importance.py b/examples/inspection/plot_permutation_importance.py
index 095a95dac0a65..d708aa0fd6756 100644
--- a/examples/inspection/plot_permutation_importance.py
+++ b/examples/inspection/plot_permutation_importance.py
@@ -37,7 +37,7 @@
 from sklearn.preprocessing import OneHotEncoder
 
 
-##############################################################################
+# %%
 # Data Loading and Feature Engineering
 # ------------------------------------
 # Let's use pandas to load a copy of the titanic dataset. The following shows
@@ -81,7 +81,7 @@
 ])
 rf.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # Accuracy of the Model
 # ---------------------
 # Prior to inspecting the feature importances, it is important to check that
@@ -106,7 +106,7 @@
 print("RF test accuracy: %0.3f" % rf.score(X_test, y_test))
 
 
-##############################################################################
+# %%
 # Tree's Feature Importance from Mean Decrease in Impurity (MDI)
 # --------------------------------------------------------------
 # The impurity-based feature importance ranks the numerical features to be the
@@ -141,7 +141,7 @@
 plt.show()
 
 
-##############################################################################
+# %%
 # As an alternative, the permutation importances of ``rf`` are computed on a
 # held out test set. This shows that the low cardinality categorical feature,
 # ``sex`` is the most important feature.
@@ -159,7 +159,7 @@
 fig.tight_layout()
 plt.show()
 
-##############################################################################
+# %%
 # It is also possible to compute the permutation importances on the training
 # set. This reveals that ``random_num`` gets a significantly higher importance
 # ranking than when computed on the test set. The difference between those two
diff --git a/examples/inspection/plot_permutation_importance_multicollinear.py b/examples/inspection/plot_permutation_importance_multicollinear.py
index 5f832ffbd4228..42ed258d76296 100644
--- a/examples/inspection/plot_permutation_importance_multicollinear.py
+++ b/examples/inspection/plot_permutation_importance_multicollinear.py
@@ -29,7 +29,7 @@
 from sklearn.inspection import permutation_importance
 from sklearn.model_selection import train_test_split
 
-##############################################################################
+# %%
 # Random Forest Feature Importance on Breast Cancer Data
 # ------------------------------------------------------
 # First, we train a random forest on the breast cancer dataset and evaluate
@@ -42,7 +42,7 @@
 clf.fit(X_train, y_train)
 print("Accuracy on test data: {:.2f}".format(clf.score(X_test, y_test)))
 
-##############################################################################
+# %%
 # Next, we plot the tree based feature importance and the permutation
 # importance. The permutation importance plot shows that permuting a feature
 # drops the accuracy by at most `0.012`, which would suggest that none of the
@@ -68,7 +68,7 @@
 fig.tight_layout()
 plt.show()
 
-##############################################################################
+# %%
 # Handling Multicollinear Features
 # --------------------------------
 # When features are collinear, permutating one feature will have little
@@ -92,7 +92,7 @@
 fig.tight_layout()
 plt.show()
 
-##############################################################################
+# %%
 # Next, we manually pick a threshold by visual inspection of the dendrogram
 # to group our features into clusters and choose a feature from each cluster to
 # keep, select those features from our dataset, and train a new random forest.
diff --git a/examples/linear_model/plot_ard.py b/examples/linear_model/plot_ard.py
index 177bd8ce24ad1..255b5c7b8ced1 100644
--- a/examples/linear_model/plot_ard.py
+++ b/examples/linear_model/plot_ard.py
@@ -32,7 +32,7 @@
 
 # #############################################################################
 # Generating simulated data with Gaussian weights
-
+#
 # Parameters of the example
 np.random.seed(0)
 n_samples, n_features = 100, 100
diff --git a/examples/linear_model/plot_lasso_model_selection.py b/examples/linear_model/plot_lasso_model_selection.py
index 73fc94fb94600..f46541aebe65a 100644
--- a/examples/linear_model/plot_lasso_model_selection.py
+++ b/examples/linear_model/plot_lasso_model_selection.py
@@ -98,7 +98,7 @@ def plot_ic_criterion(model, name, color):
 
 # #############################################################################
 # LassoCV: coordinate descent
-
+#
 # Compute paths
 print("Computing regularization path using the coordinate descent lasso...")
 t1 = time.time()
@@ -125,7 +125,7 @@ def plot_ic_criterion(model, name, color):
 
 # #############################################################################
 # LassoLarsCV: least angle regression
-
+#
 # Compute paths
 print("Computing regularization path using the Lars lasso...")
 t1 = time.time()
diff --git a/examples/linear_model/plot_poisson_regression_non_normal_loss.py b/examples/linear_model/plot_poisson_regression_non_normal_loss.py
index 3a24b55848013..721b6f6598d14 100644
--- a/examples/linear_model/plot_poisson_regression_non_normal_loss.py
+++ b/examples/linear_model/plot_poisson_regression_non_normal_loss.py
@@ -58,7 +58,7 @@
 df = fetch_openml(data_id=41214, as_frame=True).frame
 df
 
-##############################################################################
+# %%
 # The number of claims (``ClaimNb``) is a positive integer that can be modeled
 # as a Poisson distribution. It is then assumed to be the number of discrete
 # events occurring with a constant rate in a given time interval (``Exposure``,
@@ -85,7 +85,7 @@
 ax2.set_title("Frequency (number of claims per year)")
 _ = df["Frequency"].hist(bins=30, log=True, ax=ax2)
 
-##############################################################################
+# %%
 # The remaining columns can be used to predict the frequency of claim events.
 # Those columns are very heterogeneous with a mix of categorical and numeric
 # variables with different scales, possibly very unevenly distributed.
@@ -118,8 +118,7 @@
     remainder="drop",
 )
 
-
-##############################################################################
+# %%
 # A constant prediction baseline
 # ------------------------------
 #
@@ -183,7 +182,7 @@ def score_estimator(estimator, df_test):
 print("Constant mean frequency evaluation:")
 score_estimator(dummy, df_test)
 
-##############################################################################
+# %%
 # (Generalized) Linear models
 # ---------------------------
 #
@@ -201,7 +200,7 @@ def score_estimator(estimator, df_test):
 ]).fit(df_train, df_train["Frequency"],
        regressor__sample_weight=df_train["Exposure"])
 
-##############################################################################
+# %%
 # The Poisson deviance cannot be computed on non-positive values predicted by
 # the model. For models that do return a few non-positive predictions (e.g.
 # :class:`~sklearn.linear_model.Ridge`) we ignore the corresponding samples,
@@ -212,7 +211,7 @@ def score_estimator(estimator, df_test):
 print("Ridge evaluation:")
 score_estimator(ridge_glm, df_test)
 
-##############################################################################
+# %%
 # Next we fit the Poisson regressor on the target variable. We set the
 # regularization strength ``alpha`` to approximately 1e-6 over number of
 # samples (i.e. `1e-12`) in order to mimic the Ridge regressor whose L2 penalty
@@ -232,7 +231,7 @@ def score_estimator(estimator, df_test):
 print("PoissonRegressor evaluation:")
 score_estimator(poisson_glm, df_test)
 
-##############################################################################
+# %%
 # Finally, we will consider a non-linear model, namely Gradient Boosting
 # Regression Trees. Tree-based models do not require the categorical data to be
 # one-hot encoded: instead, we can encode each category label with an arbitrary
@@ -275,8 +274,7 @@ def score_estimator(estimator, df_test):
 print("Poisson Gradient Boosted Trees evaluation:")
 score_estimator(poisson_gbrt, df_test)
 
-
-##############################################################################
+# %%
 # Like the Poisson GLM above, the gradient boosted trees model minimizes
 # the Poisson deviance. However, because of a higher predictive power,
 # it reaches lower values of Poisson deviance.
@@ -316,7 +314,7 @@ def score_estimator(estimator, df_test):
         )
 plt.tight_layout()
 
-##############################################################################
+# %%
 # The experimental data presents a long tail distribution for ``y``. In all
 # models, we predict the expected frequency of a random variable, so we will
 # have necessarily fewer extreme values than for the observed realizations of
@@ -428,7 +426,7 @@ def _mean_frequency_by_risk_group(y_true, y_pred, sample_weight=None,
     axi.legend()
 plt.tight_layout()
 
-###############################################################################
+# %%
 # The dummy regression model predicts a constant frequency. This model does not
 # attribute the same tied rank to all samples but is none-the-less globally
 # well calibrated (to estimate the mean frequency of the entire population).
@@ -508,7 +506,7 @@ def lorenz_curve(y_true, y_pred, exposure):
 )
 ax.legend(loc="upper left")
 
-##############################################################################
+# %%
 # As expected, the dummy regressor is unable to correctly rank the samples and
 # therefore performs the worst on this plot.
 #
diff --git a/examples/linear_model/plot_tweedie_regression_insurance_claims.py b/examples/linear_model/plot_tweedie_regression_insurance_claims.py
index ccd18c8efff99..7a82c3b027275 100644
--- a/examples/linear_model/plot_tweedie_regression_insurance_claims.py
+++ b/examples/linear_model/plot_tweedie_regression_insurance_claims.py
@@ -191,7 +191,7 @@ def score_estimator(
     return res
 
 
-##############################################################################
+# %%
 # Loading datasets, basic feature extraction and target definitions
 # -----------------------------------------------------------------
 #
@@ -245,7 +245,7 @@ def score_estimator(
 with pd.option_context("display.max_columns", 15):
     print(df[df.ClaimAmount > 0].head())
 
-##############################################################################
+# %%
 #
 # Frequency model -- Poisson distribution
 # ---------------------------------------
@@ -278,7 +278,7 @@ def score_estimator(
 print("Evaluation of PoissonRegressor on target Frequency")
 print(scores)
 
-##############################################################################
+# %%
 # We can visually compare observed and predicted values, aggregated by the
 # drivers age (``DrivAge``), vehicle age (``VehAge``) and the insurance
 # bonus/malus (``BonusMalus``).
@@ -334,7 +334,7 @@ def score_estimator(
 )
 
 
-##############################################################################
+# %%
 # According to the observed data, the frequency of accidents is higher for
 # drivers younger than 30 years old, and is positively correlated with the
 # `BonusMalus` variable. Our model is able to mostly correctly model this
@@ -376,7 +376,7 @@ def score_estimator(
 print("Evaluation of GammaRegressor on target AvgClaimAmount")
 print(scores)
 
-##############################################################################
+# %%
 # Here, the scores for the test data call for caution as they are
 # significantly worse than for the training data indicating an overfit despite
 # the strong regularization.
@@ -393,7 +393,7 @@ def score_estimator(
       % glm_sev.predict(X_train).mean())
 
 
-##############################################################################
+# %%
 # We can visually compare observed and predicted values, aggregated for
 # the drivers age (``DrivAge``).
 
@@ -423,7 +423,7 @@ def score_estimator(
 )
 plt.tight_layout()
 
-##############################################################################
+# %%
 # Overall, the drivers age (``DrivAge``) has a weak impact on the claim
 # severity, both in observed and predicted data.
 #
@@ -491,7 +491,7 @@ def score_estimator(
 with pd.option_context('display.expand_frame_repr', False):
     print(scores)
 
-##############################################################################
+# %%
 # In this example, both modeling approaches yield comparable performance
 # metrics. For implementation reasons, the percentage of explained variance
 # :math:`D^2` is not available for the product model.
@@ -522,7 +522,7 @@ def score_estimator(
 
 print(pd.DataFrame(res).set_index("subset").T)
 
-##############################################################################
+# %%
 # Finally, we can compare the two models using a plot of cumulated claims: for
 # each model, the policyholders are ranked from safest to riskiest and the
 # fraction of observed total cumulated claims is plotted on the y axis. This
diff --git a/examples/miscellaneous/plot_display_object_visualization.py b/examples/miscellaneous/plot_display_object_visualization.py
index 32ea3ef2d1120..e48e526efc38f 100644
--- a/examples/miscellaneous/plot_display_object_visualization.py
+++ b/examples/miscellaneous/plot_display_object_visualization.py
@@ -15,7 +15,7 @@
 """
 print(__doc__)
 
-##############################################################################
+# %%
 # Load Data and train model
 # -------------------------
 # For this example, we load a blood transfusion service center data set from
@@ -35,9 +35,9 @@
 clf = make_pipeline(StandardScaler(), LogisticRegression(random_state=0))
 clf.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # Create :class:`ConfusionMatrixDisplay`
-##############################################################################
+# %%
 # With the fitted model, we compute the predictions of the model on the test
 # dataset. These predictions are used to compute the confustion matrix which
 # is plotted with the :class:`ConfusionMatrixDisplay`
@@ -50,9 +50,9 @@
 cm_display = ConfusionMatrixDisplay(cm).plot()
 
 
-##############################################################################
+# %%
 # Create :class:`RocCurveDisplay`
-##############################################################################
+# %%
 # The roc curve requires either the probabilities or the non-thresholded
 # decision values from the estimator. Since the logistic regression provides
 # a decision function, we will use it to plot the roc curve:
@@ -63,9 +63,9 @@
 fpr, tpr, _ = roc_curve(y_test, y_score, pos_label=clf.classes_[1])
 roc_display = RocCurveDisplay(fpr=fpr, tpr=tpr).plot()
 
-##############################################################################
+# %%
 # Create :class:`PrecisionRecallDisplay`
-##############################################################################
+# %%
 # Similarly, the precision recall curve can be plotted using `y_score` from
 # the prevision sections.
 from sklearn.metrics import precision_recall_curve
@@ -75,9 +75,9 @@
                                          pos_label=clf.classes_[1])
 pr_display = PrecisionRecallDisplay(precision=prec, recall=recall).plot()
 
-##############################################################################
+# %%
 # Combining the display objects into a single plot
-##############################################################################
+# %%
 # The display objects store the computed values that were passed as arguments.
 # This allows for the visualizations to be easliy combined using matplotlib's
 # API. In the following example, we place the displays next to each other in a
diff --git a/examples/miscellaneous/plot_johnson_lindenstrauss_bound.py b/examples/miscellaneous/plot_johnson_lindenstrauss_bound.py
index 9d369c6c6d46d..4ca9ed976edba 100644
--- a/examples/miscellaneous/plot_johnson_lindenstrauss_bound.py
+++ b/examples/miscellaneous/plot_johnson_lindenstrauss_bound.py
@@ -32,7 +32,7 @@
 else:
     density_param = {'normed': True}
 
-##########################################################
+# %%
 # Theoretical bounds
 # ==================
 # The distortion introduced by a random projection `p` is asserted by
@@ -76,7 +76,7 @@
 plt.show()
 
 
-##########################################################
+# %%
 # The second plot shows that an increase of the admissible
 # distortion ``eps`` allows to reduce drastically the minimal number of
 # dimensions ``n_components`` for a given number of samples ``n_samples``
@@ -99,7 +99,7 @@
 plt.title("Johnson-Lindenstrauss bounds:\nn_components vs eps")
 plt.show()
 
-##########################################################
+# %%
 # Empirical validation
 # ====================
 #
@@ -124,7 +124,7 @@
 else:
     data = fetch_20newsgroups_vectorized().data[:500]
 
-##########################################################
+# %%
 # For each value of ``n_components``, we plot:
 #
 # - 2D distribution of sample pairs with pairwise distances in original
@@ -186,7 +186,7 @@
 plt.show()
 
 
-##########################################################
+# %%
 # We can see that for low values of ``n_components`` the distribution is wide
 # with many distorted pairs and a skewed distribution (due to the hard
 # limit of zero ratio on the left as distances are always positives)
@@ -194,7 +194,7 @@
 # and the distances are well preserved by the random projection.
 
 
-##########################################################
+# %%
 # Remarks
 # =======
 #
diff --git a/examples/miscellaneous/plot_kernel_approximation.py b/examples/miscellaneous/plot_kernel_approximation.py
index 6643be0d22ad2..bf61d64f04cf5 100644
--- a/examples/miscellaneous/plot_kernel_approximation.py
+++ b/examples/miscellaneous/plot_kernel_approximation.py
@@ -29,7 +29,7 @@
 
 """
 
-###########################################################################
+# %%
 # Python package and dataset imports, load dataset
 # ---------------------------------------------------
 
@@ -55,7 +55,7 @@
 digits = datasets.load_digits(n_class=9)
 
 
-##################################################################
+# %%
 # Timing and accuracy plots
 # --------------------------------------------------
 # To apply an classifier on this data, we need to flatten the image, to
@@ -165,7 +165,7 @@
 plt.show()
 
 
-############################################################################
+# %%
 # Decision Surfaces of RBF Kernel SVM and Linear SVM
 # --------------------------------------------------------
 # The second plot visualized the decision surfaces of the RBF kernel SVM and
diff --git a/examples/miscellaneous/plot_partial_dependence_visualization_api.py b/examples/miscellaneous/plot_partial_dependence_visualization_api.py
index 761dad8b1e1fa..c78cecd83727f 100644
--- a/examples/miscellaneous/plot_partial_dependence_visualization_api.py
+++ b/examples/miscellaneous/plot_partial_dependence_visualization_api.py
@@ -25,7 +25,7 @@
 from sklearn.inspection import plot_partial_dependence
 
 
-##############################################################################
+# %%
 # Train models on the diabetes dataset
 # ================================================
 #
@@ -43,7 +43,7 @@
 tree.fit(X, y)
 mlp.fit(X, y)
 
-##############################################################################
+# %%
 # Plotting partial dependence for two features
 # ============================================
 #
@@ -56,7 +56,7 @@
 ax.set_title("Decision Tree")
 tree_disp = plot_partial_dependence(tree, X, ["age", "bmi"], ax=ax)
 
-##############################################################################
+# %%
 # The partial depdendence curves can be plotted for the multi-layer perceptron.
 # In this case, `line_kw` is passed to
 # :func:`~sklearn.inspection.plot_partial_dependence` to change the color of
@@ -66,7 +66,7 @@
 mlp_disp = plot_partial_dependence(mlp, X, ["age", "bmi"], ax=ax,
                                    line_kw={"c": "red"})
 
-##############################################################################
+# %%
 # Plotting partial dependence of the two models together
 # ======================================================
 #
@@ -91,7 +91,7 @@
 mlp_disp.plot(ax=ax2, line_kw={"c": "red"})
 ax2.set_title("Multi-layer Perceptron")
 
-##############################################################################
+# %%
 # Another way to compare the curves is to plot them on top of each other. Here,
 # we create a figure with one row and two columns. The axes are passed into the
 # :func:`~sklearn.inspection.PartialDependenceDisplay.plot` function as a list,
@@ -107,7 +107,7 @@
 ax1.legend()
 ax2.legend()
 
-##############################################################################
+# %%
 # `tree_disp.axes_` is a numpy array container the axes used to draw the
 # partial dependence plots. This can be passed to `mlp_disp` to have the same
 # affect of drawing the plots on top of each other. Furthermore, the
@@ -123,7 +123,7 @@
 tree_disp.axes_[0, 1].legend()
 plt.show()
 
-##############################################################################
+# %%
 # Plotting partial dependence for one feature
 # ===========================================
 #
diff --git a/examples/miscellaneous/plot_roc_curve_visualization_api.py b/examples/miscellaneous/plot_roc_curve_visualization_api.py
index 67592c12ec845..90fc064931ea7 100644
--- a/examples/miscellaneous/plot_roc_curve_visualization_api.py
+++ b/examples/miscellaneous/plot_roc_curve_visualization_api.py
@@ -9,7 +9,7 @@
 """
 print(__doc__)
 
-##############################################################################
+# %%
 # Load Data and Train a SVC
 # -------------------------
 # First, we load the wine dataset and convert it to a binary classification
@@ -28,7 +28,7 @@
 svc = SVC(random_state=42)
 svc.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # Plotting the ROC Curve
 # ----------------------
 # Next, we plot the ROC curve with a single call to
@@ -38,7 +38,7 @@
 svc_disp = plot_roc_curve(svc, X_test, y_test)
 plt.show()
 
-##############################################################################
+# %%
 # Training a Random Forest and Plotting the ROC Curve
 # --------------------------------------------------------
 # We train a random forest classifier and create a plot comparing it to the SVC
diff --git a/examples/model_selection/plot_cv_indices.py b/examples/model_selection/plot_cv_indices.py
index 8dc58a74b84f2..91f71b0451cb2 100644
--- a/examples/model_selection/plot_cv_indices.py
+++ b/examples/model_selection/plot_cv_indices.py
@@ -22,7 +22,7 @@
 cmap_cv = plt.cm.coolwarm
 n_splits = 4
 
-###############################################################################
+# %%
 # Visualize our data
 # ------------------
 #
@@ -61,7 +61,7 @@ def visualize_groups(classes, groups, name):
 
 visualize_groups(y, groups, 'no groups')
 
-###############################################################################
+# %%
 # Define a function to visualize cross-validation behavior
 # --------------------------------------------------------
 #
@@ -102,7 +102,7 @@ def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10):
     return ax
 
 
-###############################################################################
+# %%
 # Let's see how it looks for the :class:`~sklearn.model_selection.KFold`
 # cross-validation object:
 
@@ -110,7 +110,7 @@ def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10):
 cv = KFold(n_splits)
 plot_cv_indices(cv, X, y, groups, ax, n_splits)
 
-###############################################################################
+# %%
 # As you can see, by default the KFold cross-validation iterator does not
 # take either datapoint class or group into consideration. We can change this
 # by using the ``StratifiedKFold`` like so.
@@ -119,7 +119,7 @@ def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10):
 cv = StratifiedKFold(n_splits)
 plot_cv_indices(cv, X, y, groups, ax, n_splits)
 
-###############################################################################
+# %%
 # In this case, the cross-validation retained the same ratio of classes across
 # each CV split. Next we'll visualize this behavior for a number of CV
 # iterators.
diff --git a/examples/model_selection/plot_multi_metric_evaluation.py b/examples/model_selection/plot_multi_metric_evaluation.py
index 922e45d021c30..775d0af9817a8 100644
--- a/examples/model_selection/plot_multi_metric_evaluation.py
+++ b/examples/model_selection/plot_multi_metric_evaluation.py
@@ -29,7 +29,7 @@
 
 print(__doc__)
 
-###############################################################################
+# %%
 # Running ``GridSearchCV`` using multiple evaluation metrics
 # ----------------------------------------------------------
 #
@@ -51,7 +51,7 @@
 gs.fit(X, y)
 results = gs.cv_results_
 
-###############################################################################
+# %%
 # Plotting the result
 # -------------------
 
diff --git a/examples/model_selection/plot_precision_recall.py b/examples/model_selection/plot_precision_recall.py
index 9b71b85e9b37a..620e1d404a2fd 100644
--- a/examples/model_selection/plot_precision_recall.py
+++ b/examples/model_selection/plot_precision_recall.py
@@ -90,7 +90,7 @@
              :func:`sklearn.metrics.precision_score`,
              :func:`sklearn.metrics.f1_score`
 """
-###############################################################################
+# %%
 # In binary classification settings
 # --------------------------------------------------------
 #
@@ -121,7 +121,7 @@
 classifier.fit(X_train, y_train)
 y_score = classifier.decision_function(X_test)
 
-###############################################################################
+# %%
 # Compute the average precision score
 # ...................................
 from sklearn.metrics import average_precision_score
@@ -130,7 +130,7 @@
 print('Average precision-recall score: {0:0.2f}'.format(
       average_precision))
 
-###############################################################################
+# %%
 # Plot the Precision-Recall curve
 # ................................
 from sklearn.metrics import precision_recall_curve
@@ -141,7 +141,7 @@
 disp.ax_.set_title('2-class Precision-Recall curve: '
                    'AP={0:0.2f}'.format(average_precision))
 
-###############################################################################
+# %%
 # In multi-label settings
 # ------------------------
 #
@@ -170,7 +170,7 @@
 y_score = classifier.decision_function(X_test)
 
 
-###############################################################################
+# %%
 # The average precision score in multi-label settings
 # ....................................................
 from sklearn.metrics import precision_recall_curve
@@ -193,7 +193,7 @@
 print('Average precision score, micro-averaged over all classes: {0:0.2f}'
       .format(average_precision["micro"]))
 
-###############################################################################
+# %%
 # Plot the micro-averaged Precision-Recall curve
 # ...............................................
 #
@@ -209,7 +209,7 @@
     'Average precision score, micro-averaged over all classes: AP={0:0.2f}'
     .format(average_precision["micro"]))
 
-###############################################################################
+# %%
 # Plot Precision-Recall curve for each class and iso-f1 curves
 # .............................................................
 #
diff --git a/examples/model_selection/plot_roc.py b/examples/model_selection/plot_roc.py
index d32ab06f7bf25..86ca06eb00445 100644
--- a/examples/model_selection/plot_roc.py
+++ b/examples/model_selection/plot_roc.py
@@ -82,7 +82,7 @@
 roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
 
 
-##############################################################################
+# %%
 # Plot of a ROC curve for a specific class
 plt.figure()
 lw = 2
@@ -98,7 +98,7 @@
 plt.show()
 
 
-##############################################################################
+# %%
 # Plot ROC curves for the multilabel problem
 # ..........................................
 # Compute macro-average ROC curve and ROC area
@@ -146,7 +146,7 @@
 plt.show()
 
 
-##############################################################################
+# %%
 # Area under ROC for the multiclass problem
 # .........................................
 # The :func:`sklearn.metrics.roc_auc_score` function can be used for
diff --git a/examples/model_selection/plot_roc_crossval.py b/examples/model_selection/plot_roc_crossval.py
index e468357da9dec..f3fa6e1371365 100644
--- a/examples/model_selection/plot_roc_crossval.py
+++ b/examples/model_selection/plot_roc_crossval.py
@@ -42,7 +42,7 @@
 
 # #############################################################################
 # Data IO and generation
-
+#
 # Import some data to play with
 iris = datasets.load_iris()
 X = iris.data
@@ -56,7 +56,7 @@
 
 # #############################################################################
 # Classification and ROC analysis
-
+#
 # Run classifier with cross-validation and plot ROC curves
 cv = StratifiedKFold(n_splits=6)
 classifier = svm.SVC(kernel='linear', probability=True,
diff --git a/examples/neighbors/plot_nca_illustration.py b/examples/neighbors/plot_nca_illustration.py
index 1cb482f5e970b..1e1f435e7e57a 100644
--- a/examples/neighbors/plot_nca_illustration.py
+++ b/examples/neighbors/plot_nca_illustration.py
@@ -20,7 +20,7 @@
 
 print(__doc__)
 
-##############################################################################
+# %%
 # Original points
 # ---------------
 # First we create a data set of 9 samples from 3 classes, and plot the points
@@ -71,7 +71,7 @@ def relate_point(X, i, ax):
 relate_point(X, i, ax)
 plt.show()
 
-##############################################################################
+# %%
 # Learning an embedding
 # ---------------------
 # We use :class:`~sklearn.neighbors.NeighborhoodComponentsAnalysis` to learn an
diff --git a/examples/neural_networks/plot_rbm_logistic_classification.py b/examples/neural_networks/plot_rbm_logistic_classification.py
index 6994d3850f2f5..b4cd903935ae7 100644
--- a/examples/neural_networks/plot_rbm_logistic_classification.py
+++ b/examples/neural_networks/plot_rbm_logistic_classification.py
@@ -93,7 +93,7 @@ def shift(x, w):
 
 # #############################################################################
 # Training
-
+#
 # Hyper-parameters. These were set by cross-validation,
 # using a GridSearchCV. Here we are not performing cross-validation to
 # save time.
diff --git a/examples/preprocessing/plot_all_scaling.py b/examples/preprocessing/plot_all_scaling.py
index 6d361f90c244b..e8fd168d13228 100755
--- a/examples/preprocessing/plot_all_scaling.py
+++ b/examples/preprocessing/plot_all_scaling.py
@@ -179,7 +179,7 @@ def plot_distribution(axes, X, y, hist_nbins=50, title="",
                  color='grey', ec='grey')
     hist_X0.axis('off')
 
-###############################################################################
+# %%
 # Two plots will be shown for each scaler/normalizer/transformer. The left
 # figure will show a scatter plot of the full data set while the right figure
 # will exclude the extreme values considering only 99 % of the data set,
@@ -216,7 +216,7 @@ def make_plot(item_idx):
                               label='Color mapping for values of y')
 
 
-########################################################################
+# %%
 # .. _results:
 #
 # Original data
@@ -234,7 +234,7 @@ def make_plot(item_idx):
 
 make_plot(0)
 
-#######################################################################
+# %%
 # StandardScaler
 # --------------
 #
@@ -252,7 +252,7 @@ def make_plot(item_idx):
 
 make_plot(1)
 
-##########################################################################
+# %%
 # MinMaxScaler
 # ------------
 #
@@ -266,7 +266,7 @@ def make_plot(item_idx):
 
 make_plot(2)
 
-#############################################################################
+# %%
 # MaxAbsScaler
 # ------------
 #
@@ -277,7 +277,7 @@ def make_plot(item_idx):
 
 make_plot(3)
 
-##############################################################################
+# %%
 # RobustScaler
 # ------------
 #
@@ -293,7 +293,7 @@ def make_plot(item_idx):
 
 make_plot(4)
 
-##############################################################################
+# %%
 # PowerTransformer
 # ----------------
 #
@@ -310,7 +310,7 @@ def make_plot(item_idx):
 make_plot(5)
 make_plot(6)
 
-##############################################################################
+# %%
 # QuantileTransformer (Gaussian output)
 # -------------------------------------
 #
@@ -321,7 +321,7 @@ def make_plot(item_idx):
 
 make_plot(7)
 
-###################################################################
+# %%
 # QuantileTransformer (uniform output)
 # ------------------------------------
 #
@@ -339,7 +339,7 @@ def make_plot(item_idx):
 
 make_plot(8)
 
-##############################################################################
+# %%
 # Normalizer
 # ----------
 #
diff --git a/examples/release_highlights/plot_release_highlights_0_22_0.py b/examples/release_highlights/plot_release_highlights_0_22_0.py
index 450700d143ca2..fbdc97b0f60d6 100644
--- a/examples/release_highlights/plot_release_highlights_0_22_0.py
+++ b/examples/release_highlights/plot_release_highlights_0_22_0.py
@@ -19,7 +19,7 @@
     conda install scikit-learn
 """
 
-##############################################################################
+# %%
 # New plotting API
 # ----------------
 #
@@ -54,7 +54,7 @@
 
 plt.show()
 
-############################################################################
+# %%
 # Stacking Classifier and Regressor
 # ---------------------------------
 # :class:`~ensemble.StackingClassifier` and
@@ -93,7 +93,7 @@
 )
 clf.fit(X_train, y_train).score(X_test, y_test)
 
-##############################################################################
+# %%
 # Permutation-based feature importance
 # ------------------------------------
 #
@@ -117,7 +117,7 @@
 fig.tight_layout()
 plt.show()
 
-##############################################################################
+# %%
 # Native support for missing values for gradient boosting
 # -------------------------------------------------------
 #
@@ -136,7 +136,7 @@
 gbdt = HistGradientBoostingClassifier(min_samples_leaf=1).fit(X, y)
 print(gbdt.predict(X))
 
-############################################################################
+# %%
 # Precomputed sparse nearest neighbors graph
 # ------------------------------------------
 # Most estimators based on nearest neighbors graphs now accept precomputed
@@ -168,7 +168,7 @@
     estimator.set_params(isomap__n_neighbors=5)
     estimator.fit(X)
 
-##############################################################################
+# %%
 # KNN Based Imputation
 # ------------------------------------
 # We now support imputation for completing missing values using k-Nearest
@@ -191,7 +191,7 @@
 imputer = KNNImputer(n_neighbors=2)
 print(imputer.fit_transform(X))
 
-#############################################################################
+# %%
 # Tree pruning
 # ------------
 #
@@ -209,7 +209,7 @@
 print("Average number of nodes with pruning {:.1f}".format(
     np.mean([e.tree_.node_count for e in rf.estimators_])))
 
-############################################################################
+# %%
 # Retrieve dataframes from OpenML
 # -------------------------------
 # :func:`datasets.fetch_openml` can now return pandas dataframe and thus
@@ -220,7 +220,7 @@
 titanic = fetch_openml('titanic', version=1, as_frame=True)
 print(titanic.data.head()[['pclass', 'embarked']])
 
-############################################################################
+# %%
 # Checking scikit-learn compatibility of an estimator
 # ---------------------------------------------------
 # Developers can check the compatibility of their scikit-learn compatible
@@ -239,7 +239,7 @@
 def test_sklearn_compatible_estimator(estimator, check):
     check(estimator)
 
-############################################################################
+# %%
 # ROC AUC now supports multiclass classification
 # ----------------------------------------------
 # The :func:`roc_auc_score` function can also be used in multi-class
diff --git a/examples/text/plot_document_classification_20newsgroups.py b/examples/text/plot_document_classification_20newsgroups.py
index 1b3b2ab54f9a8..1fe4d1624e8b8 100644
--- a/examples/text/plot_document_classification_20newsgroups.py
+++ b/examples/text/plot_document_classification_20newsgroups.py
@@ -93,7 +93,7 @@ def is_interactive():
 print()
 
 
-##############################################################################
+# %%
 # Load data from the training set
 # ------------------------------------
 # Let's load data from the newsgroups dataset which comprises around 18000
@@ -199,7 +199,7 @@ def trim(s):
     return s if len(s) <= 80 else s[:77] + "..."
 
 
-##############################################################################
+# %%
 # Benchmark classifiers
 # ------------------------------------
 # We train and test the datasets with 15 different classification models
@@ -297,7 +297,7 @@ def benchmark(clf):
   ('classification', LinearSVC(penalty="l2"))])))
 
 
-##############################################################################
+# %%
 # Add plots
 # ------------------------------------
 # The bar plot indicates the accuracy, training time (normalized) and test time
diff --git a/examples/tree/plot_cost_complexity_pruning.py b/examples/tree/plot_cost_complexity_pruning.py
index 1d1f2f80d8826..822d7a206f842 100644
--- a/examples/tree/plot_cost_complexity_pruning.py
+++ b/examples/tree/plot_cost_complexity_pruning.py
@@ -23,7 +23,7 @@
 from sklearn.datasets import load_breast_cancer
 from sklearn.tree import DecisionTreeClassifier
 
-###############################################################################
+# %%
 # Total impurity of leaves vs effective alphas of pruned tree
 # ---------------------------------------------------------------
 # Minimal cost complexity pruning recursively finds the node with the "weakest
@@ -41,7 +41,7 @@
 path = clf.cost_complexity_pruning_path(X_train, y_train)
 ccp_alphas, impurities = path.ccp_alphas, path.impurities
 
-###############################################################################
+# %%
 # In the following plot, the maximum effective alpha value is removed, because
 # it is the trivial tree with only one node.
 fig, ax = plt.subplots()
@@ -50,7 +50,7 @@
 ax.set_ylabel("total impurity of leaves")
 ax.set_title("Total Impurity vs effective alpha for training set")
 
-###############################################################################
+# %%
 # Next, we train a decision tree using the effective alphas. The last value
 # in ``ccp_alphas`` is the alpha value that prunes the whole tree,
 # leaving the tree, ``clfs[-1]``, with one node.
@@ -62,7 +62,7 @@
 print("Number of nodes in the last tree is: {} with ccp_alpha: {}".format(
       clfs[-1].tree_.node_count, ccp_alphas[-1]))
 
-###############################################################################
+# %%
 # For the remainder of this example, we remove the last element in
 # ``clfs`` and ``ccp_alphas``, because it is the trivial tree with only one
 # node. Here we show that the number of nodes and tree depth decreases as alpha
@@ -83,7 +83,7 @@
 ax[1].set_title("Depth vs alpha")
 fig.tight_layout()
 
-###############################################################################
+# %%
 # Accuracy vs alpha for training and testing sets
 # ----------------------------------------------------
 # When ``ccp_alpha`` is set to zero and keeping the other default parameters


Code review comments:
diff_hunk: @@ -32,9 +32,9 @@
 # Authors: Maria Telenczuk  <https://github.com/maikia>
 # License: BSD 3 clause
 
-###############################################################################
+# %%
 # Download the data and make missing values sets
-################################################
+# %%
path: examples/impute/plot_missing_values.py
text: @user1:
This can be reverted. The original was correct.

@user1:
Revert this to make the above a header.

diff_hunk: @@ -164,6 +164,7 @@
 # Learn a graphical structure from the correlations
 edge_model = covariance.GraphicalLassoCV()
 
+# %%
path: examples/applications/plot_stock_market.py
text: @user1:
looks like there's a bunch of these that should not be added

@author:
I added a few manually in https://github.com/scikit-learn/scikit-learn/pull/17068/commits/9a63b6ee981a756fdfd5cf61f6a170a71c387892 because I though they should have been cells in the first place. Can revert if you prefer.

@user2:
I would revert and have these adjustments be made separate PRs. 

With this PR, we can keep the same formatting as master.

@user2:
I would revert these and have other PRs insert them.

diff_hunk: @@ -44,9 +44,9 @@
 # X = titanic.frame.drop('survived', axis=1)
 # y = titanic.frame['survived']
 
-###############################################################################
+# %%
 # Use ``ColumnTransformer`` by selecting column by names
-###############################################################################
+# %%
path: examples/compose/plot_column_transformer_mixed_types.py
text: @user1:
Revert this.

The second `##########################` was used for a header:

This PR:

<img width="858" alt="Screen Shot 2020-05-26 at 6 13 07 PM" src="https://user-images.githubusercontent.com/5402633/82955319-9141ef80-9f7c-11ea-97dc-f79f6501d577.png">

Master: 

<img width="639" alt="Screen Shot 2020-05-26 at 6 13 23 PM" src="https://user-images.githubusercontent.com/5402633/82955345-a159cf00-9f7c-11ea-89b4-c859842b0fe7.png">

diff_hunk: @@ -20,9 +20,9 @@
 Note that the use of ``memory`` to enable caching becomes interesting when the
 fitting of a transformer is costly.
 
-###############################################################################
+# %%
 Illustration of ``Pipeline`` and ``GridSearchCV``
-###############################################################################
+# %%
path: examples/compose/plot_compare_reduction.py
text: @user1:
Revert this to make the above a header.

diff_hunk: @@ -89,9 +89,9 @@
 
 plt.show()
 
-###############################################################################
+# %%
 # Caching transformers within a ``Pipeline``
-###############################################################################
+# %%
path: examples/compose/plot_compare_reduction.py
text: @user1:
Revert this to make the above a header.

diff_hunk: @@ -120,11 +120,11 @@
 f.suptitle("Synthetic data", y=0.035)
 f.tight_layout(rect=[0.05, 0.05, 0.95, 0.95])
 
-###############################################################################
+# %%
 # Real-world data set
-###############################################################################
+# %%
path: examples/compose/plot_transformed_target.py
text: @user1:
Revert this to make the above a header.

diff_hunk: @@ -25,9 +25,9 @@
 
 print(__doc__)
 
-###############################################################################
+# %%
 # Synthetic example
-###############################################################################
+# %%
path: examples/compose/plot_transformed_target.py
text: @user1:
Revert this to make the above a header.

diff_hunk: @@ -223,6 +224,7 @@
 lc.set_linewidths(15 * values)
 ax.add_collection(lc)
 
+# %%
path: examples/applications/plot_stock_market.py
text: @user1:
Revert

diff_hunk: @@ -120,11 +120,11 @@
 f.suptitle("Synthetic data", y=0.035)
 f.tight_layout(rect=[0.05, 0.05, 0.95, 0.95])
 
-###############################################################################
+# %%
 # Real-world data set
-###############################################################################
+# %%
 
-###############################################################################
+# %%
path: examples/compose/plot_transformed_target.py
text: @user1:
Both are not needed.

diff_hunk: @@ -35,9 +35,9 @@
 clf = make_pipeline(StandardScaler(), LogisticRegression(random_state=0))
 clf.fit(X_train, y_train)
 
-##############################################################################
+# %%
 # Create :class:`ConfusionMatrixDisplay`
-##############################################################################
+# %%
path: examples/miscellaneous/plot_display_object_visualization.py
text: @user1:
Revert this to make the above a header.

diff_hunk: @@ -48,14 +48,15 @@
 
 # #############################################################################
 # Canonical (symmetric) PLS
-
+#
 # Transform data
 # ~~~~~~~~~~~~~~
 plsca = PLSCanonical(n_components=2)
 plsca.fit(X_train, Y_train)
 X_train_r, Y_train_r = plsca.transform(X_train, Y_train)
 X_test_r, Y_test_r = plsca.transform(X_test, Y_test)
 
+# %%
path: examples/cross_decomposition/plot_compare_cross_decomposition.py
text: @user1:
Revert. We can directly address this in another PR

diff_hunk: @@ -50,9 +50,9 @@
 cm_display = ConfusionMatrixDisplay(cm).plot()
 
 
-##############################################################################
+# %%
 # Create :class:`RocCurveDisplay`
-##############################################################################
+# %%
path: examples/miscellaneous/plot_display_object_visualization.py
text: @user1:
Revert this to make the above a header.

diff_hunk: @@ -63,9 +63,9 @@
 fpr, tpr, _ = roc_curve(y_test, y_score, pos_label=clf.classes_[1])
 roc_display = RocCurveDisplay(fpr=fpr, tpr=tpr).plot()
 
-##############################################################################
+# %%
 # Create :class:`PrecisionRecallDisplay`
-##############################################################################
+# %%
path: examples/miscellaneous/plot_display_object_visualization.py
text: @user1:
Revert this to make the above a header.

diff_hunk: @@ -75,9 +75,9 @@
                                          pos_label=clf.classes_[1])
 pr_display = PrecisionRecallDisplay(precision=prec, recall=recall).plot()
 
-##############################################################################
+# %%
 # Combining the display objects into a single plot
-##############################################################################
+# %%
path: examples/miscellaneous/plot_display_object_visualization.py
text: @user1:
Revert this to make the above a header.