<jupyter_start><jupyter_text>MultiClass Classification   Segundo a descrição provida pela página do [sklearn](http://scikit-learn.org/stable/modules/multiclass.html):    **Multiclass Classification** significa uma tarefa de classificação com mais de duas classes. Ex: uma série de imagens de frutas podem ser laranjas, maçãs ou pêras. **Multiclass Classification** assume que cada amostra pode ser classificada como uma, e apenas uma, categoria. Um ***dataset*** comum para esse tipo de problema é o **[iris flower dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set)**[Explicação de Andrew Ng para o MultiClass Classification](https://www.youtube.com/watch?v=ZvaELFv5IpM)<jupyter_code>import pandas as pd
import numpy as np


import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')

%matplotlib inline
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
iris = load_iris()
print(iris.DESCR)<jupyter_output>Iris Plants Database
====================

Notes
-----
Data Set Characteristics:
    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20  0.76     0.9565  (high!)
    ============== ==== ==== ======= ===== ====================

    :Missing Attr[...]<jupyter_text>Agora definimos nossos dados. Como de costume definimos `X` e `Y`.`X` = Nosso `DataFrame` com as `features``Y` = Nosso Array com o `Target`, o que queremos classificar<jupyter_code>X = pd.DataFrame(iris.data,columns=iris.feature_names)

Y = pd.DataFrame(iris.target,columns=['Species'])
X.columns = ['sepal len','sepal wid','petal len','petal wid']
X.head()
Y.head()<jupyter_output><empty_output><jupyter_text>Aqui construí um método para transformar os valores numéricos da coluna Species em nomes<jupyter_code>def name_flower(document):
    if document == 0:
        response = 'setosa'
    elif document == 2:
        response = 'versicolor'
    else:
        response = 'virginica'
    return response<jupyter_output><empty_output><jupyter_text>Use o método [.map](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html) para aplicar a função na coluna<jupyter_code>Y['Species'] = Y['Species'].map(name_flower)
Y.head()<jupyter_output><empty_output><jupyter_text>Juntar X e Y<jupyter_code>iris = pd.concat([X,Y],axis=1)
iris.head()<jupyter_output><empty_output><jupyter_text>Vamos visualizar esse DataFrame* Ferramenta muito interessante do Seaborn. [PairPlot](https://seaborn.pydata.org/generated/seaborn.pairplot.html)<jupyter_code>sns.pairplot(data=iris,hue='Species',size=2)<jupyter_output><empty_output><jupyter_text>Essa visualização nos mostra que a Setosa, de cor azul nos gráficos, é naturalmente bem separada. O maior desafio será identificar as outras duas flores! Vamos continuar com os gráficos e ver mais características<jupyter_code>sns.factorplot(x='petal len',data=iris,hue='Species',kind='count',size=10)
sns.factorplot(x='petal wid',data=iris,hue='Species',kind='count',size=10)
sns.factorplot(x='sepal wid',data=iris,hue='Species',kind='count',size=10)
sns.factorplot(x='sepal len',data=iris,hue='Species',kind='count',size=10)<jupyter_output><empty_output><jupyter_text>Vamos utilizar o Sklearn para classificar as flores!<jupyter_code>log_model = LogisticRegression()
np.ravel(Y['Species'])<jupyter_output><empty_output><jupyter_text>Divida os dados em Train e Test ObservaçãoPara `Y`, `target`, devemos utilizar uma array de uma dimensão ou uma coluna do `DataFrame`. Como eu transformei o `Y` em um `DataFrame` no inicio deste notebook, precisei passar apenas a coluna com os valores que quero classificar para o metodo `.fit`<jupyter_code>X_train, X_test, Y_train, Y_test = train_test_split(X,np.ravel(Y['Species']),test_size=0.3,random_state=3)
X_train.shape
log_model.fit(X_train,Y_train)<jupyter_output><empty_output><jupyter_text>Metrics from SkLearn: **[Metrics](http://scikit-learn.org/stable/modules/classes.html)**<jupyter_code>from sklearn import metrics
Y_predicts = log_model.predict(X_test)<jupyter_output><empty_output><jupyter_text>SuspeitoDar 100% de accuracy é suspeito<jupyter_code>print(metrics.accuracy_score(Y_test,Y_predicts))<jupyter_output>1.0<jupyter_text>K-nearest Neighbors[Sklearn K-nearest Neighbors Tutorial](http://scikit-learn.org/stable/modules/neighbors.html)[Kneighbors Classifier](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.htmlsklearn.neighbors.KNeighborsClassifier)<jupyter_code>from sklearn.neighbors import KNeighborsClassifier<jupyter_output><empty_output><jupyter_text>Utilizar o KNN se assemelha a utilizar as regressões que já aprendemos<jupyter_code>knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train,Y_train)
knn_pred = knn.predict(X_test)
print(metrics.accuracy_score(Y_test,knn_pred))<jupyter_output>0.955555555556
{'fraction_non_alphanumeric': 0.13975431725120172, 'fraction_numerical': 0.017981128716396653, 'mean_word_length': 5.376844494892168, 'pattern_counts': {'":': 0, '<': 50, '<?xml version=': 0, '>': 50, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '662328', 'license': 'MIT', 'n_tokens_mistral': 2083, 'n_tokens_neox': 1970, 'n_words': 420, 'path': 'Machine Learning/MultiClass Classification.ipynb', 'repo_name': 'SabinoGs/DataAnalysisEducation', 'size': '5617'}