A training dataset is the collection of examples used to fit a model’s parameters. For a toxicity classifier, each example can pair a comment with labels describing whether it is toxic, obscene, threatening, or otherwise abusive. section 4.2.1 section 9.3.4
Inspect examples and labels before training: look at the text format, comment lengths, and label accuracy. Trying the labeling task yourself can also help you judge whether it is reasonable for a model. section 9.3.4
Keep evaluation examples separate from those used to fit the model. Accuracy on training examples can be misleading: it is like taking an exam with questions you have already studied. A held-out set gives a more realistic check on unseen comments. section 4.2.1
A toxicity classifier’s training score
A linear discriminant analysis classifier scored 0.999 on its training split but only 0.554 on the held-out test split. The gap is a warning not to treat near-perfect training accuracy as evidence of comparable real-world performance. section 4.2.1
Listing 4.6 LDA model performance with train/test split
>>> from sklearn.model_selection import train_test_split >>> X_train, X_test, y_train, y_test = train_test_split(tfidf_docs,\ ... comments.toxic.values, test_size=0.5, random_state=271828) >>> lda_tfidf = LinearDiscriminantAnalysis(n_components=1) >>> lda = lda_tfidf.fit(X_train, y_train) #1 >>> round(float(lda.score(X_train, y_train)), 3) 0.999 >>> round(float(lda.score(X_test, y_test)), 3) 0.554
See how scikit-learn splits comment features and labels, fits on the training portion, and scores both portions. section 4.2.1
Preparing examples for BERT fine-tuning
The Toxic Comment Classification Challenge training file contains 159,571 rows. An 80/20 split produces 127,656 training examples and 31,915 evaluation examples; each is reformatted as text paired with six labels. A pretrained BERT model can then be fine-tuned on the training portion and evaluated on the held-out portion. section 9.3.4
Listing 9.33 Creating datasets for your model
>>> def get_dataset(X, y):
... data = [[X.iloc[i][0], y.iloc[i].values.tolist()]
for i in range(X.shape[0])]
... return pd.DataFrame(data, columns=['text', 'labels'])
...
>>> train_df = get_dataset(X_train, y_train)
>>> eval_df = get_dataset(X_test, y_test)
>>> train_df.shape, eval_df.shape
((127656, 2), (31915, 2))
>>> train_df.head() #1
text labels
0 Grandma Terri Should Burn in Trash \nGrandma T... [1, 0, 0, 0, 0, 0]
1 , 9 May 2009 (UTC)\nIt would be easiest if you... [0, 0, 0, 0, 0, 0]
2 "\n\nThe Objectivity of this Discussion is dou... [0, 0, 0, 0, 0, 0]
3 Shelly Shock\nShelly Shock is. . .( ) [0, 0, 0, 0, 0, 0]
4 I do not care. Refer to Ong Teng Cheong talk p... [0, 0, 0, 0, 0, 0]
Inspect the text-and-label format used for the training and evaluation datasets. section 9.3.4





































