JUPYTER NOTEBOOK

http://jupyter.org/

Project Jupyter is an open source project was born out of the IPython Project in 2014 as it evolved to support interactive data science and scientific computing across all programming languages. Jupyter will always be 100% open source software, free for all to use and released under the liberal terms of the modified BSD license

Características

- Interface no navegador
- Compartilhamento de notebooks (inslusive remoto)
- nbviwer - http://nbviewer.jupyter.org/
- jupterhub
- GitHub
- Docker

- Suporte para mais de 40 linguagens de programação
- Python
- R 
- Julia
- Scala
- etc

- Big data integration
- Apache Spark
- from Python
- R
- Scala
- scikit-learn
- ggplot2
- dplyr
- etc

- Suporte para latex $\LaTeX$, videos e imagens
- Documentação de suporte - https://jupyter.readthedocs.io/en/latest/index.html
- Interatividade e Widgets - http://jupyter.org/widgets.html
- Exporta para - https://ipython.org/ipython-doc/3/notebook/nbconvert.html
- latex
- html
- py/ipynb
- PDF

- Iporta modulos .py e .ipynb
- Tabelas

instalação

http://jupyter.readthedocs.io/en/latest/install.html

- Linux
- pip
    - pip3 install --upgrade pip
    - pip3 install jupyter

- Anaconda

- Windows/ macOS
- Anaconda - https://www.continuum.io/downloads



Usar o pytthon 2.7 porque é compatível com a grande maioria dos pacotes.

Se quiser instalar mais de uma versão do python, é melhor criar multiplos enviroments.

- Para poder exportar PDF
- http://pandoc.org/installing.html

EXEMPLO DE USO

Ajuste Polinomial de Curvas

Esse tutorial visa explicar os conceitos de overfitting e regulzarização através de um exemplo de ajuste polinomial de curvas usando o método dos mínimos quadrados. Overfitting ocorre quando o modelo decora os dados de entrada, de forma que o modelo se torne incapaz de generalizar para novos dados. Regulzarização é uma técnica para evitar o overfitting. O tutorial é uma adaptação do exemplo apresentado no capítulo 1 do livro: "Christopher M. Bishop. 2006. Pattern Recognition and Machine Learning (Information Science and Statistics). Springer-Verlag New York, Inc., Secaucus, NJ, USA."


In [9]:
%matplotlib inline
import numpy as np
import matplotlib.pylab as plt
from ipywidgets import *

#Variância do ruído
var = 0.3

#Conjunto de treino
train_size = 10
x_train = np.linspace(0,1,train_size)
y_train = np.sin(2*np.pi*x_train) + np.random.normal(0,var,train_size) #sinal + ruido

#Conjunto de teste
test_size = 100
x_test= np.linspace(0,1,test_size)
y = np.sin(2*np.pi*x_test)
y_test = y + np.random.normal(0,var,test_size) #sinal + ruido

# Gráfico do sinal sem ruído e do conhunto de treinamento gerado
plt.figure()
plt.plot(x_test,y,linewidth = 2.0,label = r'Modelo: $sin(2 \pi x)$')
plt.scatter(x_train,y_train,color='red',label = "Modelo + ruido")
plt.legend(loc = (0.02, 0.18))
plt.xlabel("x")
plt.ylabel("y")
plt.show()


Observações: $$\boldsymbol{X} =(x_1,x_2,...,x_N)^T$$ Alvo: $$\boldsymbol{T} =(t_1,t_2,...,t_N)^T$$

Dados

Observações: $$\boldsymbol{X} =(x_1,x_2,...,x_N)^T$$ Alvo: $$\boldsymbol{T} =(t_1,t_2,...,t_N)^T$$

Modelo

$$y(x,\boldsymbol{W})= w_0 + w_1x +w_2x^2+...+w_mx^m = \sum^M_{j=0}w_jx^j$$

Função de custo

Função de custo quadrática: $$E(\boldsymbol{W})=\frac{1}{2}\sum_{n=1}^N\{y(x_n,\boldsymbol{W})-t_n\}^2$$

Derivando a função de custo e igualando a zero obtemos o vetor W* que minimiza o erro: $$ \boldsymbol{W}^* = (\boldsymbol{A}^T\boldsymbol{A})^{-1}\boldsymbol{A} ^T\boldsymbol{T}$$

Onde A é definido por:

$$\boldsymbol{A} = \begin{bmatrix} 1 & x_{1} & x_{1}^2 & \dots & x_{1}^M \\ 1 & x_{2} & x_{2}^2 & \dots & x_{2}^M \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 1 & x_{N} & x_{N}^2 & \dots & x_{N}^M \end{bmatrix}$$

In [11]:
#Implementação da solução dos  mínimos quadrados
def polynomial_fit(X,T,M):
    A = np.power(X.reshape(-1,1),np.arange(0,M+1).reshape(1,-1))
    T = T.reshape(-1,1)
    W = np.dot(np.linalg.pinv(A),T)
    return W.ravel()

Plotando o resultado dos mínimos quadrados para polinômios de graus 0 a 9. Qual é um bom modelo?


In [12]:
def plotmodel(M):
    coefs = polynomial_fit(x_train, y_train, M)[::-1]
    p = np.poly1d(coefs)
    plt.figure()
    plt.plot(x_test,y,linewidth = 2.0,label = 'Real')
    plt.scatter(x_train,y_train,color='red',label= "Treino")
    plt.xlabel("x")
    plt.ylabel(r'y')
    y_fit = p(x_test) 
    plt.plot(x_test,y_fit,linewidth = 2.0,label ="Estimado")
    plt.plot(x_test,y_test,'x',color='black',label = "Teste")
    plt.legend(loc=(0.02,0.02))

interact(plotmodel,M=(0,9,1))



In [ ]: