<jupyter_start><jupyter_text>ML Pipeline PreparationFollow the instructions below to help you create your ML pipeline. 1. Import libraries and load data from database.- Import Python libraries- Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html)- Define feature and target variables X and Y<jupyter_code># import libraries
import pandas as pd
import sqlalchemy as DB
import nltk
import pickle
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize 
from nltk.stem import WordNetLemmatizer
from sklearn.pipeline import Pipeline
from sklearn.multioutput import MultiOutputClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import classification_report, accuracy_score
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
# load data from database
engine = DB.create_engine('sqlite:///myDB.db')
df = pd.read_sql('select * from myTable', con=engine)
X = df['message'].values
Y = df.drop(['id', 'message', 'genre'], axis=1)<jupyter_output><empty_output><jupyter_text>2. Write a tokenization function to process your text data<jupyter_code>def tokenize(text):
    tokens = word_tokenize(text)
    lemmatizer = WordNetLemmatizer()

    clean_tokens = []
    for tok in tokens:
        clean_tok = lemmatizer.lemmatize(tok).lower().strip()
        clean_tokens.append(clean_tok)

    return clean_tokens<jupyter_output><empty_output><jupyter_text>3. Build a machine learning pipelineThis machine pipeline should take in the `message` column as input and output classification results on the other 36 categories in the dataset. You may find the [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html) helpful for predicting multiple target variables.<jupyter_code>pipeline = Pipeline([
        ('vect', CountVectorizer(tokenizer=tokenize)),
        ('tfidf', TfidfTransformer()),
        ('clf', MultiOutputClassifier(RandomForestClassifier()))
    ])<jupyter_output><empty_output><jupyter_text>4. Train pipeline- Split data into train and test sets- Train pipeline<jupyter_code>X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
pipeline.fit(X_train, Y_train)<jupyter_output><empty_output><jupyter_text>5. Test your modelReport the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's `classification_report` on each.<jupyter_code>Y_pred = pipeline.predict(X_test)
Y_pred_df = pd.DataFrame(Y_pred, columns = Y_test.columns)
for column in Y_test.columns:
    print('------------------------------------------------------\n')
    print('Accuracy: ', accuracy_score(Y_test[column], Y_pred_df[column]))
    print('Feature: {}\n'.format(column))
    print(classification_report(Y_test[column],Y_pred_df[column]))<jupyter_output>------------------------------------------------------

Accuracy:  0.7934782608695652
Feature: related

              precision    recall  f1-score   support

           0       0.62      0.34      0.44      1217
           1       0.82      0.94      0.87      3986
           2       0.60      0.15      0.24        41

   micro avg       0.79      0.79      0.79      5244
   macro avg       0.68      0.48      0.52      5244
weighted avg       0.77      0.79      0.77      5244

------------------------------------------------------

Accuracy:  0.8861556064073226
Feature: request

              precision    recall  f1-score   support

           0       0.89      0.98      0.93      4356
           1       0.84      0.41      0.55       888

   micro avg       0.89      0.89      0.89      5244
   macro avg       0.86      0.70      0.74      5244
weighted avg       0.88      0.89      0.87      5244

------------------------------------------------------

Accuracy:  0.995232646834477[...]<jupyter_text>6. Improve your modelUse grid search to find better parameters.<jupyter_code>parameters = {
        'vect__ngram_range': ((1, 1), (1, 2)),
        'clf__estimator__min_samples_split': [2, 4],
    }
cv = GridSearchCV(pipeline, param_grid=parameters, verbose=2, n_jobs=4)
cv.fit(X_train, Y_train)
cv_pred = cv.predict(X_test)<jupyter_output><empty_output><jupyter_text>7. Test your modelShow the accuracy, precision, and recall of the tuned model.  Since this project focuses on code quality, process, and  pipelines, there is no minimum performance metric needed to pass. However, make sure to fine tune your models for accuracy, precision and recall to make your project stand out - especially for your portfolio!<jupyter_code>overall_accuracy_cv = (cv_pred == Y_test).mean().mean()
overall_accuracy_normal = (Y_pred == Y_test).mean().mean()
print(overall_accuracy_normal)
print(overall_accuracy_cv)
cv_pred_df = pd.DataFrame(cv_pred, columns = Y_test.columns)
for column in Y_test.columns:
    print('------------------------------------------------------\n')
    print('Feature: {}\n'.format(column))
    print('Accuracy: ', accuracy_score(Y_test[column], cv_pred_df[column]))
    print(classification_report(Y_test[column],cv_pred_df[column]))<jupyter_output>------------------------------------------------------

Feature: related

Accuracy:  0.7906178489702517
              precision    recall  f1-score   support

           0       0.61      0.35      0.45      1217
           1       0.82      0.93      0.87      3986
           2       0.44      0.10      0.16        41

   micro avg       0.79      0.79      0.79      5244
   macro avg       0.63      0.46      0.49      5244
weighted avg       0.77      0.79      0.77      5244

------------------------------------------------------

Feature: request

Accuracy:  0.8878718535469108
              precision    recall  f1-score   support

           0       0.89      0.98      0.94      4356
           1       0.82      0.43      0.57       888

   micro avg       0.89      0.89      0.89      5244
   macro avg       0.86      0.71      0.75      5244
weighted avg       0.88      0.89      0.87      5244

------------------------------------------------------

Feature: offer

Accuracy:  0[...]<jupyter_text>8. Try improving your model further. Here are a few ideas:* try other machine learning algorithms* add other features besides the TF-IDF<jupyter_code>improved_pipeline = Pipeline([
        ('vect', CountVectorizer(tokenizer=tokenize)),
        ('tfidf', TfidfTransformer()),
        ('clf', MultiOutputClassifier(AdaBoostClassifier()))
    ])
improved_pipeline.fit(X_train, Y_train)
improved_pred = improved_pipeline.predict(X_test)
improved_pred_df = pd.DataFrame(improved_pred, columns = Y_test.columns)
for column in Y_test.columns:
    print('------------------------------------------------------\n')
    print('Accuracy: ', accuracy_score(Y_test[column], improved_pred_df[column]))
    print('Feature: {}\n'.format(column))
    print(classification_report(Y_test[column],improved_pred_df[column]))
overall_accuracy = (improved_pred == Y_test).mean().mean()
overall_accuracy<jupyter_output><empty_output><jupyter_text>9. Export your model as a pickle file<jupyter_code>with open('adaboost.pkl', 'wb') as file:
    pickle.dump(improved_pipeline, file)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1514951045250066, 'fraction_numerical': 0.053188674252447735, 'mean_word_length': 2.4738051470588234, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 23, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '638062', 'license': 'MIT', 'n_tokens_mistral': 2483, 'n_tokens_neox': 2271, 'n_words': 580, 'path': 'ML Pipeline Preparation.ipynb', 'repo_name': 'rowhitswami/Disaster-Response-Project', 'size': '7558'}