Toxic challenge - classify comments as toxic or not
import numpy as np
import pandas as pd
import keras
import matplotlib.pyplot as plt
%matplotlib inline
import vis
Uncomment and run this to get the data
#!wget http://bit.do/deep_toxic_train -P data/
#! mv data/deep_toxic_train data/train.zip
df = pd.read_csv("data/train.zip")
df.columns
df.head()
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
train_sentences = df["comment_text"]
train_sentences.head()
# Tokenizer
max_features = 2000
tokenizer = Tokenizer(num_words = max_features)
tokenizer.fit_on_texts(list(train_sentences))
# Index Representation
tokenized_train = tokenizer.texts_to_sequences(train_sentences)
len(tokenized_train[0]), len(tokenized_train[1])
## Selecting Padding
# Find the length of each sentence and plot the lenght
number_of_words = [len(comment) for comment in tokenized_train]
plt.hist(number_of_words, bins = np.arange(0, 500, 10));
# Padding to make in uniform
maxlen = 200
X = pad_sequences(tokenized_train, maxlen = maxlen, padding="post")
X
labels = df.iloc[:,2].values
labels
# Baseline Beat
sum(labels), len(labels), 1 - sum(labels)/len(labels)
from keras.utils import to_categorical
y = to_categorical(labels)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2,
random_state=42)
X_train.shape, X_test.shape, y_test.shape, y_train.shape
from keras.models import Sequential
from keras.layers import Dense, Embedding, Dropout, LSTM, Flatten
model = Sequential()
model.add(Embedding(max_features, output_dim=128, input_length=maxlen))
model.add(Flatten())
model.add(Dense(50, activation="relu"))
model.add(Dropout(0.1))
model.add(Dense(2, activation="sigmoid"))
model.summary()
model.compile(loss="binary_crossentropy", optimizer="rmsprop", metrics=["accuracy"])
output = model.fit(X_train, y_train, batch_size=128, epochs=5,
validation_data =(X_test, y_test), verbose=1)
from keras.layers import LSTM
model_LSTM = Sequential()
model_LSTM.add(Embedding(max_features, output_dim=128, input_length=maxlen))
model_LSTM.add(LSTM(60))
model_LSTM.add(Dropout(0.1))
model_LSTM.add(Dense(2, activation="sigmoid"))
model_LSTM.compile(loss="binary_crossentropy", optimizer="rmsprop", metrics=["accuracy"])
output = model_LSTM.fit(X_train, y_train, batch_size=128, epochs=2,
validation_data =(X_test, y_test), verbose=1)