Show Sidebar Hide Sidebar

# Path with L1- Logistic Regression in Scikit-learn

Computes path on IRIS dataset.

#### New to Plotly?¶

You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

### Version¶

In [1]:
import sklearn
sklearn.__version__

Out[1]:
'0.18.1'

### Imports¶

This tutorial imports l1_min_c.

In [2]:
import plotly.plotly as py
import plotly.graph_objs as go

from datetime import datetime
import numpy as np
from sklearn import linear_model
from sklearn import datasets
from sklearn.svm import l1_min_c


### Calculations¶

In [3]:
iris = datasets.load_iris()
X = iris.data
y = iris.target

X = X[y != 2]
y = y[y != 2]

X -= np.mean(X, 0)


Demo path functions

In [4]:
cs = l1_min_c(X, y, loss='log') * np.logspace(0, 3)

print("Computing regularization path ...")
start = datetime.now()
clf = linear_model.LogisticRegression(C=1.0, penalty='l1', tol=1e-6)
coefs_ = []
for c in cs:
clf.set_params(C=c)
clf.fit(X, y)
coefs_.append(clf.coef_.ravel().copy())
print("This took ", datetime.now() - start)

Computing regularization path ...
('This took ', datetime.timedelta(0, 0, 60255))


### Plot Results¶

In [5]:
coefs_ = np.array(coefs_)
y_ = []

for col in range(0, len(coefs_[0])):
y_.append([ ])
for row in range(0, len(coefs_)):
y_[col].append(coefs_[row][col])

data = []

for i in range(1, len(y_)):
trace = go.Scatter(x=np.log10(cs), y=y_[i],
mode='lines')
data.append(trace)

layout = go.Layout(title='Logistic Regression Path',
showlegend=False,
xaxis=dict(title='log(C)', zeroline=False),
yaxis=dict(title='Coefficients'))
fig = go.Figure(data=data, layout=layout)

In [6]:
py.iplot(fig)

Out[6]:

Author:

    Alexandre Gramfort <alexandre.gramfort@inria.fr>



    BSD 3 clause