103 |
104 |
198 |
199 | {% endblock %}
200 |
201 |
202 | {% block relbar1 %}{% endblock %}
203 | {% block relbar2 %}{% endblock %}
204 |
205 |
206 | {%- block footer %}
207 |
228 |
229 | {%- if pagename != 'index' %}
230 | {%- if parents %}
231 |
232 | {% else %}
233 |
234 | {% endif %}
235 |
239 | {%- for rellink in rellinks|reverse %}
240 |
245 | {%- endfor %}
246 | {% endif %}
247 |
248 |
258 | {%- endblock %}
259 |
260 |
261 |
--------------------------------------------------------------------------------
/doc/themes/scikit-learn/static/sidebar.js:
--------------------------------------------------------------------------------
1 | /*
2 | * sidebar.js
3 | * ~~~~~~~~~~
4 | *
5 | * This script makes the Sphinx sidebar collapsible.
6 | *
7 | * .sphinxsidebar contains .sphinxsidebarwrapper. This script adds
8 | * in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton
9 | * used to collapse and expand the sidebar.
10 | *
11 | * When the sidebar is collapsed the .sphinxsidebarwrapper is hidden
12 | * and the width of the sidebar and the margin-left of the document
13 | * are decreased. When the sidebar is expanded the opposite happens.
14 | * This script saves a per-browser/per-session cookie used to
15 | * remember the position of the sidebar among the pages.
16 | * Once the browser is closed the cookie is deleted and the position
17 | * reset to the default (expanded).
18 | *
19 | * :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
20 | * :license: BSD, see LICENSE for details.
21 | *
22 | */
23 |
24 | $(function() {
25 | // global elements used by the functions.
26 | // the 'sidebarbutton' element is defined as global after its
27 | // creation, in the add_sidebar_button function
28 | var bodywrapper = $('.bodywrapper');
29 | var sidebar = $('.sphinxsidebar');
30 | var sidebarwrapper = $('.sphinxsidebarwrapper');
31 |
32 | // for some reason, the document has no sidebar; do not run into errors
33 | if (!sidebar.length) return;
34 |
35 | // original margin-left of the bodywrapper and width of the sidebar
36 | // with the sidebar expanded
37 | var bw_margin_expanded = bodywrapper.css('margin-left');
38 | var ssb_width_expanded = sidebar.width();
39 |
40 | // margin-left of the bodywrapper and width of the sidebar
41 | // with the sidebar collapsed
42 | var bw_margin_collapsed = '-190px';
43 | var ssb_width_collapsed = '1.0em';
44 |
45 | // colors used by the current theme
46 | var dark_color = $('.related').css('background-color');
47 | var light_color = $('.footer').css('color');
48 |
49 | function sidebar_is_collapsed() {
50 | return sidebarwrapper.is(':not(:visible)');
51 | }
52 |
53 | function toggle_sidebar() {
54 | if (sidebar_is_collapsed())
55 | expand_sidebar();
56 | else
57 | collapse_sidebar();
58 | }
59 |
60 | function collapse_sidebar() {
61 | sidebarwrapper.hide();
62 | sidebar.css('width', ssb_width_collapsed);
63 | bodywrapper.css('margin-left', bw_margin_collapsed);
64 | sidebarbutton.css({
65 | 'margin-left': '0',
66 | 'height': bodywrapper.height()
67 | });
68 | sidebarbutton.find('span').text('»');
69 | sidebarbutton.attr('title', _('Expand sidebar'));
70 | document.cookie = 'sidebar=collapsed';
71 | }
72 |
73 | function expand_sidebar() {
74 | bodywrapper.css('margin-left', bw_margin_expanded);
75 | sidebar.css('width', ssb_width_expanded);
76 | sidebarwrapper.show();
77 | sidebarbutton.css({
78 | 'margin-left': ssb_width_expanded-13,
79 | 'height': bodywrapper.height()
80 | });
81 | sidebarbutton.find('span').text('«');
82 | sidebarbutton.attr('title', _('Collapse sidebar'));
83 | document.cookie = 'sidebar=expanded';
84 | }
85 |
86 | function add_sidebar_button() {
87 | sidebarwrapper.css({
88 | 'float': 'left' ,
89 | 'margin-right': '0',
90 | 'width': ssb_width_expanded - 13
91 | });
92 | // create the button
93 | sidebar.append(
94 | ''
95 | );
96 | var sidebarbutton = $('#sidebarbutton');
97 | light_color = sidebarbutton.css('background-color');
98 | // find the height of the viewport to center the '<<' in the page
99 | var viewport_height;
100 | if (window.innerHeight)
101 | viewport_height = window.innerHeight;
102 | else
103 | viewport_height = $(window).height();
104 | sidebarbutton.find('span').css({
105 | 'display': 'block',
106 | 'margin-top': (viewport_height - sidebar.position().top + 60) / 2
107 | });
108 |
109 | sidebarbutton.click(toggle_sidebar);
110 | sidebarbutton.attr('title', _('Collapse sidebar'));
111 | sidebarbutton.css({
112 | 'border-left': '1px solid ' + dark_color,
113 | 'border-top-left-radius' : '15px',
114 | 'font-size': '1.2em',
115 | 'cursor': 'pointer',
116 | 'height': bodywrapper.height(),
117 | 'padding-top': '1px',
118 | 'margin-left': ssb_width_expanded - 12
119 | });
120 |
121 | sidebarbutton.hover(
122 | function () {
123 | $(this).css('background-color', '#D0D0D0');
124 | },
125 | function () {
126 | $(this).css('background-color', '#F0F0F0');
127 | }
128 | );
129 | }
130 |
131 | function set_position_from_cookie() {
132 | if (!document.cookie)
133 | return;
134 | var items = document.cookie.split(';');
135 | for(var k=0; k
20
33 | radius[far_pts] *= 1.2
34 | radius[~far_pts] *= 1.1
35 |
36 | theta = np.random.random(Npts) * np.pi * 2
37 |
38 | data = np.empty((Npts, 2))
39 | data[:, 0] = radius * np.cos(theta)
40 | data[:, 1] = radius * np.sin(theta)
41 |
42 | labels = np.ones(Npts)
43 | labels[far_pts] = -1
44 |
45 | return data, labels
46 |
47 | #------------------------------------------------------------
48 | # Linear model
49 | X, y = linear_model()
50 | clf = svm.SVC(kernel='linear',
51 | gamma=0.01, coef0=0, degree=3)
52 | clf.fit(X, y)
53 |
54 | fig = pl.figure()
55 | ax = pl.subplot(111, xticks=[], yticks=[])
56 | ax.scatter(X[:, 0], X[:, 1], c=y, cmap=pl.cm.bone)
57 |
58 | ax.scatter(clf.support_vectors_[:, 0],
59 | clf.support_vectors_[:, 1],
60 | s=80, edgecolors="k", facecolors="none")
61 |
62 | delta = 1
63 | y_min, y_max = -50, 50
64 | x_min, x_max = -50, 50
65 | x = np.arange(x_min, x_max + delta, delta)
66 | y = np.arange(y_min, y_max + delta, delta)
67 | X1, X2 = np.meshgrid(x, y)
68 | Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])
69 | Z = Z.reshape(X1.shape)
70 |
71 | levels = [-1.0, 0.0, 1.0]
72 | linestyles = ['dashed', 'solid', 'dashed']
73 | colors = 'k'
74 | ax.contour(X1, X2, Z, levels,
75 | colors=colors,
76 | linestyles=linestyles)
77 |
78 |
79 | #------------------------------------------------------------
80 | # RBF model
81 | X, y = nonlinear_model()
82 | clf = svm.SVC(kernel='rbf',
83 | gamma=0.001, coef0=0, degree=3)
84 | clf.fit(X, y)
85 |
86 | fig = pl.figure()
87 | ax = pl.subplot(111, xticks=[], yticks=[])
88 | ax.scatter(X[:, 0], X[:, 1], c=y, cmap=pl.cm.bone, zorder=2)
89 |
90 | ax.scatter(clf.support_vectors_[:, 0],
91 | clf.support_vectors_[:, 1],
92 | s=80, edgecolors="k", facecolors="none")
93 |
94 | delta = 1
95 | y_min, y_max = -50, 50
96 | x_min, x_max = -50, 50
97 | x = np.arange(x_min, x_max + delta, delta)
98 | y = np.arange(y_min, y_max + delta, delta)
99 | X1, X2 = np.meshgrid(x, y)
100 | Z = clf.decision_function(np.c_[X1.ravel(), X2.ravel()])
101 | Z = Z.reshape(X1.shape)
102 |
103 | levels = [-1.0, 0.0, 1.0]
104 | linestyles = ['dashed', 'solid', 'dashed']
105 | colors = 'k'
106 |
107 | ax.contourf(X1, X2, Z, 10,
108 | cmap=matplotlib.cm.bone,
109 | origin='lower',
110 | alpha=0.85, zorder=1)
111 | ax.contour(X1, X2, Z, [0.0],
112 | colors='k',
113 | linestyles=['solid'], zorder=1)
114 |
115 | pl.show()
116 |
117 |
--------------------------------------------------------------------------------
/examples/plot_iris_projections.py:
--------------------------------------------------------------------------------
1 | """
2 | Iris Projections
3 | ----------------
4 |
5 | This code generates the Iris projection example plots found in the tutorial
6 | """
7 |
8 | from itertools import cycle
9 | import pylab as pl
10 |
11 | from sklearn.datasets import load_iris
12 | from sklearn.decomposition import PCA
13 |
14 |
15 | def plot_2D(data, target, target_names):
16 | colors = cycle('rgbcmykw')
17 | target_ids = range(len(target_names))
18 | pl.figure()
19 | for i, c, label in zip(target_ids, colors, target_names):
20 | pl.plot(data[target == i, 0],
21 | data[target == i, 1], 'o',
22 | c=c, label=label)
23 | pl.legend(target_names)
24 |
25 | #----------------------------------------------------------------------
26 | # Load iris data
27 | iris = load_iris()
28 | X, y = iris.data, iris.target
29 |
30 |
31 | #----------------------------------------------------------------------
32 | # First figure: PCA
33 | pca = PCA(n_components=2, whiten=True).fit(X)
34 | X_pca = pca.transform(X)
35 | plot_2D(X_pca, iris.target, iris.target_names)
36 |
37 |
38 | #----------------------------------------------------------------------
39 | # Second figure: Kmeans labels
40 | from sklearn.cluster import KMeans
41 | from numpy.random import RandomState
42 | rng = RandomState(42)
43 | kmeans = KMeans(3, random_state=rng).fit(X_pca)
44 | plot_2D(X_pca, kmeans.labels_, ["c0", "c1", "c2"])
45 |
46 |
47 | pl.show()
48 |
--------------------------------------------------------------------------------
/examples/plot_python_101.py:
--------------------------------------------------------------------------------
1 | """
2 | Basic numerics and plotting with Python
3 | ========================================
4 |
5 | """
6 |
7 | # import numpy: the module providing numerical arrays
8 | import numpy as np
9 | t = np.linspace(1, 10, 2000)
10 |
11 | # import pylab: the module for scientific plotting
12 | import pylab as pl
13 | pl.plot(t, np.cos(t))
14 |
--------------------------------------------------------------------------------
/examples/plot_sdss_filters.py:
--------------------------------------------------------------------------------
1 | """
2 | SDSS Filters
3 | ------------
4 |
5 | This example downloads and plots the filters from the Sloan Digital Sky
6 | Survey, along with a reference spectrum.
7 | """
8 | import os
9 | import urllib2
10 |
11 | import numpy as np
12 | import pylab as pl
13 | from matplotlib.patches import Arrow
14 |
15 | REFSPEC_URL = 'ftp://ftp.stsci.edu/cdbs/current_calspec/1732526_nic_002.ascii'
16 | URL = 'http://www.sdss.org/dr7/instruments/imager/filters/%s.dat'
17 |
18 | def fetch_filter(filt):
19 | assert filt in 'ugriz'
20 | url = URL % filt
21 |
22 | if not os.path.exists('downloads'):
23 | os.makedirs('downloads')
24 |
25 | loc = os.path.join('downloads', '%s.dat' % filt)
26 | if not os.path.exists(loc):
27 | print "downloading from %s" % url
28 | F = urllib2.urlopen(url)
29 | open(loc, 'w').write(F.read())
30 |
31 | F = open(loc)
32 |
33 | data = np.loadtxt(F)
34 | return data
35 |
36 | def fetch_vega_spectrum():
37 | if not os.path.exists('downloads'):
38 | os.makedirs('downloads')
39 |
40 | refspec_file = os.path.join('downloads', REFSPEC_URL.split('/')[-1])
41 |
42 | if not os.path.exists(refspec_file):
43 | print "downloading from %s" % REFSPEC_URL
44 | F = urllib2.urlopen(REFSPEC_URL)
45 | open(refspec_file, 'w').write(F.read())
46 |
47 | F = open(refspec_file)
48 |
49 | data = np.loadtxt(F)
50 | return data
51 |
52 |
53 | Xref = fetch_vega_spectrum()
54 | Xref[:, 1] /= 2.1 * Xref[:, 1].max()
55 |
56 | #----------------------------------------------------------------------
57 | # Plot filters in color with a single spectrum
58 | pl.figure()
59 | pl.plot(Xref[:, 0], Xref[:, 1], '-k', lw=2)
60 |
61 | for f,c in zip('ugriz', 'bgrmk'):
62 | X = fetch_filter(f)
63 | pl.fill(X[:, 0], X[:, 1], ec=c, fc=c, alpha=0.4)
64 |
65 | kwargs = dict(fontsize=20, ha='center', va='center', alpha=0.5)
66 | pl.text(3500, 0.02, 'u', color='b', **kwargs)
67 | pl.text(4600, 0.02, 'g', color='g', **kwargs)
68 | pl.text(6100, 0.02, 'r', color='r', **kwargs)
69 | pl.text(7500, 0.02, 'i', color='m', **kwargs)
70 | pl.text(8800, 0.02, 'z', color='k', **kwargs)
71 |
72 | pl.xlim(3000, 11000)
73 |
74 | pl.title('SDSS Filters and Reference Spectrum')
75 | pl.xlabel('Wavelength (Angstroms)')
76 | pl.ylabel('normalized flux / filter transmission')
77 |
78 | #----------------------------------------------------------------------
79 | # Plot filters in gray with several redshifted spectra
80 | pl.figure()
81 |
82 | redshifts = [0.0, 0.4, 0.8]
83 | colors = 'bgr'
84 |
85 | for z, c in zip(redshifts, colors):
86 | pl.plot((1. + z) * Xref[:, 0], Xref[:, 1], color=c)
87 |
88 | pl.gca().add_patch(Arrow(4200, 0.47, 1300, 0, lw=0, width=0.05, color='r'))
89 | pl.gca().add_patch(Arrow(5800, 0.47, 1250, 0, lw=0, width=0.05, color='r'))
90 |
91 | pl.text(3800, 0.49, 'z = 0.0', fontsize=14, color=colors[0])
92 | pl.text(5500, 0.49, 'z = 0.4', fontsize=14, color=colors[1])
93 | pl.text(7300, 0.49, 'z = 0.8', fontsize=14, color=colors[2])
94 |
95 | for f in 'ugriz':
96 | X = fetch_filter(f)
97 | pl.fill(X[:, 0], X[:, 1], ec='k', fc='k', alpha=0.2)
98 |
99 | kwargs = dict(fontsize=20, color='gray', ha='center', va='center')
100 | pl.text(3500, 0.02, 'u', **kwargs)
101 | pl.text(4600, 0.02, 'g', **kwargs)
102 | pl.text(6100, 0.02, 'r', **kwargs)
103 | pl.text(7500, 0.02, 'i', **kwargs)
104 | pl.text(8800, 0.02, 'z', **kwargs)
105 |
106 | pl.xlim(3000, 11000)
107 | pl.ylim(0, 0.55)
108 |
109 | pl.title('Redshifting of a Spectrum')
110 | pl.xlabel('Observed Wavelength (Angstroms)')
111 | pl.ylabel('normalized flux / filter transmission')
112 |
113 | pl.show()
114 |
--------------------------------------------------------------------------------
/examples/plot_sdss_images.py:
--------------------------------------------------------------------------------
1 | """
2 | SDSS Images
3 | -----------
4 |
5 | This script plots an example quasar, star, and galaxy image for use in
6 | the tutorial.
7 | """
8 | import os
9 | import urllib2
10 |
11 | import pylab as pl
12 | from matplotlib import image
13 |
14 | def _fetch(outfile, RA, DEC, scale=0.2, width=400, height=400):
15 | """Fetch the image at the given RA, DEC from the SDSS server"""
16 | url = ("http://casjobs.sdss.org/ImgCutoutDR7/"
17 | "getjpeg.aspx?ra=%.8f&dec=%.8f&scale=%.2f&width=%i&height=%i"
18 | % (RA, DEC, scale, width, height))
19 | print "downloading %s" % url
20 | print " -> %s" % outfile
21 | fhandle = urllib2.urlopen(url)
22 | open(outfile, 'w').write(fhandle.read())
23 |
24 |
25 | def fetch_image(object_type):
26 | """Return the data array for the image of object type"""
27 | if not os.path.exists('downloads'):
28 | os.makedirs('downloads')
29 |
30 | filename = os.path.join('downloads', '%s_image.jpg' % object_type)
31 | if not os.path.exists(filename):
32 | RA = image_locations[object_type]['RA']
33 | DEC = image_locations[object_type]['DEC']
34 | _fetch(filename, RA, DEC)
35 |
36 | return image.imread(filename)
37 |
38 |
39 | image_locations = dict(star=dict(RA=180.63040108,
40 | DEC=64.96767375),
41 | galaxy=dict(RA=197.51943983,
42 | DEC=0.94881436),
43 | quasar=dict(RA=226.18451462,
44 | DEC=4.07456639))
45 |
46 |
47 | # Plot the images
48 | fig = pl.figure(figsize=(9, 3))
49 |
50 | # Check that PIL is installed for jpg support
51 | if 'jpg' not in fig.canvas.get_supported_filetypes():
52 | raise ValueError("PIL required to load SDSS jpeg images")
53 |
54 | object_types = ['star', 'galaxy', 'quasar']
55 |
56 | for i, object_type in enumerate(object_types):
57 | ax = pl.subplot(131 + i, xticks=[], yticks=[])
58 | I = fetch_image(object_type)
59 | ax.imshow(I)
60 | if object_type != 'galaxy':
61 | pl.arrow(0.65, 0.65, -0.1, -0.1, width=0.005, head_width=0.03,
62 | length_includes_head=True,
63 | color='w', transform=ax.transAxes)
64 | pl.text(0.99, 0.01, object_type, fontsize='large', color='w', ha='right',
65 | transform=ax.transAxes)
66 |
67 | pl.subplots_adjust(bottom=0.04, top=0.94, left=0.02, right=0.98, wspace=0.04)
68 |
69 | pl.show()
70 |
--------------------------------------------------------------------------------
/examples/plot_sdss_photoz.py:
--------------------------------------------------------------------------------
1 | """
2 | SDSS Photometric Redshifts
3 | --------------------------
4 |
5 | This example shows how a Decision tree can be used to learn redshifts
6 | of galaxies in the Sloan Digital Sky Survey.
7 | """
8 |
9 | import os
10 | import urllib2
11 | import numpy as np
12 | import pylab as pl
13 |
14 | from sklearn.datasets import get_data_home
15 | from sklearn.tree import DecisionTreeRegressor
16 |
17 | DATA_URL = ('http://www.astro.washington.edu/users/'
18 | 'vanderplas/pydata/sdss_photoz.npy')
19 | LOCAL_FILE = 'sdss_photoz.npy'
20 |
21 | def fetch_photoz_data():
22 | if not os.path.exists('downloads'):
23 | os.makedirs('downloads')
24 |
25 | local_file = os.path.join('downloads', LOCAL_FILE)
26 |
27 | if not os.path.exists(local_file):
28 | # data directory is password protected so the public can't access it
29 | password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
30 | password_mgr.add_password(None, DATA_URL, 'pydata', 'astroML')
31 | handler = urllib2.HTTPBasicAuthHandler(password_mgr)
32 | opener = urllib2.build_opener(handler)
33 | fhandle = opener.open(DATA_URL)
34 | open(local_file, 'w').write(fhandle.read())
35 |
36 | return np.load(local_file)
37 |
38 | data = fetch_photoz_data()
39 |
40 | N = len(data)
41 |
42 | # put colors in a matrix
43 | X = np.zeros((N, 4))
44 | X[:, 0] = data['u'] - data['g']
45 | X[:, 1] = data['g'] - data['r']
46 | X[:, 2] = data['r'] - data['i']
47 | X[:, 3] = data['i'] - data['z']
48 | z = data['redshift']
49 |
50 | # divide into training and testing data
51 | Ntrain = 3 * N / 4
52 | Xtrain = X[:Ntrain]
53 | ztrain = z[:Ntrain]
54 |
55 | Xtest = X[Ntrain:]
56 | ztest = z[Ntrain:]
57 |
58 |
59 | clf = DecisionTreeRegressor(max_depth=20)
60 | clf.fit(Xtrain, ztrain)
61 | zpred = clf.predict(Xtest)
62 |
63 | axis_lim = np.array([-0.1, 2.5])
64 |
65 | rms = np.sqrt(np.mean((ztest - zpred) ** 2))
66 | print rms
67 | print len(ztest)
68 | print np.sum(abs(ztest - zpred) > 1)
69 |
70 | ax = pl.axes()
71 | pl.scatter(ztest, zpred, c='k', lw=0, s=4)
72 | pl.plot(axis_lim, axis_lim, '--k')
73 | pl.plot(axis_lim, axis_lim + rms, ':k')
74 | pl.plot(axis_lim, axis_lim - rms, ':k')
75 | pl.xlim(axis_lim)
76 | pl.ylim(axis_lim)
77 |
78 | pl.text(0.99, 0.02, "RMS error = %.2g" % rms,
79 | ha='right', va='bottom', transform=ax.transAxes,
80 | bbox=dict(ec='w', fc='w'), fontsize=16)
81 |
82 | pl.title('Photo-z: Decision Tree Regression')
83 | pl.xlabel(r'$\mathrm{z_{true}}$', fontsize=14)
84 | pl.ylabel(r'$\mathrm{z_{phot}}$', fontsize=14)
85 | pl.show()
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/examples/plot_sdss_specPCA.py:
--------------------------------------------------------------------------------
1 | """
2 | SDSS Spectra Plots
3 | ------------------
4 |
5 | This plots some of the SDSS spectra examples for the astronomy tutorial
6 | """
7 | import os
8 | import urllib2
9 |
10 | import numpy as np
11 | import pylab as pl
12 |
13 | from sklearn import preprocessing
14 | from sklearn.decomposition import RandomizedPCA
15 |
16 | DATA_URL = ('http://www.astro.washington.edu/users/'
17 | 'vanderplas/pydata/spec4000_corrected.npz')
18 |
19 | def fetch_sdss_spec_data():
20 | if not os.path.exists('downloads'):
21 | os.makedirs('downloads')
22 |
23 | local_file = os.path.join('downloads', os.path.basename(DATA_URL))
24 |
25 | # data directory is password protected so the public can't access it
26 | password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
27 | password_mgr.add_password(None, DATA_URL, 'pydata', 'astroML')
28 | handler = urllib2.HTTPBasicAuthHandler(password_mgr)
29 | opener = urllib2.build_opener(handler)
30 |
31 | # download training data
32 | if not os.path.exists(local_file):
33 | fhandle = opener.open(DATA_URL)
34 | open(local_file, 'w').write(fhandle.read())
35 |
36 | return np.load(local_file)
37 |
38 | #----------------------------------------------------------------------
39 | #
40 | # Load the data
41 | data = fetch_sdss_spec_data()
42 |
43 | wavelengths = data['wavelengths']
44 | X = data['X']
45 | y = data['y']
46 | labels = data['labels']
47 |
48 | from matplotlib.ticker import FuncFormatter
49 | format = FuncFormatter(lambda i, *args: labels[i].replace(' ', '\n'))
50 |
51 | #----------------------------------------------------------------------
52 | #
53 | # Plot the first few spectra, offset so they don't overlap
54 | #
55 | pl.figure()
56 |
57 | for i_class in (2, 3, 4, 5, 6):
58 | i = np.where(y == i_class)[0][0]
59 | l = pl.plot(wavelengths, X[i] + 20 * i_class)
60 | c = l[0].get_color()
61 | pl.text(6800, 2 + 20 * i_class, labels[i_class], color=c)
62 |
63 | pl.subplots_adjust(hspace=0)
64 | pl.xlabel('wavelength (Angstroms)')
65 | pl.ylabel('flux + offset')
66 | pl.title('Sample of Spectra')
67 |
68 | #----------------------------------------------------------------------
69 | #
70 | # Plot the mean spectrum
71 | #
72 | X = preprocessing.normalize(X, 'l2')
73 |
74 | pl.figure()
75 |
76 | mu = X.mean(0)
77 | std = X.std(0)
78 |
79 | pl.plot(wavelengths, mu, color='black')
80 | pl.fill_between(wavelengths, mu - std, mu + std, color='#CCCCCC')
81 | pl.xlim(wavelengths[0], wavelengths[-1])
82 | pl.ylim(0, 0.06)
83 | pl.xlabel('wavelength (Angstroms)')
84 | pl.ylabel('scaled flux')
85 | pl.title('Mean Spectrum + Variance')
86 |
87 | #----------------------------------------------------------------------
88 | #
89 | # Plot a random pair of digits
90 | #
91 | pl.figure()
92 | np.random.seed(25255)
93 | i1, i2 = np.random.randint(1000, size=2)
94 |
95 | pl.scatter(X[:, i1], X[:, i2], c=y, s=4, lw=0,
96 | vmin=2, vmax=6, cmap=pl.cm.jet)
97 | pl.colorbar(ticks = range(2, 7), format=format)
98 | pl.xlabel('wavelength = %.1f' % wavelengths[i1])
99 | pl.ylabel('wavelength = %.1f' % wavelengths[i2])
100 | pl.title('Random Pair of Spectra Bins')
101 |
102 | #----------------------------------------------------------------------
103 | #
104 | # Perform PCA
105 | #
106 |
107 | rpca = RandomizedPCA(n_components=4, random_state=0)
108 | X_proj = rpca.fit_transform(X)
109 |
110 | #----------------------------------------------------------------------
111 | #
112 | # Plot PCA components
113 | #
114 |
115 | pl.figure()
116 | pl.scatter(X_proj[:, 0], X_proj[:, 1], c=y, s=4, lw=0,
117 | vmin=2, vmax=6, cmap=pl.cm.jet)
118 | pl.colorbar(ticks = range(2, 7), format=format)
119 | pl.xlabel('coefficient 1')
120 | pl.ylabel('coefficient 2')
121 | pl.title('PCA projection of Spectra')
122 |
123 | #----------------------------------------------------------------------
124 | #
125 | # Plot PCA eigenspectra
126 | #
127 |
128 | pl.figure()
129 |
130 | l = pl.plot(wavelengths, rpca.mean_ - 0.15)
131 | c = l[0].get_color()
132 | pl.text(7000, -0.16, "mean" % i, color=c)
133 |
134 | for i in range(4):
135 | l = pl.plot(wavelengths, rpca.components_[i] + 0.15 * i)
136 | c = l[0].get_color()
137 | pl.text(7000, -0.01 + 0.15 * i, "component %i" % (i + 1), color=c)
138 | pl.ylim(-0.2, 0.6)
139 | pl.xlabel('wavelength (Angstroms)')
140 | pl.ylabel('scaled flux + offset')
141 | pl.title('Mean Spectrum and Eigen-spectra')
142 |
143 | pl.show()
144 |
--------------------------------------------------------------------------------
/examples/plot_sgd_separating_hyperplane.py:
--------------------------------------------------------------------------------
1 | """
2 | =========================================
3 | SGD: Maximum margin separating hyperplane
4 | =========================================
5 |
6 | Plot the maximum margin separating hyperplane within a two-class
7 | separable dataset using a linear Support Vector Machines classifier
8 | trained using SGD.
9 | """
10 | print __doc__
11 |
12 | import numpy as np
13 | import pylab as pl
14 | from sklearn.linear_model import SGDClassifier
15 | from sklearn.datasets.samples_generator import make_blobs
16 |
17 | # we create 50 separable points
18 | X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)
19 |
20 | # fit the model
21 | clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=200, fit_intercept=True)
22 | clf.fit(X, Y)
23 |
24 | # plot the line, the points, and the nearest vectors to the plane
25 | xx = np.linspace(-1, 5, 10)
26 | yy = np.linspace(-1, 5, 10)
27 |
28 | X1, X2 = np.meshgrid(xx, yy)
29 | Z = np.empty(X1.shape)
30 | for (i, j), val in np.ndenumerate(X1):
31 | x1 = val
32 | x2 = X2[i, j]
33 | p = clf.decision_function([x1, x2])
34 | Z[i, j] = p[0]
35 | levels = [-1.0, 0.0, 1.0]
36 | linestyles = ['dashed', 'solid', 'dashed']
37 | colors = 'k'
38 | pl.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)
39 | pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired)
40 |
41 | pl.axis('tight')
42 | pl.show()
43 |
--------------------------------------------------------------------------------