<jupyter_start><jupyter_text>Train an SMS spam detector  Import dependencies<jupyter_code>import numpy as np
import pandas as pd

import joblib, re

from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, classification_report
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split, cross_val_score

import streamlit as st<jupyter_output><empty_output><jupyter_text>Load and read the data<jupyter_code># read data
df = pd.read_csv('data/spam.csv', encoding="ISO-8859-1")

# drop useless columns
df = df[['v1', 'v2']]
# display
df.head()<jupyter_output><empty_output><jupyter_text>Preprocess data<jupyter_code># separate target from input text
x, y = df['v2'], df['v1']

# print example
idx = 2000
x[idx], y[idx]
# preprocess text data
def preprocessor(text):
    text = re.sub('<[^>]*>', '', text) # Effectively removes HTML markup tags
    emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text)
    text = re.sub('[\W]+', ' ', text.lower()) + ' '.join(emoticons).replace('-', '')
    return text
# train-test split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=123)<jupyter_output><empty_output><jupyter_text>Train a text classification model<jupyter_code>tfidf = TfidfVectorizer(strip_accents=None, lowercase=False, max_features=700, preprocessor=preprocessor, ngram_range=(1,1))


neural_net_pipeline = Pipeline([
    ('vectorizer', tfidf),
    ('nn_classifier', MLPClassifier(hidden_layer_sizes=(800, 600)))
], verbose=True)


neural_net_pipeline.fit(x_train, y_train)
y_pred = neural_net_pipeline.predict(x_test)
print(classification_report(y_test, y_pred))
print('Accuracy: {} %'.format(100 * accuracy_score(y_test, y_pred)))
joblib.dump(neural_net_pipeline, 'spam_classifier.joblib')<jupyter_output><empty_output><jupyter_text>[DEPREC] Take a look a vocabulary<jupyter_code>vect = tfidf.fit(x)
print(vect.transform(x[:3]))
print('Length of the vocabulary:', len(vect.vocabulary_))
print('---> sample of the vocabulary: ', {key: vect.vocabulary_[key] for key in list(vect.vocabulary_.keys())[:10]})<jupyter_output>Length of the vocabulary: 700
---> sample of the vocabulary:  {'go': 240, 'until': 614, 'available': 63, 'only': 427, 'in': 298, 'great': 249, 'world': 676, 'there': 569, 'got': 247, 'wat': 638}<jupyter_text>[DEPREC] Example predictions<jupyter_code>index = 2123
# x_sample = x_test.loc[x_test.index[811]]
x_sample = x_test.loc[index]
y_sample = y_test[index]
print(y_sample, '-----', x_sample)
neural_net_pipeline.predict([x_sample])
neural_net_pipeline.predict_proba([x_sample])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15067004708438972, 'fraction_numerical': 0.026801883375588555, 'mean_word_length': 7.420731707317073, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '405840', 'license': 'Apache-2.0', 'n_tokens_mistral': 1074, 'n_tokens_neox': 1002, 'n_words': 205, 'path': 'train_model.ipynb', 'repo_name': 'mehdi-elion/spam_detection_streamlit', 'size': '2761'}