Machine Learning Techniques for the Detection of Inappropriate Erotic Content in Text
Paper · 2020 · Gonzalo Molpeceres Barrientos, Rocío Alaiz-Rodríguez, Víctor González-Castro et al.
Summary
A website can be suitable for children and still contain an individual post they should have the option to avoid. Molpeceres Barrientos and colleagues investigate whether a program can recognize erotic or sexual content from the text itself. They frame this as a text classification task in which each item receives an erotic or neutral label. The authors envisage filters for minors and for people who choose to avoid such material. Their experiment asks how well the text can be classified before any decision is made about what a filter should do with it.
The authors assembled 111,834 items from public Reddit data. The communities from which they drew the items supplied the labels, giving 50,921 erotic items and 60,913 neutral ones. They compared representations based on word counts, counts adjusted for how widely words occur across documents, and vectors learned from neighboring words. Each representation was paired with several conventional classifiers. The study also varied whether features were based on individual words or adjacent pairs, alongside settings specific to each classifier.
The strongest result in the main comparison came from a linear support vector machine using the adjusted counts known as TF-IDF. With the paper’s 2-gram setting, it reached a cross-validation accuracy of 0.9712 and an erotic-class F-score of 0.9621 in the main results tables. The abstract reports accuracy of 0.97, F-score of 0.96, precision of 0.96 and recall of 0.95. TF-IDF gave the best accuracy for most of the classifier families tested. The random forest was an exception, performing best with the learned vectors from Word2Vec.
The result depends on how the Reddit task was constructed. Cross-validation measures how well the classifiers recover the assigned labels on withheld items drawn from the assembled collection. Since those labels come from communities, the score can reflect vocabulary associated with a source as well as subject matter within a particular item. The study establishes that conventional text representations and classifiers can separate the selected material with high accuracy under that evaluation. Applying such a system to individual posts in mixed communities or on another service raises a different question about what the labels mean and which signals carry over.
Deep dive: Machine Learning Techniques for the Detection of Inappropriate Erotic Content in Text
A Reddit study compares word counts, TF-IDF and Word2Vec for detecting erotic text and examines how the choice of classifier changes the results. · about 37 minutes to read
The problem and its context
From website rules to decisions about posts
The authors start from a practical problem with parental controls. A list can determine whether a device may open a particular website, but access to the site tells the software little about any given item inside it. The paper uses the example of unsuitable advertising appearing on material that a family has already chosen to allow. The same issue arises with comments. A platform may serve many purposes and have an audience spanning different age groups, while individual contributions vary in subject matter.
The authors describe two other difficulties with the tools available at the time. Someone has to maintain the lists of allowed or blocked sites, and the judgments required for that maintenance can vary from person to person. Adults can also inspect browsing or app histories for signs that a child has encountered material they consider unsuitable. That option depends on someone taking the time to review the record and recognizing the relevant item after it has already been seen. The authors are interested in detecting content at the point when a decision about it could still affect what the reader sees.
For the operators of social networks, forums and commercial websites, the immediate concern is the volume of material submitted by users. A site may receive comments on subjects that change from one discussion to the next. Human review requires attention to individual contributions, and the paper argues that the volume makes thorough manual screening impractical. A system that supplies labels from text could direct attention to likely cases or support a filter. The paper’s experiment tests the classification step underlying such applications.
That step requires a narrower question than whether a whole site is appropriate for a particular reader. The authors look for a specific category of content, which they call erotic or sexual. They assign the other material the neutral label. Neutral consequently has an operational meaning in the study, referring to the comparison class chosen for this task. A moderation policy could have separate categories for aggression, threats or other material. Each category would require its own definition and evidence.
What earlier classification research offered
The paper places moderation within the history of automatic text categorization. It describes early applications in finding useful documents and later applications in filtering information, categorizing web material, recommending items, assessing sentiment and producing summaries. These tasks share a practical need to reduce the amount of text someone must inspect, even though the desired output differs. For the Reddit study, the output is a category assigned to a single piece of text. The authors draw on methods surveyed in earlier research on automated text categorization.
The research the authors review gives several accounts of what can count as inappropriate language. One project brought together simple classifiers to help block web content and considered information from websites in different languages. Another studied both search suggestions and messages in conversations. As the authors describe it, that work obtained stronger results with deep learning than with pattern rules and other handcrafted features. A study of comments on news articles looked at transforming the text before classification and found that its chosen transformations could improve performance. These experiments dealt with different settings, where the unit being classified could be a suggestion, a message or a comment.
Work on hate speech and offensive language provided a more specialized precedent. The paper recounts an experiment that used logistic regression on 24,840 manually labeled sentences from YouTube discussions concerning minority groups, immigrants and gay people. According to the report, about 10% of texts in the violent category were misclassified, and 5% of nonviolent texts were labeled violent. Those figures illustrate why errors in different categories deserve separate attention. A system can miss some of the material reviewers want it to find while also flagging material outside the target category. The paper situates such work alongside research including Automated Hate Speech Detection and the Problem of Offensive Language.
Cyberbullying studies offered examples of different choices about what evidence a classifier should receive. The paper describes a Twitter comparison in which TF-IDF performed better than pretrained GloVe and Word2Vec representations. It also discusses a study that drew features from the user, their activity and the contents of the tweet. That distinction matters for the Reddit experiment. Information about accounts or activity can supplement the text, whereas the classifiers in this study receive features derived from the words in the item. The related work includes GloVe and research on cyberbullying across social media platforms.
The paper also describes work on the Wikipedia Detox Project’s Attack and Aggression datasets. That study paired word counts and TF-IDF with conventional classifiers and compared them with StarSpace, a deep learning system. The authors report accuracy over 93% in that earlier work. The figure belongs to the reviewed research on attacks and aggression. The relevance to the Reddit study lies in the experimental design, which let researchers compare representations and learners on the same task.
The authors identify relatively little prior work aimed specifically at detecting explicit sexual or erotic comments in text. They cite research on filtering adult content to restrict access by minors as a related effort. Their own question concerns writing contributed by users and whether wording alone can support a useful distinction. A classifier for hate speech or aggression provides a precedent for the approach, while its training labels describe a different property of the text.
Why compare representations and classifiers together?
A program needs a representation of a post before it can classify it. A count of particular words makes some clues immediately accessible. A representation learned from word contexts can bring together terms that occur in similar company. Each design determines which similarities and differences are visible to the classifier, and each classifier has its own way of using those differences.
The authors note that conventional learning techniques can be attractive on text tasks because deep learning can require more training time and hardware. That argument explains their choice of systems to compare. Their experiment measures classification performance and leaves measurements of computational cost to other work. Its central question is which pairings work on the chosen task. The next section follows the stages of that comparison, from assigning labels through testing predictions. The broader approach is supervised machine learning applied to natural language processing.
The method, step by step
Assigning an example and its label
The procedure starts with text from public Reddit data. Reddit is divided into communities called subreddits, and the authors choose a set of communities for each class. A text drawn from a community assigned to the erotic group receives the erotic label. A text from the other group receives the neutral label. The category information comes from the source community, while the features supplied to the classifier come from the text.
This is supervised learning because the training examples already have target labels. The learner sees both a numerical representation and the associated category during training. During evaluation it receives the representation of a withheld item and produces a prediction, which can then be checked against the assigned label. The paper expresses the dataset as a collection of text and label pairs.
𝒟 = {(xᵢ, dᵢ) ∣ i = 1, …, N}
Here 𝒟 is the dataset, and each ordered pair consists of the text xᵢ and its label dᵢ. The subscript ᵢ refers to item i. The vertical bar introduces the range of item indices, the ellipsis represents the intermediate indices, and N is the total number of items. At this stage xᵢ is a document or text segment. Later the paper uses x notation for the numerical representation of a document as well.
From Reddit text to an evaluated prediction
The steps in order.
Normalizing the writing
Before numerical encoding, the authors convert the letters to lower-case. They remove material outside the words and reduce the spaces separating them to a single space. Their cleaning example illustrates the effects of deleting a digit attached to a word and removing emphatic punctuation at the end of a fragment. After this operation, differences in capitalization and punctuation patterns are unavailable as direct features. A word written in all capitals and its lower-case form can contribute to the same entry in the representation.
They also remove stop words, a list of common words selected for omission. This changes which parts of the text are available to each encoder. A word on the list can appear in the original item and still contribute no direct count to the resulting vector. For an adjacent-pair feature, the relevant sequence is the one the feature extractor receives after preprocessing. The relationship between the cleaned sequence and the original sentence therefore matters when interpreting a pair.
The authors use lemmatization to reduce lexical variants to a common form. They illustrate the idea with forms of the verb be. Collapsing variants allows occurrences that take different grammatical forms to contribute to the same lexical feature. The description names spaCy for lemmatization and NLTK for stop-word removal and tokenization, the operation that identifies the word units passed to the encoders. The paper also identifies scikit-learn in its account of preprocessing and count-based feature extraction.
The result is a sequence of tokens suitable for the next stage. Treating the text as tokens makes it possible to define a vocabulary and compare which units occur in different items. Normalization introduces an assumption about what should count as the same evidence. It lets variants share a feature, while distinctions erased at this stage cannot be recovered by choosing a more flexible classifier later.
Choosing the size of a feature
The experiment reports unigram and bigram settings for its encoders. A unigram is an individual token, the n = 1 case of an n-gram. A bigram is an adjacent pair, corresponding to n = 2. A classifier using counts of individual words can detect their presence regardless of where they occur. A bigram can provide evidence that particular words occur together in a specific order. A representation built from such pairs still leaves out the location of each occurrence within the longer document.
The vocabulary determines which token types or pairs can have a feature. For bag of words and TF-IDF, the authors report a minimum document frequency of 3. Document frequency counts how many documents contain a feature. Applying a lower cutoff removes features that occur in too few documents to qualify for the vocabulary. A feature could occur repeatedly in the same item and still fall below a cutoff based on the number of items in which it appears. The cutoff serves a different purpose from the within-document count used to represent a particular item.
The reported comparisons distinguish settings labeled 1-gram and 2-gram. For count-based features the distinction is intuitive, since the columns can stand for words or pairs. For Word2Vec, a neighboring-word prediction window and an n-gram setting describe different parts of the representation. The window determines which surrounding positions can supply training context. The n-gram setting concerns the units used in feature extraction. The paper gives the Word2Vec training parameters and the results for both settings, with less detail about how the bigram features were formed for that encoder.
Counting what appears in the document
Bag of words represents each text by the occurrences of features in a common vocabulary. Imagine reading a row of such a representation. The name above each position identifies a word or pair, and the value in the row records the corresponding evidence in that text. The same position has the same meaning for every document. A classifier can compare many texts because the rows all use the same vocabulary.
The paper’s illustration of bag of words takes a phrase and encodes it by reference to an existing dictionary. Entries associated with units that appear in the phrase receive their counts, while the other entries have no occurrences to record. The illustration captures why an individual document’s vector can be sparse. The complete vocabulary can cover a large collection, and any particular text may use only a small portion of it.
The authors describe the general document vector as follows.
xᵢ = [xᵢ₁, xᵢ₂, …, xᵢₚ]
Here xᵢ is the numerical representation for document i. The bracketed expression lists the coordinates of the vector, and the ellipsis stands for the intervening coordinates. The final index p is the number of features in the vocabulary. A coordinate written xᵢⱼ is the value of feature j in document i. The paper calls the feature itself fⱼ. For bag of words, the coordinate records its frequency. For TF-IDF, it records a weight for that same feature.
Two texts with the same individual word counts receive the same unigram bag-of-words representation even if their sentences arrange the words differently. Adjacent pairs can distinguish some such arrangements. In either case, the representation makes lexical evidence easy to inspect. Each coordinate has a vocabulary entry attached to it, and two different entries occupy distinct coordinates even if their meanings are related.
Weighting terms by where they occur
TF-IDF starts with the same kind of vocabulary as bag of words. It changes what a coordinate value means. A term can receive a high weight when it occurs often in the current document and is comparatively uncommon across the collection. A term shared by many documents carries less weight under the inverse-document-frequency factor. The authors present this as a way to make document vectors reflect the words that help distinguish one text from the rest.
They first describe the weights for an individual document as a vector.
wᴰ = (w₁,ᴰ, w₂,ᴰ, …, wₚ,ᴰ)
Here D identifies the document and wᴰ is its vector of weights. An entry such as w₁,ᴰ is the weight of the first vocabulary term in D. The initial subscript selects a term, p is the vocabulary size, and the ellipsis denotes the remaining entries between those shown. The parentheses group the ordered weights into a vector. The position of a weight identifies the associated feature across documents.
The paper defines each weight with the following expression.
wᵢ,ᴰ = tfᵢ,ᴰ × log(N / dfᵢ)
In this formula i indexes a term, and D identifies the document being represented. The value wᵢ,ᴰ is the weight assigned to that term. The quantity tfᵢ,ᴰ is the frequency of term i in D, dfᵢ counts the documents that contain it, and N is the size of the document collection. The slash denotes division. The function log takes the logarithm of the resulting ratio, and the multiplication sign combines that collection-wide factor with the local frequency. The indices in this formula serve different roles from those in the dataset notation, where i selects a document.
The weight addresses a feature of raw counts that matters to classification. A term can be common in a given item simply because it is common throughout the collection. Another term can occur in an item and be comparatively unusual elsewhere. Document frequency lets the representation treat those cases differently before the classifier learns which categories to assign. A high TF-IDF value itself expresses distinctiveness in the collection. Information about whether that distinctiveness favors the erotic or neutral class comes from the supervised training stage.
The authors relate inverse document frequency to earlier work on term specificity in information retrieval. Their experiment uses scikit-learn to implement the count-based encoders. The analytical expression explains the weighting principle, while the experimental account identifies the minimum document frequency and the n-gram settings. The paper gives the expression as the definition of TF-IDF and leaves some details of the software configuration implicit.
Learning a representation for each word
Word2Vec begins with a different unit of representation. Bag of words gives a document a coordinate for each vocabulary entry. Word2Vec learns a dense vector for each word, where an individual coordinate has no assigned word name. Information about a word is distributed across its vector. The authors discuss this method alongside GloVe and FastText as ways to obtain word embeddings.
In the architecture the paper describes, the input and output layers correspond in size to the training vocabulary. Between them is a single hidden layer. Its width determines the dimensionality of the learned vectors. The network adjusts its weights with a prediction task involving words and their neighbors. The weights learned during that process provide the numerical word representations. The training signal at this stage is the relationship between words in the corpus. Erotic and neutral labels enter when the document classifier is trained.
The paper explains both Continuous Bag-of-Words, abbreviated CBOW, and Skip-Gram. CBOW predicts a center word from surrounding words. Skip-Gram starts with the center word and tries to predict its neighbors. The paper’s example uses a window of size 1. When the center word is dog, the immediate neighbors greedy and story form the context. CBOW would use those neighbors to predict dog. Skip-Gram uses dog as the input for predicting words in the surrounding context. The separate architecture illustration shows a context window of size 2. Both are explanatory examples. The Reddit experiment uses a context window of 5.
The authors describe earlier work as suggesting that the direction of prediction can matter to training speed and the treatment of infrequent words. The Reddit comparison implements CBOW in Gensim. The alternative Skip-Gram design explains the choice available within Word2Vec, and the study reports no direct comparison between the designs. For details about the original approaches, the paper points readers to Efficient Estimation of Word Representations in Vector Space and Distributed Representations of Words and Phrases and their Compositionality.
The authors set the embedding dimensionality to 500 and train for 30 epochs, meaning passes through the material used for training. They report a minimum frequency setting of 3, described in the paper as a minimum document frequency. Training uses negative sampling with 5 negative samples. The idea is to learn from the words observed in context and from sampled alternatives that the prediction should distinguish from them. The paper discusses hierarchical softmax as another way to train Word2Vec. It uses negative sampling in the Reddit experiments. The threshold for random downsampling of higher-frequency words is 0.001.
These settings play separate roles. The context window controls which surrounding words can contribute to prediction examples. The dimensionality sets the size of each trained word vector. The frequency cutoff limits the items eligible for representation, while downsampling controls the influence of highly frequent words during training. The number of epochs and the negative samples relate to how the learning objective is applied. The study holds this Word2Vec recipe fixed while evaluating its use with different downstream classifiers and n-gram settings.
Turning word vectors into a document vector
A classifier needs an input representation for the entire item. Word2Vec provides representations at the word level, so the authors describe expressing a document in the shared space of its word vectors. The paper gives the following matrix relation.
x∗ = W x
Here x is the original document column vector with dimensions p × 1, where p is the size of the vocabulary and the 1 denotes a single column. W is the embedding matrix of dimensions q × p. Its columns correspond to the vocabulary entries, and q is the dimensionality of a word vector. The juxtaposition W x denotes matrix multiplication. The result x∗ is the document column vector in the embedding space, with dimensions q × 1. The star distinguishes the transformed vector from the original x.
This expression shows how to combine word vectors according to the coordinates of the document. Each coordinate of x supplies a coefficient for the corresponding column of W. The transformation yields a document vector whose positions are learned embedding dimensions. A conventional classifier can then use these dimensions as ordinary numerical inputs. The equation states the mapping at the level of document representation. The experimental description gives fewer details about the exact weighting of x in the implementation and the handling of vocabulary items with no learned vector.
The representation can alter what is easy to separate. Several distinct lexical entries may contribute vectors with shared properties because they have similar contexts. That is a potential advantage when related words occur in different documents. The combination can also make the contribution of a single distinctive word harder to recover from the resulting vector. The experiment asks which effects matter for the supervised task by pairing each encoding with the same families of classifiers.
Comparing the decision rules
The linear support vector machine, or SVM, classifies documents by their position relative to a boundary in the feature space. In a text task, the coordinates of that space could be word counts, TF-IDF weights or embedding dimensions. A linear boundary lets each coordinate contribute to an overall decision. Training a support vector machine involves balancing separation of the classes against the penalty for training examples that violate the desired margin. The authors vary C, the inverse of regularization strength. Their linear SVM search uses 0.1, 1, 10 and 100.
They also test a support vector machine with a radial basis function kernel, abbreviated RBF. Its underlying comparison depends on proximity between feature vectors, letting it represent a curved decision boundary in the original space. The setting γ controls how quickly the influence of similarity changes with distance. This matters when an encoder changes the scale or arrangement of documents in the space. The RBF configurations combine C values of 0.1, 1 and 10 with γ values of 0.1 and 1.
Logistic regression also learns a weighted combination of the features. It uses this combination to estimate the probability of a class and assign a label. Like the linear SVM, it can use a vocabulary-wide pattern of evidence from the input. Its training objective is different, which makes the comparison informative even when both learners use linear decisions. The values of the inverse regularization strength tested for logistic regression are 0.1, 1, 10 and 100.
The k-nearest neighbors classifier, or kNN, assigns a category by consulting training items that lie near the new document. It measures distance in the encoded feature space, using Euclidean distance in this study. The value of k specifies the number of neighbors considered. The authors test 3, 5 and 7. A change of encoder can therefore change which training items are consulted. For a count-based representation, the dimensions are lexical features. With Word2Vec they are the components of a dense document vector.
The random forest builds a collection of decision trees. A tree divides the items according to feature values, making successive decisions as the item moves toward a leaf. The forest combines the decisions of its trees. The authors test forests of 3, 10 and 30 trees, with a maximum depth of 5 or no prescribed maximum depth. In the latter setting, trees can continue growing until leaves are pure or have too few observations to split. A pure leaf contains examples belonging to a single class. Depth specifies how many successive decisions a path through a tree can use, so it directly affects how much structure a tree can fit.
The classifiers are implemented in scikit-learn, with default settings for parameters the authors do not otherwise specify. The comparison covers four classifier families, and the two kernel choices for the SVM produce separate result rows. That distinction accounts for why the results discuss both linear and RBF SVM configurations alongside logistic regression, nearest neighbors and random forests.
Estimating performance on withheld items
The authors use k-fold cross-validation with k = 5. The collection is divided into folds so that a classifier can be trained on the other parts and evaluated on the fold withheld for that run. Rotating the withheld part allows the study to evaluate predictions across the collection under that partitioning procedure. The symbol k here counts folds. In nearest neighbors, k instead counts training items consulted to make a prediction.
Cross-validation supplies the basis for the reported comparisons. A held-out item contributes its text to the prediction step and its assigned label to the scoring step. The generalization being estimated is to other items represented by those folds. Whether the same result would hold for a withheld community, later period or different source depends on how those cases are represented in training and evaluation. The paper describes cross-validation and the parameter grid, with fewer details about the independence of representation fitting and parameter selection from the evaluation folds.
The score is calculated after identifying the erotic class as positive. This convention determines how the paper names correct and incorrect decisions. In this experiment a positive prediction means that the classifier has assigned the erotic label. Its correctness is assessed against the class assigned from the selected subreddit.
Experiments and results
The Reddit collection
The authors report starting from a public Reddit dataset with 98,753,936 files. They filtered by subreddit and selected material from January and July in the years 2015–2018. The resulting collection contains 111,834 files, of which 50,921 belong to the erotic group and 60,913 to the neutral group. The paper uses comments, posts and files in its descriptions of the material. The reported counts refer to the files in the assembled classification dataset.
The corpus table gives the communities and the number of selected files from each. In the erotic group, sex contributes 25,640 files and gonewildstories contributes 12,943. The same group includes eroticliterature, with 528 files, and eroticwriting, with 29. These names show that the class draws on communities centered on sexual discussion as well as communities organized around erotic writing.
The neutral group includes explainlikeimfive, with 18,760 files, pets, with 11,053, paranormal, with 10,176, and outoftheloop, with 8133. It also includes more directly literary communities. The paper reports 1619 files from stories, 545 from literature and 440 from write. The neutral label encompasses material from many subjects. Writing and storytelling are represented on both sides of the comparison at least at the level of the communities’ stated themes.
The differences in community sizes matter when considering what contributes to the aggregate result. A classifier that performs well on items from a large source can affect an overall score more than one that distinguishes items from a source with few examples. The paper’s reporting is organized by classifier, encoder, parameters and class. It gives the distribution of input sources, while the performance tables summarize behavior across sources.
Reading the evaluation metrics
Accuracy answers how frequently the assigned label and the prediction agree across the evaluation examples. The paper counts correct erotic decisions and correct neutral decisions together.
accuracy = (tp + tn) / (tp + fp + fn + tn)
Here tp counts true positives, which are erotic-labeled items predicted as erotic. The term tn counts true negatives, which are neutral-labeled items predicted as neutral. The term fp counts false positives, where a neutral-labeled item is predicted as erotic. The term fn counts false negatives, where an erotic-labeled item is predicted as neutral. The plus signs add the relevant counts. Division by the total number of predictions gives the fraction that agree with the assigned labels. Parentheses group the sums.
Precision takes the perspective of a reader looking at the items a system has flagged. A high erotic-class precision means that a large share of the flagged items carry the erotic label in the dataset.
precision = tp / (tp + fp)
The symbol tp counts correct erotic predictions, and fp counts neutral items predicted to be erotic. Their sum is the number of positive predictions, as indicated by the grouped denominator. The slash divides the number of correct positive decisions by that sum. The precision score consequently depends on which items the classifier chooses to flag.
Recall takes the perspective of a reader who wants to know how much erotic material the system found. Its denominator includes the erotic items that the system overlooked.
recall = tp / (tp + fn)
Here tp again counts erotic items correctly identified. The symbol fn counts items bearing the erotic label that were assigned to the neutral category by the classifier. The sum in parentheses counts all items labeled erotic in the evaluation. The ratio expresses how much of that group the classifier recovered.
A classifier can achieve good precision by making positive predictions only for cases it identifies with strong confidence. If that strategy overlooks many positive examples, its recall will show the cost. The authors also report an F-score, which combines the two measures using their harmonic mean.
F-score = 2 × (precision × recall) / (precision + recall)
Here precision is the share of positive predictions that are correct, and recall is the share of positive examples recovered. The multiplication signs combine the values in the numerator and apply the factor 2. The plus sign adds precision and recall in the denominator, and the slash divides the grouped product by the grouped sum. The harmonic mean gives a lower value when one of the measures is weak, even if the other is strong. The authors report class-specific measures for erotic and neutral items in the appendix. The main F-score table emphasizes the erotic class.
The strongest results across classifiers
The main comparison uses the conventional systems as baselines for one another. Component choices can be compared on the same dataset, while each pairing is represented by its highest reported score under the settings considered. The accuracy chart isolates the best TF-IDF result the paper lists for each classifier variant. The associated settings can differ from one row to another.
Best reported TF-IDF accuracy by classifier on the Reddit dataset
The linear SVM leads, with the RBF SVM and logistic regression close behind.
The numbers
| System or setting | accuracy |
|---|---|
| Linear SVM (this paper) | 0.9712 |
| RBF SVM | 0.9707 |
| Logistic regression | 0.9687 |
| Random forest | 0.9375 |
| k-nearest neighbors | 0.9294 |
The linear SVM achieves 0.9712 accuracy with TF-IDF in the 2-gram setting and C = 100. In the detailed results, that configuration has erotic-class precision of 0.9666 and recall of 0.9577. The neutral-class precision is 0.9727 and recall is 0.9796. The reported F-scores are 0.9621 for the erotic class and 0.9761 for the neutral class. These numbers describe the same configuration in the detailed linear SVM results.
The abstract describes the leading combination with accuracy of 0.97, F-score of 0.96, precision of 0.96 and recall of 0.95. The conclusion reports a classification error of 3%. The more detailed results identify the actual settings and let the reader see how the erotic and neutral errors contribute to the overall outcome. For instance, the lower recall for erotic items means that a larger share of the assigned erotic group was missed than the share of the assigned neutral group that was missed.
The strongest RBF SVM accuracy with TF-IDF is 0.9707. The setting behind it is the 2-gram representation with C = 10 and γ = 0.1. Its erotic-class precision is 0.9667 and its erotic recall is 0.9561. Logistic regression reaches 0.9687 accuracy with TF-IDF in the 2-gram setting and C = 100. Its erotic-class precision is 0.9672 and recall is 0.9504. Both are close to the leading linear SVM in the main comparison. The ordering is descriptive, since the paper does not accompany these differences with estimates of sampling uncertainty.
Comparing the encoders
Looking at the encoders within the same classifier answers a different question. For the linear SVM, the best bag-of-words configuration reaches 0.9642 accuracy, and the best Word2Vec configuration reaches 0.9601. TF-IDF leads with 0.9712. The ordering is also visible in the erotic-class F-scores reported for that classifier.
Best reported erotic-class F-score by encoder for the linear SVM on Reddit
TF-IDF gives the strongest erotic-class F-score with the linear SVM.
The numbers
| System or setting | erotic-class F-score |
|---|---|
| Bag of words | 0.9527 |
| TF-IDF (this paper) | 0.9621 |
| Word2Vec | 0.9474 |
The encoder comparison for logistic regression follows a related pattern. Its best bag-of-words accuracy is 0.9639, compared with 0.9617 for Word2Vec and 0.9687 for TF-IDF. The erotic-class F-scores are 0.9522 for bag of words, 0.9494 for Word2Vec and 0.9587 for TF-IDF. The common finding across these linear learners is that giving distinctive terms their own weighted coordinates works well for the assigned Reddit classes.
Bag of words fares very differently with the RBF SVM. Its highest accuracy in the main table is 0.8019 and its highest erotic F-score is 0.7402. Word2Vec reaches 0.9659 accuracy and 0.955 erotic F-score with that classifier in the main tables. The RBF SVM therefore gives Word2Vec one of its strongest reported outcomes. The detailed runs show how dependent that outcome is on the kernel parameters.
For nearest neighbors the highest accuracy is 0.9294 with TF-IDF, compared with 0.9159 for Word2Vec and 0.8211 for bag of words. The best reported erotic F-scores are 0.9065, 0.896 and 0.7213, respectively. Those maxima summarize distinct settings. The detailed results show that some Word2Vec settings find a larger share of the erotic items than the leading TF-IDF setting, at the cost of flagging more neutral items.
The random forest changes the encoder ordering. Its highest accuracy is 0.9493 with Word2Vec. TF-IDF reaches 0.9375 and bag of words reaches 0.9218. The main erotic-class F-score table gives 0.9323 for Word2Vec, 0.9166 for TF-IDF and 0.8978 for bag of words. All of these forest results concern the chosen Reddit collection. They show that the paper’s broad preference for TF-IDF depends on which decision rule receives the features.
The figures in the main tables are useful for asking how far a classifier and encoder pairing can go within the tested settings. The maximum for accuracy is selected for that metric, and the maximum for F-score is selected for its metric. When interpreting precision and recall together, the detailed configuration rows provide the appropriate values from the same run. The next section uses those rows to examine which changes improve results and which introduce new errors.
What the ablations show
What the comparisons hold fixed
The paper offers component comparisons and parameter sweeps. It does not report a systematic ablation that removes each preprocessing operation from the final system. Its closest controlled comparisons hold a learner and some of its settings fixed while changing the representation, or hold the representation fixed while changing a classifier setting. The main tables answer a related question about the best outcome found for each pairing after considering its settings. The detailed comparisons are better suited to tracing the effect of a specific change.
Weighting and the linear decision
The linear SVM results provide a direct comparison between counts and weighted features. At C = 100 in the 2-gram setting, bag of words gives an accuracy of 0.963 and an erotic-class F-score of 0.951. TF-IDF at the same classifier and n-gram settings gives accuracy of 0.9712 and an erotic F-score of 0.9621. This comparison supports the view that collection-wide term weighting contributes to the leading result. It leaves open which terms carry the useful distinction and how closely those terms track platform or community vocabulary.
The detailed results qualify the role of tuning. With TF-IDF in the 2-gram setting, the linear SVM’s reported accuracy starts at 0.9585 for C = 0.1 and reaches 0.9712 for C = 100. With Word2Vec in the 1-gram setting, accuracy is 0.9601 at C = 1 and 0.9474 at C = 100. The paper describes an improvement as C increases in its discussion of the linear SVM. The detailed values support that pattern for the winning TF-IDF case. In the methods, C is defined as the inverse of regularization strength, so increasing it corresponds to weaker regularization in that parameterization.
Logistic regression gives a second view of that interaction. With TF-IDF in the 2-gram setting, it reports accuracy of 0.9034 at C = 0.1 and 0.9687 at C = 100. For the Word2Vec 1-gram setting, the corresponding endpoints are 0.961 and 0.9592. A setting that helps a linear learner use sparse lexical features can behave differently with dense inputs. The sweep provides evidence about those pairings within the tested range.
When a nonlinear kernel changes the errors
The RBF SVM’s performance depends strongly on its encoder and parameter settings. With Word2Vec, the authors highlight a 1-gram accuracy of 0.6385 at C = 0.1 and γ = 1, alongside 0.9659 at C = 1 and γ = 1. The erotic-class precision at the lower-performing setting is 1, but its erotic recall is 0.0484. This combination is compatible with a system that is extremely selective in assigning positive labels. Its high precision gives little indication of how much erotic material it recovers until recall is examined.
Keeping the encoder and n-gram setting fixed reveals sensitivity to γ as well. In the RBF SVM’s Word2Vec 1-gram results at C = 10, the paper reports accuracy of 0.9649 for γ = 0.1 and 0.722 for γ = 1. Erotic recall falls from 0.9384 to 0.2758 across those configurations. A kernel changes how proximity among documents enters the decision, and the authors suggest that representations may differ in how well they work with the resulting transformation. The scores establish the sensitivity. The paper offers the transformation as an explanation and leaves its geometric effects unmeasured.
Bag of words produces some of the strongest examples of missed positives in the RBF sweep. For the 2-gram configuration at C = 0.1 and γ = 0.1, the reported erotic recall and F-score are both 0, with neutral recall of 1 and accuracy of 0.6207. This illustrates what aggregate accuracy can hide. A classifier can predict the neutral class for the cases it receives and preserve some accuracy through that class while failing to serve the experiment’s main detection objective.
TF-IDF gives much more consistent high results with the RBF SVM at the upper end of the grid. In the 2-gram setting at C = 10 and γ = 0.1, the detailed table reports accuracy of 0.9707 and erotic recall of 0.9561. At the same C and with γ = 1, it gives accuracy of 0.9654 and erotic recall of 0.9386. This is a more modest change in both quantities than the Word2Vec example at the same C. The top RBF score shows that the method can work well, while the sweep shows why that best score alone gives an incomplete picture.
What changing the number of neighbors reveals
For nearest neighbors, the encoder determines which training examples count as similar under Euclidean distance. Increasing k changes how many of those examples can influence the prediction. The best TF-IDF accuracy in the 2-gram setting occurs at k = 7. The detailed accuracies for k = 3 and k = 5 are 0.912 and 0.923, followed by 0.9294 at k = 7. In this configuration, the observed pattern supports the authors’ account that using more neighbors helped.
The 2-gram bag-of-words results show the reverse pattern over the same settings. Accuracy is 0.7531 at k = 3, 0.742 at k = 5 and 0.7379 at k = 7. Erotic recall changes from 0.392 at k = 3 to 0.3371 at k = 7. Precision rises from 0.9179 to 0.9407. As more neighbors are consulted under this representation, the decisions favor a more selective identification of the erotic class. The precision, recall and accuracy changes together explain why the result worsens on the measures the authors emphasize.
Comparing different encodings at the same k reveals another tradeoff. At k = 7 in the 2-gram setting, TF-IDF achieves erotic precision of 0.8985 and recall of 0.9151. Word2Vec gives erotic precision of 0.8322 and recall of 0.9701. The Word2Vec setting identifies more of the erotic-labeled items, while its flags are less frequently correct. TF-IDF achieves the stronger erotic F-score for those settings. A rule chosen specifically to recover as much labeled erotic material as possible could value the two outcomes differently from the reported F-score ranking.
Why forest depth matters
The random forest comparisons vary both the number of trees and the maximum depth. A useful way to read them is to keep the size of the forest and the encoder fixed when assessing depth. For a 30-tree random forest with 1-gram TF-IDF, the accuracy is 0.7454 when depth is limited to 5. With no specified maximum depth the reported accuracy is 0.9375. Erotic recall moves from 0.3619 to 0.9016. The shallow forest misses a much larger share of the positive group in spite of producing erotic precision of 0.9361, compared with 0.9327 for the deeper setting.
The contrast is smaller with the dense representation. At 30 trees with Word2Vec in the 1-gram setting, the depth-5 forest reaches 0.9351 accuracy and the corresponding forest with no stated depth cap reaches 0.9482. Erotic recall is 0.8885 and 0.9125, respectively. The deeper forest still improves the score, while the shallow forest already works comparatively well with this representation.
Accuracy by encoder and depth limit for 30-tree random forests on Reddit
Removing the depth limit helps the count-based encoders most, while Word2Vec leads with either depth setting shown.
The numbers
| System or setting | accuracy |
|---|---|
| Bag of words 1-gram, depth 5 | 0.7365 |
| Bag of words 1-gram, no depth cap | 0.9218 |
| TF-IDF 1-gram, depth 5 | 0.7454 |
| TF-IDF 1-gram, no depth cap | 0.9375 |
| Word2Vec 1-gram, depth 5 | 0.9351 |
| Word2Vec 1-gram, no depth cap | 0.9482 |
| Word2Vec 2-gram, no depth cap (this paper) | 0.9493 |
The pattern is consistent with the representations providing different kinds of evidence to a tree. A split in a sparse lexical representation can access a particular feature, and a shallow tree has few successive splits available along any path. An embedding dimension combines contributions from many words. The result shows that the shallow forests worked better with those combined features on this dataset. The authors do not trace individual trees or inspect their splits to establish which features explain the performance gap.
Increasing the number of trees can also help, particularly when the depth cap is removed. With 1-gram TF-IDF and no maximum depth, accuracy is 0.8686 with 3 trees, 0.9221 with 10 and 0.9375 with 30. The pattern is less uniform for shallow trees across the representations. The strongest forest result in the paper comes from giving the forest both the largest tested tree count and the freedom to grow deeper, paired with the 2-gram Word2Vec representation.
Where adjacent pairs help
The authors observe that unigram and bigram results are frequently similar, with a small improvement in a number of the 2-gram settings. The winning linear SVM result provides an example with the classifier and TF-IDF weighting fixed. At C = 100, the 1-gram accuracy is 0.9584 and the 2-gram accuracy is 0.9712. The erotic F-score is 0.945 for the 1-gram setting and 0.9621 for the 2-gram setting.
Some of the clearest counterexamples occur with nearest neighbors and raw counts. At k = 3, bag of words gives 0.8211 accuracy for 1-grams and 0.7531 for 2-grams. Erotic recall is 0.6092 and 0.392, respectively. In a classifier that decides by proximity, features based on pairs can change both which examples overlap in vocabulary and which neighbors determine the prediction. The observed drop shows that the usefulness of adjacent pairs depends on how the representation is used.
The authors suggest that neighboring words can capture informal phrases and jargon that isolated counts miss. The improved configurations are consistent with that possibility. The experiment gives aggregate scores and does not identify which pairs drove particular classification decisions. It can show that changing the n-gram setting helps or hurts for a given configuration. It leaves open whether the improved settings recognized subject matter more reliably, picked up community-specific expressions, or benefited from both.
Limitations
Limits and open questions the authors identify
The authors describe their benchmark as a collection selected from public Reddit data and present the classifiers as a possible basis for filters. Their experimental evidence concerns text. The moderation problem that motivates the study also includes images, video and other material, which the text classifiers do not evaluate. The proposed use for minors or for readers setting their own preferences remains an application of the findings.
The authors identify deep learning and ensembles of classifiers as future directions. The systems evaluated here give a comparison among the conventional methods chosen for the study. A direct evaluation against deep learning on the same Reddit corpus would answer a separate question, even though the paper cites deep learning results for other kinds of inappropriate language. An ensemble could also combine the errors of different classifiers in a way that cannot be inferred from their aggregate scores alone.
The authors further propose studying feature reduction because of the high dimensionality of the representation space. A vocabulary-based encoder can create a coordinate for many different words or pairs. The frequency cutoff already limits some of those entries, while the paper leaves a dedicated comparison of dimensionality reduction techniques to future work. The existing experiment gives the behavior of the reported representations and learners with their selected settings.
Limits of the subreddit labels
The principal limitation visible in the setup is the origin of the target labels. The paper describes assigning classes through the communities selected for the collection. It does not report independent review of each item against a detailed definition of erotic content. A text from a source assigned to the erotic class can be routine or administrative. A source chosen for the neutral group can contain an item that discusses sex. Cross-validation treats the assigned category as the target even when such a case would receive a different judgment in individual review.
This has consequences for what the classifier can learn. The vocabulary of a community can reflect habitual subjects, genres and ways of writing. A strong prediction can come from recognizing those signals in the text, even though the feature extractor receives no subreddit identifier. This is compatible with genuine detection of erotic language. The two influences are hard to distinguish when the label also describes the community. The paper provides community counts, while the reported results give no breakdown of content-level errors within the different sources.
The distinction also affects the meaning of the word inappropriate. The operational categories are erotic and neutral according to the selected communities. A policy for particular readers would have to resolve how to handle a post that uses sexual vocabulary in an educational or health context, for example. The score for the paper’s task supplies no separate estimate for such judgments. The stated filtering application therefore depends on how a service would translate a content label into a decision for a reader.
Limits of the split and comparisons
The reported evaluation uses folds of the assembled corpus. A held-out-subreddit study would ask whether an encoder and classifier trained on some communities can identify similar subject matter in a new community with its own vocabulary. A chronological split would ask whether the same decisions hold later. A platform transfer test would ask whether the cues learned on Reddit carry over to another service. The paper’s corpus spans January and July across 2015–2018, but the reported fold design does not establish performance under those other tests.
The study gives the cross-validation procedure and the parameter choices. It leaves unclear whether the vocabulary, document frequencies and embeddings were fitted afresh on the training portion of each fold. A representation fitted on the full collection would have access to statistics from withheld documents even without their labels. The paper also reports the best settings from the cross-validation comparisons without identifying a separate nested selection process or final independent test. Those details affect how closely the best reported scores can be interpreted as estimates for a new corpus after tuning.
The main tables report values to several decimal places. They do not give fold-by-fold variation or uncertainty intervals that would establish whether the close ordering of the leading classifiers is stable. The broad performance contrasts, such as the random forest’s response to tree depth, can be seen directly in the detailed scores. The finer difference between the highest accuracies of the linear and RBF SVMs remains a difference in the reported estimates.
There is also a small inconsistency worth retaining when reading the F-score results. The main table lists 0.9614 as the best erotic F-score for the RBF SVM with TF-IDF, while the detailed RBF table contains a TF-IDF entry of 0.9622 for that metric. The main accuracy comparison and the authors’ discussion identify the linear SVM as the leading configuration. The published F-score entries leave the ordering of those two SVM variants on that particular metric less clear than the main table suggests.
Limits of the encoder and deployment evidence
The Word2Vec result measures a particular implementation of CBOW and a particular document representation. The paper gives a dimensionality, a context window, a sampling method and a training duration. It does not compare the effects of those choices or test alternatives such as Skip-Gram on the Reddit data. Its own random forest results already show that the standing of Word2Vec depends on the classifier. The finding in favor of TF-IDF therefore applies to the reported configurations and metrics, with a clear exception for the forests.
The preprocessing and n-gram comparisons leave related questions open. The paper reports using lowercasing, stop-word removal, lemmatization and other cleaning throughout the experiment. No controlled comparison isolates what any of those operations contributes. The scores also do not show which features the strongest classifier used most heavily, or which kinds of text account for its remaining false positives and false negatives. Such distinctions matter when a numerical gain is being interpreted as improved recognition of a type of language.
Finally, the class counts reflect the authors’ selection of communities. Precision concerns the proportion of correct decisions among items flagged in that evaluation. A mixed stream with a different prevalence of erotic items could produce a different precision even if the classifier retained similar behavior within each class. The paper gives accuracy, precision, recall and F-score on the benchmark. It does not test the effect of a decision threshold in a live stream or measure how readers and moderators would experience the resulting false alarms and missed items.
What came after
The citation record connects the study to later work on two different problems involving sensitive language. In 2024, a paper on classifying sensitive content in social media presented its contribution as a resource and evaluation. Its title places the inquiry at the broader level of sensitive-content classification. The connection to the Reddit study is the problem of deciding how content categories can be represented and evaluated in social media text. The citation establishes that the earlier experiment figures in that later work. It leaves the degree of reuse of the Reddit collection, the labels and the TF-IDF comparison unspecified. Sensitive Content Classification in Social Media: A Holistic Resource and Evaluation
In 2025, a paper on Polish erotic discourse described the creation and investigation of the forePLay annotated dataset. Its stated focus shares the earlier study’s interest in erotic text and places the construction of an annotated resource at the center of the work. The earlier paper evaluates how well classifiers can recover groups assigned from subreddit membership. The later title identifies a different language and a dataset devoted to discourse in that language. The citation alone leaves open how forePLay defines and annotates its categories or whether its investigation uses any of the earlier classifiers. Behind Closed Words: Creating and Investigating the forePLay Annotated Dataset for Polish Erotic Discourse
Cite
Cite as Gonzalo Molpeceres Barrientos, Rocío Alaiz-Rodríguez, Víctor González-Castro and Andrew C. Parnell. 2020. Machine Learning Techniques for the Detection of Inappropriate Erotic Content in Text. International Journal of Computational Intelligence Systems 13(1).
@article{barrientos2020machine,
title = {{Machine Learning Techniques for the Detection of Inappropriate Erotic Content in Text}},
author = {Gonzalo Molpeceres Barrientos, Rocío Alaiz-Rodríguez, Víctor González-Castro and Andrew C. Parnell},
journal = {International Journal of Computational Intelligence Systems 13(1)},
year = {2020},
doi = {10.2991/ijcis.d.200519.003},
url = {https://doi.org/10.2991/ijcis.d.200519.003}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/barrientos-2020-machine-learning-inappropriate-erotic-text/