<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 sys
import re
import nltk

import pandas as pd
import pickle
from sqlalchemy import create_engine
import matplotlib.pyplot as plt
%matplotlib inline

# import statements
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer

from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.multioutput import MultiOutputClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import classification_report
import warnings
warnings.filterwarnings("ignore")
nltk.download(['punkt', 'wordnet', 'stopwords'])
# load data from database
engine = create_engine('sqlite:///InsertDatabaseName.db')
df = pd.read_sql_table('InsertTableName', con=engine)
X = df['message'].values
Y = df.iloc[:,4:].values<jupyter_output><empty_output><jupyter_text>2. Write a tokenization function to process your text data<jupyter_code>url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
def tokenize(text):
    detected_urls = re.findall(url_regex, text)
    for url in detected_urls:
        text = text.replace(url, "urlplaceholder")
        
    # normalize text
    text = re.sub(r"[^a-zA-Z0-9]", " ", text.lower())
    # tokenize text
    tokens = word_tokenize(text)
    # Remove stopwords
    tokens = [t for t in tokens if t not in stopwords.words('english')]
    
    # initiate lemmatizer and lemmatize
    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)
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>categories = df.columns[4:]
range(0, len(categories))
def evaluate_model(model, X_test, y_test):
    '''
    Evaluate model's performance on test data
    Input: Model, test data set
    Output: the Classification report
    '''
    y_pred = model.predict(X_test)
    for i in range(0, len(categories)):
        print(categories[i])
        print(classification_report(y_test[:, i], y_pred[:, i]))
evaluate_model(pipeline, X_test, y_test)<jupyter_output>related
             precision    recall  f1-score   support

          0       0.64      0.47      0.54      1511
          1       0.85      0.92      0.88      4999
          2       0.37      0.36      0.37        44

avg / total       0.80      0.81      0.80      6554

request
             precision    recall  f1-score   support

          0       0.89      0.98      0.93      5400
          1       0.79      0.43      0.55      1154

avg / total       0.87      0.88      0.86      6554

offer
             precision    recall  f1-score   support

          0       1.00      1.00      1.00      6531
          1       0.00      0.00      0.00        23

avg / total       0.99      1.00      0.99      6554

aid_related
             precision    recall  f1-score   support

          0       0.75      0.86      0.80      3776
          1       0.77      0.60      0.67      2778

avg / total       0.75      0.75      0.75      6554

medical_help
             precision    recall  f1-sco[...]<jupyter_text>6. Improve your modelUse grid search to find better parameters.  parameters = {    'clf__estimator__min_samples_split': [2, 4],    'clf__estimator__max_features': [None, 'log2', 'sqrt'],    'clf__estimator__criterion': ['gini', 'entropy'],    'clf__estimator__max_depth': [25, 100, 200],}parameters = {    'vect__max_df': (0.5, 0.75, 1.0),     'vect__max_features': (None, 5000, 10000, 50000),    'vect__ngram_range': ((1, 1), (1, 2)),   unigrams or bigrams     'tfidf__use_idf': (True, False),     'tfidf__norm': ('l1', 'l2'),    'clf__max_iter': (20,),    'clf__alpha': (0.00001, 0.000001),    'clf__penalty': ('l2', 'elasticnet'),     'clf__max_iter': (10, 50, 80),}<jupyter_code>parameters = {
    #'vect__max_df': (0.5, 0.75, 1.0),
    # 'vect__max_features': (None, 5000, 10000, 50000),
    'vect__ngram_range': ((1, 1), (1, 2)),  # unigrams or bigrams
    'tfidf__use_idf': (True, False),
    # 'tfidf__norm': ('l1', 'l2'),
    #'clf__alpha': (0.00001, 0.000001),
    'clf__estimator__n_estimators': [50, 100],
    'clf__estimator__min_samples_split': [2, 4],
    # 'clf__max_iter': (10, 50, 80),
}

cv = GridSearchCV(pipeline, param_grid=parameters, n_jobs=-1, verbose=5)
cv.get_params().keys()
cv<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>cv.fit(X_train, y_train)
evaluate_model(cv, X_test, y_test)<jupyter_output><empty_output><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  9. Export your model as a pickle file<jupyter_code>with open('model_cv.pkl', 'wb') as file:
    pickle.dump(cv, file)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11063197026022305, 'fraction_numerical': 0.04728624535315985, 'mean_word_length': 3.36469824789098, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '621651', 'license': 'FTL', 'n_tokens_mistral': 2392, 'n_tokens_neox': 2208, 'n_words': 600, 'path': 'ML Pipeline Preparation.ipynb', 'repo_name': 'kaienn/DST2_Disaster-Response-Pipeline', 'size': '6725'}