8000 [MRG] DOC examples with correct notebook style (#9061) · scikit-learn/scikit-learn@1f6ac72 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1f6ac72

Browse files
plagreeraghavrv
authored andcommitted
[MRG] DOC examples with correct notebook style (#9061)
* DOC examples with correct notebook style * Modifications in examples/ to avoid unwanted notebook style * Remove last notebook style example * Space formatting to avoid notebook style
1 parent 0d5d842 commit 1f6ac72

File tree

56 files changed

+169
-171
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+169
-171
lines changed

examples/applications/plot_face_recognition.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
4949

5050

51-
###############################################################################
51+
# #############################################################################
5252
# Download the data, if not already on disk and load it as numpy arrays
5353

5454
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
@@ -72,15 +72,15 @@
7272
print("n_classes: %d" % n_classes)
7373

7474

75-
###############################################################################
75+
# #############################################################################
7676
# Split into a training set and a test set using a stratified k fold
7777

7878
# split into a training and testing set
7979
X_train, X_test, y_train, y_test = train_test_split(
8080
X, y, test_size=0.25, random_state=42)
8181

8282

83-
###############################################################################
83+
# #############################################################################
8484
# Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled
8585
# dataset): unsupervised feature extraction / dimensionality reduction
8686
n_components = 150
@@ -101,7 +101,7 @@
101101
print("done in %0.3fs" % (time() - t0))
102102

103103

104-
###############################################################################
104+
# #############################################################################
105105
# Train a SVM classification model
106106

107107
print("Fitting the classifier to the training set")
@@ -115,7 +115,7 @@
115115
print(clf.best_estimator_)
116116

117117

118-
###############################################################################
118+
# #############################################################################
119119
# Quantitative evaluation of the model quality on the test set
120120

121121
print("Predicting people's names on the test set")
@@ -127,7 +127,7 @@
127127
print(confusion_matrix(y_test, y_pred, labels=range(n_classes)))
128128

129129

130-
###############################################################################
130+
# #############################################################################
131131
# Qualitative evaluation of the predictions using matplotlib
132132

133133
def plot_gallery(images, titles, h, w, n_row=3, n_col=4):

examples/applications/plot_model_complexity_influence.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@
3434
from sklearn.linear_model.stochastic_gradient import SGDClassifier
3535
from sklearn.metrics import hamming_loss
3636

37-
###############################################################################
37+
# #############################################################################
3838
# Routines
3939

4040

41-
# initialize random generator
41+
# Initialize random generator
4242
np.random.seed(0)
4343

4444

@@ -122,8 +122,8 @@ def _count_nonzero_coefficients(estimator):
122122
a = estimator.coef_.toarray()
123123
return np.count_nonzero(a)
124124

125-
###############################################################################
126-
# main code
125+
# #############################################################################
126+
# Main code
127127
regression_data = generate_data('regression')
128128
classification_data = generate_data('classification', sparse=True)
129129
configurations = [

examples/applications/plot_prediction_latency.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -266,12 +266,13 @@ def plot_benchmark_throughput(throughputs, configuration):
266266
plt.show()
267267

268268

269-
###############################################################################
270-
# main code
269+
# #############################################################################
270+
# Main code
271271

272272
start_time = time.time()
273273

274-
# benchmark bulk/atomic prediction speed for various regressors
274+
# #############################################################################
275+
# Benchmark bulk/atomic prediction speed for various regressors
275276
configuration = {
276277
'n_train': int(1e3),
277278
'n_test': int(1e2),

examples/applications/plot_stock_market.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@
7474
from sklearn import cluster, covariance, manifold
7575

7676

77-
###############################################################################
77+
# #############################################################################
7878
# Retrieve the data from Internet
7979

8080
def quotes_historical_google(symbol, date1, date2):
@@ -189,7 +189,7 @@ def quotes_historical_google(symbol, date1, date2):
189189
variation = close_prices - open_prices
190190

191191

192-
###############################################################################
192+
# #############################################################################
193193
# Learn a graphical structure from the correlations
194194
edge_model = covariance.GraphLassoCV()
195195

@@ -199,7 +199,7 @@ def quotes_historical_google(symbol, date1, date2):
199199
X /= X.std(axis=0)
200200
edge_model.fit(X)
201201

202-
###############################################################################
202+
# #############################################################################
203203
# Cluster using affinity propagation
204204

205205
_, labels = cluster.affinity_propagation(edge_model.covariance_)
@@ -208,7 +208,7 @@ def quotes_historical_google(symbol, date1, date2):
208208
for i in range(n_labels + 1):
209209
print('Cluster %i: %s' % ((i + 1), ', '.join(names[labels == i])))
210210

211-
###############################################################################
211+
# #############################################################################
212212
# Find a low-dimension embedding for visualization: find the best position of
213213
# the nodes (the stocks) on a 2D plane
214214

@@ -220,7 +220,7 @@ def quotes_historical_google(symbol, date1, date2):
220220

221221
embedding = node_position_model.fit_transform(X.T).T
222222

223-
###############################################################################
223+
# #############################################################################
224224
# Visualization
225225
plt.figure(1, facecolor='w', figsize=(10, 8))
226226
plt.clf()

examples/applications/wikipedia_principal_eigenvector.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252

5353
print(__doc__)
5454

55-
###############################################################################
55+
# #############################################################################
5656
# Where to download the data, if not already on disk
5757
redirects_url = "http://downloads.dbpedia.org/3.5.1/en/redirects_en.nt.bz2"
5858
redirects_filename = redirects_url.rsplit("/", 1)[1]
@@ -73,7 +73,7 @@
7373
print()
7474

7575

76-
###############################################################################
76+
# #############################################################################
7777
# Loading the redirect files
7878

7979
memory = Memory(cachedir=".")

examples/calibration/plot_calibration.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@
8383
clf_sigmoid_score = brier_score_loss(y_test, prob_pos_sigmoid, sw_test)
8484
print("With sigmoid calibration: %1.3f" % clf_sigmoid_score)
8585

86-
###############################################################################
86+
# #############################################################################
8787
# Plot the data and the predicted probabilities
8888
plt.figure()
8989
y_unique = np.unique(y)

examples/calibration/plot_compare_calibration.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@
8181
rfc = RandomForestClassifier(n_estimators=100)
8282

8383

84-
###############################################################################
84+
# #############################################################################
8585
# Plot calibration plots
8686

8787
plt.figure(figsize=(10, 10))

examples/classification/plot_lda_qda.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ class has its own standard deviation with QDA.
2020
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
2121
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
2222

23-
###############################################################################
24-
# colormap
23+
# #############################################################################
24+
# Colormap
2525
cmap = colors.LinearSegmentedColormap(
2626
'red_blue_classes',
2727
{'red': [(0, 1, 1), (1, 0.7, 0.7)],
@@ -30,8 +30,8 @@ class has its own standard deviation with QDA.
3030
plt.cm.register_cmap(cmap=cmap)
3131

3232

33-
###############################################################################
34-
# generate datasets
33+
# #############################################################################
34+
# Generate datasets
3535
def dataset_fixed_cov():
3636
'''Generate 2 Gaussians samples with the same covariance matrix'''
3737
n, dim = 300, 2
@@ -54,8 +54,8 @@ def dataset_cov():
5454
return X, y
5555

5656

57-
###############################################################################
58-
# plot functions
57+
# #############################################################################
58+
# Plot functions
5959
def plot_data(lda, X, y, y_pred, fig_index):
6060
splot = plt.subplot(2, 2, fig_index)
6161
if fig_index == 1:
@@ -132,7 +132,6 @@ def plot_qda_cov(qda, splot):
132132
plot_ellipse(splot, qda.means_[0], qda.covariances_[0], 'red')
133133
plot_ellipse(splot, qda.means_[1], qda.covariances_[1], 'blue')
134134

135-
###############################################################################
136135
for i, (X, y) in enumerate([dataset_fixed_cov(), dataset_cov()]):
137136
# Linear Discriminant Analysis
138137
lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=True)

examples/cluster/plot_affinity_propagation.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@
1414
from sklearn import metrics
1515
from sklearn.datasets.samples_generator import make_blobs
1616

17-
##############################################################################
17+
# #############################################################################
1818
# Generate sample data
1919
centers = [[1, 1], [-1, -1], [1, -1]]
2020
X, labels_true = make_blobs(n_samples=300, centers=centers, cluster_std=0.5,
2121
random_state=0)
2222

23-
##############################################################################
23+
# #############################################################################
2424
# Compute Affinity Propagation
2525
af = AffinityPropagation(preference=-50).fit(X)
2626
cluster_centers_indices = af.cluster_centers_indices_
@@ -39,7 +39,7 @@
3939
print("Silhouette Coefficient: %0.3f"
4040
% metrics.silhouette_score(X, labels, metric='sqeuclidean'))
4141

42-
##############################################################################
42+
# #############################################################################
4343
# Plot result
4444
import matplotlib.pyplot as plt
4545
from itertools import cycle

examples/cluster/plot_dbscan.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@
1717
from sklearn.preprocessing import StandardScaler
1818

1919

20-
##############################################################################
20+
# #############################################################################
2121
# Generate sample data
2222
centers = [[1, 1], [-1, -1], [1, -1]]
2323
X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4,
2424
random_state=0)
2525

2626
X = StandardScaler().fit_transform(X)
2727

28-
##############################################################################
28+
# #############################################################################
2929
# Compute DBSCAN
3030
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
3131
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
@@ -46,7 +46,7 @@
4646
print("Silhouette Coefficient: %0.3f"
4747
% metrics.silhouette_score(X, labels))
4848

49-
##############################################################################
49+
# #############################################################################
5050
# Plot result
5151
import matplotlib.pyplot as plt
5252

examples/cluster/plot_dict_face_patches.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
faces = datasets.fetch_olivetti_faces()
3434

35-
###############################################################################
35+
# #############################################################################
3636
# Learn the dictionary of images
3737

3838
print('Learning the dictionary... ')
@@ -66,7 +66,7 @@
6666
dt = time.time() - t0
6767
print('done in %.2fs.' % dt)
6868

69-
###############################################################################
69+
# #############################################################################
7070
# Plot the results
7171
plt.figure(figsize=(4.2, 4))
7272
for i, patch in enumerate(kmeans.cluster_centers_):

examples/cluster/plot_face_ward_segmentation.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from sklearn.cluster import AgglomerativeClustering
2626

2727

28-
###############################################################################
28+
# #############################################################################
2929
# Generate data
3030
try: # SciPy >= 0.16 have face in misc
3131
from scipy.misc import face
@@ -38,11 +38,11 @@
3838

3939
X = np.reshape(face, (-1, 1))
4040

41-
###############################################################################
41+
# #############################################################################
4242
# Define the structure A of the data. Pixels connected to their neighbors.
4343
connectivity = grid_to_graph(*face.shape)
4444

45-
###############################################################################
45+
# #############################################################################
4646
# Compute clustering
4747
print("Compute structured hierarchical clustering...")
4848
st = time.time()
@@ -55,7 +55,7 @@
5555
print("Number of pixels: ", label.size)
5656
print("Number of clusters: ", np.unique(label).size)
5757

58-
###############################################################################
58+
# #############################################################################
5959
# Plot the results on an image
6060
plt.figure(figsize=(5, 5))
6161
plt.imshow(face, cmap=plt.cm.gray)

examples/cluster/plot_feature_agglomeration_vs_univariate_selection.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from sklearn.model_selection import GridSearchCV
3535
from sklearn.model_selection import KFold
3636

37-
###############################################################################
37+
# #############################################################################
3838
# Generate data
3939
n_samples = 200
4040
size = 40 # image size
@@ -58,7 +58,7 @@
5858
noise_coef = (linalg.norm(y, 2) / np.exp(snr / 20.)) / linalg.norm(noise, 2)
5959
y += noise_coef * noise # add noise
6060

61-
###############################################################################
61+
# #############################################################################
6262
# Compute the coefs of a Bayesian Ridge with GridSearch
6363
cv = KFold(2) # cross-validation generator for model selection
6464
ridge = BayesianRidge()
@@ -88,7 +88,7 @@
8888
coef_ = clf.best_estimator_.steps[0][1].inverse_transform(coef_.reshape(1, -1))
8989
coef_selection_ = coef_.reshape(size, size)
9090

91-
###############################################################################
91+
# #############################################################################
9292
# Inverse the transformation to plot the results on an image
9393
plt.close('all')
9494
plt.figure(figsize=(7.3, 2.7))

examples/cluster/plot_kmeans_digits.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def bench_k_means(estimator, name, data):
8484
data=data)
8585
print(82 * '_')
8686

87-
###############################################################################
87+
# #############################################################################
8888
# Visualize the results on PCA-reduced data
8989

9090
reduced_data = PCA(n_components=2).fit_transform(data)

examples/cluster/plot_mean_shift.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616
from sklearn.cluster import MeanShift, estimate_bandwidth
1717
from sklearn.datasets.samples_generator import make_blobs
1818

19-
###############################################################################
19+
# #############################################################################
2020
# Generate sample data
2121
centers = [[1, 1], [-1, -1], [1, -1]]
2222
X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)
2323

24-
###############################################################################
24+
# #############################################################################
2525
# Compute clustering with MeanShift
2626

2727
# The following bandwidth can be automatically detected using
@@ -37,7 +37,7 @@
3737

3838
print("number of estimated clusters : %d" % n_clusters_)
3939

40-
###############################################################################
40+
# #############################################################################
4141
# Plot result
4242
import matplotlib.pyplot as plt
4343
from itertools import cycle

0 commit comments

Comments
 (0)
0