<jupyter_start><jupyter_text>Import as bibliotecasVamos importar algumas bibliotecas para começar!<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt # biblioteca de visualização utilizada pelo pandas e pelo seaborn
import seaborn as sns # biblioteca de visualização com mais opções de gráficos
 #comando necessário para que as imagens sejam exibidas aqui mesmo no notebook
%matplotlib inline<jupyter_output><empty_output><jupyter_text>1. Acessando os dados * Utilize a função **pd.read_csv** para ler o dado preprocessado e salve-o na variável **train**    - O nome do dataset é **titanic_ready_to_ml.csv**    - Visualize alguns elementos do seu data set, para isto use **train.head()**<jupyter_code>train = pd.read_csv("titanic_ready_to_ml.csv")
train.head(10)<jupyter_output><empty_output><jupyter_text>Vejo o exemplo do iris  2. Importando mais bibliotecas  Vamos importar mais arquivos necessários.<jupyter_code># importe train_test_split do módulo sklearn.model_selection
# importe a biblioteca sklearn. 
# importe a classe DecisionTreeClassifier do módulo sklearn.tree. 
# importe as classes classification_report e confusion_matrix do módulo
import itertools
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix<jupyter_output><empty_output><jupyter_text>Separe os dados em teste e treino<jupyter_code>X_train, X_test, y_train, y_test = train_test_split(train.drop(['Survived'],axis=1), 
                                                    train['Survived'], test_size=0.30, 
                                                    random_state=101)<jupyter_output><empty_output><jupyter_text>Crie um objeto do classificador DecisionTreeClassifier()<jupyter_code>dtc = DecisionTreeClassifier()
rfc = RandomForestClassifier(n_estimators=100)<jupyter_output><empty_output><jupyter_text>Treine o modelo chamando a função fit<jupyter_code>dtc.fit(X_train, y_train)
rfc.fit(X_train, y_train)<jupyter_output><empty_output><jupyter_text>Faça as predições<jupyter_code>predictions = dtc.predict(X_test)
predictions2 = rfc.predict(X_test)
labels = ['business', 'health']
cnf_matrix = confusion_matrix(y_test, predictions, labels=[1,0])
cnf_matrix
labels = ['business', 'health']
cnf_matrix2 = confusion_matrix(y_test, predictions2, labels=[1,0])
cnf_matrix2
tn, fp, fn, tp = confusion_matrix(y_test, predictions, labels=[0,1]).ravel()
tn, fp, fn, tp 
tn2, fp2, fn2, tp2 = confusion_matrix(y_test, predictions2, labels=[0,1]).ravel()
tn2, fp2, fn2, tp2 
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.tight_layout()
plot_confusion_matrix(cnf_matrix, classes=['Sobrevivente','Nao sobrevivente'],
                      title='Confusion matrix, without normalization')
plot_confusion_matrix(cnf_matrix2, classes=['Sobrevivente','Nao sobrevivente'],
                      title='Confusion matrix, without normalization')
print(classification_report(y_test,predictions))
print(classification_report(y_test,predictions2))<jupyter_output>precision    recall  f1-score   support

           0       0.85      0.85      0.85       163
           1       0.77      0.77      0.77       104

   micro avg       0.82      0.82      0.82       267
   macro avg       0.81      0.81      0.81       267
weighted avg       0.82      0.82      0.82       267
{'fraction_non_alphanumeric': 0.09826974267968057, 'fraction_numerical': 0.023735581188997337, 'mean_word_length': 3.6010204081632655, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '330028', 'license': 'MIT', 'n_tokens_mistral': 1528, 'n_tokens_neox': 1460, 'n_words': 348, 'path': 'notebooks/Classificacao/Arvore_De_Decisao.ipynb', 'repo_name': 'alexssandroos/learn_treinamento_atl', 'size': '4508'}