Skip to content

Commit f994376

Browse files
committed
Pushing the docs to dev/ for branch: master, commit 5147fd09c6a063188efde444f47bd006fa5f95f0
1 parent 8389059 commit f994376

File tree

917 files changed

+4426
-2918
lines changed

Some content is hidden

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

917 files changed

+4426
-2918
lines changed
9.2 KB
Binary file not shown.
7.14 KB
Binary file not shown.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
{
2+
"nbformat_minor": 0,
3+
"nbformat": 4,
4+
"cells": [
5+
{
6+
"execution_count": null,
7+
"cell_type": "code",
8+
"source": [
9+
"%matplotlib inline"
10+
],
11+
"outputs": [],
12+
"metadata": {
13+
"collapsed": false
14+
}
15+
},
16+
{
17+
"source": [
18+
"\n# Multiclass sparse logisitic regression on newgroups20\n\n\nComparison of multinomial logistic L1 vs one-versus-rest L1 logistic regression\nto classify documents from the newgroups20 dataset. Multinomial logistic\nregression yields more accurate results and is faster to train on the larger\nscale dataset.\n\nHere we use the l1 sparsity that trims the weights of not informative\nfeatures to zero. This is good if the goal is to extract the strongly\ndiscriminative vocabulary of each class. If the goal is to get the best\npredictive accuracy, it is better to use the non sparsity-inducing l2 penalty\ninstead.\n\nA more traditional (and possibly better) way to predict on a sparse subset of\ninput features would be to use univariate feature selection followed by a\ntraditional (l2-penalised) logistic regression model.\n\n"
19+
],
20+
"cell_type": "markdown",
21+
"metadata": {}
22+
},
23+
{
24+
"execution_count": null,
25+
"cell_type": "code",
26+
"source": [
27+
"import time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\nprint(__doc__)\n# Author: Arthur Mensch\n\nt0 = time.clock()\n\n# We use SAGA solver\nsolver = 'saga'\n\n# Turn down for faster run time\nn_samples = 10000\n\n# Memorized fetch_rcv1 for faster access\ndataset = fetch_20newsgroups_vectorized('all')\nX = dataset.data\ny = dataset.target\nX = X[:n_samples]\ny = y[:n_samples]\n\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n random_state=42,\n stratify=y,\n test_size=0.1)\ntrain_samples, n_features = X_train.shape\nn_classes = np.unique(y).shape[0]\n\nprint('Dataset 20newsgroup, train_samples=%i, n_features=%i, n_classes=%i'\n % (train_samples, n_features, n_classes))\n\nmodels = {'ovr': {'name': 'One versus Rest', 'iters': [1, 3]},\n 'multinomial': {'name': 'Multinomial', 'iters': [1, 3, 7]}}\n\nfor model in models:\n # Add initial chance-level values for plotting purpose\n accuracies = [1 / n_classes]\n times = [0]\n densities = [1]\n\n model_params = models[model]\n\n # Small number of epochs for fast runtime\n for this_max_iter in model_params['iters']:\n print('[model=%s, solver=%s] Number of epochs: %s' %\n (model_params['name'], solver, this_max_iter))\n lr = LogisticRegression(solver=solver,\n multi_class=model,\n C=1,\n penalty='l1',\n fit_intercept=True,\n max_iter=this_max_iter,\n random_state=42,\n )\n t1 = time.clock()\n lr.fit(X_train, y_train)\n train_time = time.clock() - t1\n\n y_pred = lr.predict(X_test)\n accuracy = np.sum(y_pred == y_test) / y_test.shape[0]\n density = np.mean(lr.coef_ != 0, axis=1) * 100\n accuracies.append(accuracy)\n densities.append(density)\n times.append(train_time)\n models[model]['times'] = times\n models[model]['densities'] = densities\n models[model]['accuracies'] = accuracies\n print('Test accuracy for model %s: %.4f' % (model, accuracies[-1]))\n print('%% non-zero coefficients for model %s, '\n 'per class:\\n %s' % (model, densities[-1]))\n print('Run time (%i epochs) for model %s:'\n '%.2f' % (model_params['iters'][-1], model, times[-1]))\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nfor model in models:\n name = models[model]['name']\n times = models[model]['times']\n accuracies = models[model]['accuracies']\n ax.plot(times, accuracies, marker='o',\n label='Model: %s' % name)\n ax.set_xlabel('Train time (s)')\n ax.set_ylabel('Test accuracy')\nax.legend()\nfig.suptitle('Multinomial vs One-vs-Rest Logistic L1\\n'\n 'Dataset %s' % '20newsgroups')\nfig.tight_layout()\nfig.subplots_adjust(top=0.85)\nrun_time = time.clock() - t0\nprint('Example run in %.3f s' % run_time)\nplt.show()"
28+
],
29+
"outputs": [],
30+
"metadata": {
31+
"collapsed": false
32+
}
33+
}
34+
],
35+
"metadata": {
36+
"kernelspec": {
37+
"display_name": "Python 2",
38+
"name": "python2",
39+
"language": "python"
40+
},
41+
"language_info": {
42+
"mimetype": "text/x-python",
43+
"nbconvert_exporter": "python",
44+
"name": "python",
45+
"file_extension": ".py",
46+
"version": "2.7.13",
47+
"pygments_lexer": "ipython2",
48+
"codemirror_mode": {
49+
"version": 2,
50+
"name": "ipython"
51+
}
52+
}
53+
}
54+
}
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
"""
2+
=====================================================
3+
Multiclass sparse logisitic regression on newgroups20
4+
=====================================================
5+
6+
Comparison of multinomial logistic L1 vs one-versus-rest L1 logistic regression
7+
to classify documents from the newgroups20 dataset. Multinomial logistic
8+
regression yields more accurate results and is faster to train on the larger
9+
scale dataset.
10+
11+
Here we use the l1 sparsity that trims the weights of not informative
12+
features to zero. This is good if the goal is to extract the strongly
13+
discriminative vocabulary of each class. If the goal is to get the best
14+
predictive accuracy, it is better to use the non sparsity-inducing l2 penalty
15+
instead.
16+
17+
A more traditional (and possibly better) way to predict on a sparse subset of
18+
input features would be to use univariate feature selection followed by a
19+
traditional (l2-penalised) logistic regression model.
20+
"""
21+
import time
22+
23+
import matplotlib.pyplot as plt
24+
import numpy as np
25+
26+
from sklearn.datasets import fetch_20newsgroups_vectorized
27+
from sklearn.linear_model import LogisticRegression
28+
from sklearn.model_selection import train_test_split
29+
30+
print(__doc__)
31+
# Author: Arthur Mensch
32+
33+
t0 = time.clock()
34+
35+
# We use SAGA solver
36+
solver = 'saga'
37+
38+
# Turn down for faster run time
39+
n_samples = 10000
40+
41+
# Memorized fetch_rcv1 for faster access
42+
dataset = fetch_20newsgroups_vectorized('all')
43+
X = dataset.data
44+
y = dataset.target
45+
X = X[:n_samples]
46+
y = y[:n_samples]
47+
48+
X_train, X_test, y_train, y_test = train_test_split(X, y,
49+
random_state=42,
50+
stratify=y,
51+
test_size=0.1)
52+
train_samples, n_features = X_train.shape
53+
n_classes = np.unique(y).shape[0]
54+
55+
print('Dataset 20newsgroup, train_samples=%i, n_features=%i, n_classes=%i'
56+
% (train_samples, n_features, n_classes))
57+
58+
models = {'ovr': {'name': 'One versus Rest', 'iters': [1, 3]},
59+
'multinomial': {'name': 'Multinomial', 'iters': [1, 3, 7]}}
60+
61+
for model in models:
62+
# Add initial chance-level values for plotting purpose
63+
accuracies = [1 / n_classes]
64+
times = [0]
65+
densities = [1]
66+
67+
model_params = models[model]
68+
69+
# Small number of epochs for fast runtime
70+
for this_max_iter in model_params['iters']:
71+
print('[model=%s, solver=%s] Number of epochs: %s' %
72+
(model_params['name'], solver, this_max_iter))
73+
lr = LogisticRegression(solver=solver,
74+
multi_class=model,
75+
C=1,
76+
penalty='l1',
77+
fit_intercept=True,
78+
max_iter=this_max_iter,
79+
random_state=42,
80+
)
81+
t1 = time.clock()
82+
lr.fit(X_train, y_train)
83+
train_time = time.clock() - t1
84+
85+
y_pred = lr.predict(X_test)
86+
accuracy = np.sum(y_pred == y_test) / y_test.shape[0]
87+
density = np.mean(lr.coef_ != 0, axis=1) * 100
88+
accuracies.append(accuracy)
89+
densities.append(density)
90+
times.append(train_time)
91+
models[model]['times'] = times
92+
models[model]['densities'] = densities
93+
models[model]['accuracies'] = accuracies
94+
print('Test accuracy for model %s: %.4f' % (model, accuracies[-1]))
95+
print('%% non-zero coefficients for model %s, '
96+
'per class:\n %s' % (model, densities[-1]))
97+
print('Run time (%i epochs) for model %s:'
98+
'%.2f' % (model_params['iters'][-1], model, times[-1]))
99+
100+
fig = plt.figure()
101+
ax = fig.add_subplot(111)
102+
103+
for model in models:
104+
name = models[model]['name']
105+
times = models[model]['times']
106+
accuracies = models[model]['accuracies']
107+
ax.plot(times, accuracies, marker='o',
108+
label='Model: %s' % name)
109+
ax.set_xlabel('Train time (s)')
110+
ax.set_ylabel('Test accuracy')
111+
ax.legend()
112+
fig.suptitle('Multinomial vs One-vs-Rest Logistic L1\n'
113+
'Dataset %s' % '20newsgroups')
114+
fig.tight_layout()
115+
fig.subplots_adjust(top=0.85)
116+
run_time = time.clock() - t0
117+
print('Example run in %.3f s' % run_time)
118+
plt.show()
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
{
2+
"nbformat_minor": 0,
3+
"nbformat": 4,
4+
"cells": [
5+
{
6+
"execution_count": null,
7+
"cell_type": "code",
8+
"source": [
9+
"%matplotlib inline"
10+
],
11+
"outputs": [],
12+
"metadata": {
13+
"collapsed": false
14+
}
15+
},
16+
{
17+
"source": [
18+
"\n=====================================================\nMNIST classfification using multinomial logistic + L1\n=====================================================\n\nHere we fit a multinomial logistic regression with L1 penalty on a subset of\nthe MNIST digits classification task. We use the SAGA algorithm for this\npurpose: this a solver that is fast when the number of samples is significantly\nlarger than the number of features and is able to finely optimize non-smooth\nobjective functions which is the case with the l1-penalty. Test accuracy\nreaches > 0.8, while weight vectors remains *sparse* and therefore more easily\n*interpretable*.\n\nNote that this accuracy of this l1-penalized linear model is significantly\nbelow what can be reached by an l2-penalized linear model or a non-linear\nmulti-layer perceptron model on this dataset.\n\n\n"
19+
],
20+
"cell_type": "markdown",
21+
"metadata": {}
22+
},
23+
{
24+
"execution_count": null,
25+
"cell_type": "code",
26+
"source": [
27+
"import time\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn.datasets import fetch_mldata\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.utils import check_random_state\n\nprint(__doc__)\n\n# Author: Arthur Mensch <[email protected]>\n# License: BSD 3 clause\n\n# Turn down for faster convergence\nt0 = time.time()\ntrain_samples = 5000\n\nmnist = fetch_mldata('MNIST original')\nX = mnist.data.astype('float64')\ny = mnist.target\nrandom_state = check_random_state(0)\npermutation = random_state.permutation(X.shape[0])\nX = X[permutation]\ny = y[permutation]\nX = X.reshape((X.shape[0], -1))\n\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, train_size=train_samples, test_size=10000)\n\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n# Turn up tolerance for faster convergence\nclf = LogisticRegression(C=50 / train_samples,\n multi_class='multinomial',\n penalty='l1', solver='saga', tol=0.1)\nclf.fit(X_train, y_train)\nsparsity = np.mean(clf.coef_ == 0) * 100\nscore = clf.score(X_test, y_test)\n# print('Best C % .4f' % clf.C_)\nprint(\"Sparsity with L1 penalty: %.2f%%\" % sparsity)\nprint(\"Test score with L1 penalty: %.4f\" % score)\n\ncoef = clf.coef_.copy()\nplt.figure(figsize=(10, 5))\nscale = np.abs(coef).max()\nfor i in range(10):\n l1_plot = plt.subplot(2, 5, i + 1)\n l1_plot.imshow(coef[i].reshape(28, 28), interpolation='nearest',\n cmap=plt.cm.RdBu, vmin=-scale, vmax=scale)\n l1_plot.set_xticks(())\n l1_plot.set_yticks(())\n l1_plot.set_xlabel('Class %i' % i)\nplt.suptitle('Classification vector for...')\n\nrun_time = time.time() - t0\nprint('Example run in %.3f s' % run_time)\nplt.show()"
28+
],
29+
"outputs": [],
30+
"metadata": {
31+
"collapsed": false
32+
}
33+
}
34+
],
35+
"metadata": {
36+
"kernelspec": {
37+
"display_name": "Python 2",
38+
"name": "python2",
39+
"language": "python"
40+
},
41+
"language_info": {
42+
"mimetype": "text/x-python",
43+
"nbconvert_exporter": "python",
44+
"name": "python",
45+
"file_extension": ".py",
46+
"version": "2.7.13",
47+
"pygments_lexer": "ipython2",
48+
"codemirror_mode": {
49+
"version": 2,
50+
"name": "ipython"
51+
}
52+
}
53+
}
54+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
=====================================================
3+
MNIST classfification using multinomial logistic + L1
4+
=====================================================
5+
6+
Here we fit a multinomial logistic regression with L1 penalty on a subset of
7+
the MNIST digits classification task. We use the SAGA algorithm for this
8+
purpose: this a solver that is fast when the number of samples is significantly
9+
larger than the number of features and is able to finely optimize non-smooth
10+
objective functions which is the case with the l1-penalty. Test accuracy
11+
reaches > 0.8, while weight vectors remains *sparse* and therefore more easily
12+
*interpretable*.
13+
14+
Note that this accuracy of this l1-penalized linear model is significantly
15+
below what can be reached by an l2-penalized linear model or a non-linear
16+
multi-layer perceptron model on this dataset.
17+
18+
"""
19+
import time
20+
import matplotlib.pyplot as plt
21+
import numpy as np
22+
23+
from sklearn.datasets import fetch_mldata
24+
from sklearn.linear_model import LogisticRegression
25+
from sklearn.model_selection import train_test_split
26+
from sklearn.preprocessing import StandardScaler
27+
from sklearn.utils import check_random_state
28+
29+
print(__doc__)
30+
31+
# Author: Arthur Mensch <[email protected]>
32+
# License: BSD 3 clause
33+
34+
# Turn down for faster convergence
35+
t0 = time.time()
36+
train_samples = 5000
37+
38+
mnist = fetch_mldata('MNIST original')
39+
X = mnist.data.astype('float64')
40+
y = mnist.target
41+
random_state = check_random_state(0)
42+
permutation = random_state.permutation(X.shape[0])
43+
X = X[permutation]
44+
y = y[permutation]
45+
X = X.reshape((X.shape[0], -1))
46+
47+
X_train, X_test, y_train, y_test = train_test_split(
48+
X, y, train_size=train_samples, test_size=10000)
49+
50+
scaler = StandardScaler()
51+
X_train = scaler.fit_transform(X_train)
52+
X_test = scaler.transform(X_test)
53+
54+
# Turn up tolerance for faster convergence
55+
clf = LogisticRegression(C=50 / train_samples,
56+
multi_class='multinomial',
57+
penalty='l1', solver='saga', tol=0.1)
58+
clf.fit(X_train, y_train)
59+
sparsity = np.mean(clf.coef_ == 0) * 100
60+
score = clf.score(X_test, y_test)
61+
# print('Best C % .4f' % clf.C_)
62+
print("Sparsity with L1 penalty: %.2f%%" % sparsity)
63+
print("Test score with L1 penalty: %.4f" % score)
64+
65+
coef = clf.coef_.copy()
66+
plt.figure(figsize=(10, 5))
67+
scale = np.abs(coef).max()
68+
for i in range(10):
69+
l1_plot = plt.subplot(2, 5, i + 1)
70+
l1_plot.imshow(coef[i].reshape(28, 28), interpolation='nearest',
71+
cmap=plt.cm.RdBu, vmin=-scale, vmax=scale)
72+
l1_plot.set_xticks(())
73+
l1_plot.set_yticks(())
74+
l1_plot.set_xlabel('Class %i' % i)
75+
plt.suptitle('Classification vector for...')
76+
77+
run_time = time.time() - t0
78+
print('Example run in %.3f s' % run_time)
79+
plt.show()

dev/_downloads/scikit-learn-docs.pdf

42.9 KB
Binary file not shown.

0 commit comments

Comments
 (0)