![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
# Challenges of Detecting AI-Generated Text
We'll take an in-depth look at the challenges of detecting AI-generated text, and the effectiveness of the techniques used in practice.
[Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)
September 27, 202315 min read
![Photo by Houcine Ncib on Unsplash](../images/000.jpg)
Photo by [Houcine Ncib](https://unsplash.com/@houcinencibphotography?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)
Co-authored with [Naresh Singh](https://medium.com/@brocolishbroxoli).
* * *
## Table of contents
  1. [Introduction](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#86be)
  2. [Building an intuition for text source detection](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#64d4)
  3. [What is the perplexity of a language model?](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#542b)
  4. [Computing the perplexity of a language model's prediction](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#dc6a)
  5. [Detecting AI-generated text](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#f256)
  6. [Misinformation](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#b56a)
  7. [What's next?](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#a778)
  8. [Conclusion](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/#8446)


* * *
## Introduction
AI-assisted technologies for writing articles or posts are everywhere now! ChatGPT has unlocked numerous applications of language-based AI, and the use of AI for any kind of content generation has gone through the roof.
However, in school assignments such as creative writing, students are expected to create their own content. However, due to the popularity and effectiveness of AI for such tasks, they might be tempted to use it. In such cases, it is important for teachers to have access to reliable and trustworthy tools to detect AI-generated content.
This article aims to provide an intuition as well as the technical specification of building such a tool. It is intended for the readers who want to understand how AI detection works intuitively as well as the technical audience who wants to build such a tool.
Let's jump straight in!
* * *
## Building an intuition for text source detection
At a high level, we're trying to answer the question, _"How likely is it that an AI language model such as GPT-3 has generated all or part of this text?"_
If you step back, you will realize this is a typical daily scenario. For example, how likely would it be for your mother to say the following sentence to you?
  1. Dear, please go to bed before 8:00 pm.
  2. Dear, please go to bed after 11:00 pm.


We would guess that the former is much more likely than the latter because you have built an understanding of the world around you and have a sense of which events are more likely to occur.
This is exactly how a language model works. Language models learn something about the world around them, specifically language. They learn to predict the next token or word given an incomplete sentence.
In the example above, if you're told that your mother is saying something, and what has been said so far is _"Dear, please go to bed"_ , then the most likely continuation of the sentence is going to be "before 8:00 pm", and not "after 11:00 pm". In technical terms, we say that you'd be more _perplexed_ to hear the 2nd sentence as opposed to the 1st one.
Let's dig deeper into what perplexity means in the context of a language mode.
* * *
## What is the perplexity of a language model?
According to [dictionary.com](https://www.dictionary.com/browse/perplexity), perplexity is defined as
> the state of being perplexed; confusion; uncertainty.
In the real world, if you encounter a situation that you don't expect, you will be more perplexed than if you encounter a situation that you expect. For example, when driving on a road, if you see a traffic light, then you're less likely to be perplexed as opposed to if you see a goat crossing the street.
Similarly, for a language model that is trying to predict the next word in a sentence, we say that the model will perplex us if it completes the sentence using a word that we don't expect v/s if it uses a word that we expect. Some examples.
**Sentences with a low perplexity would look like the following**
  1. It's a sunny day outside.
  2. I'm sorry I missed the flight and was unable to reach the national park in time.


**Sentences with a high perplexity would look like the following**
  1. It's a bread day outside.
  2. I'm convenient missed light outside and could not reach national park.


Next, let's look at how we can compute the perplexity of a prediction made by the language model.
* * *
## Computing the perplexity of a language model's prediction
The perplexity of a language model is related to the probability of being able to unsurprisingly predict the next token (word) of a sentence.
Suppose we train a language model with a vocabulary of 6600 tokens and run a single prediction step to have the model predict the next token in a sentence. Let's assume that the likelihood of picking this token is 5/6600 (i.e., this token was not very likely). Its perplexity is the inverse of the probability which is 6600/5 = 1320, which suggests that _we are highly perplexed_ by this suggestion. If the likelihood of picking this token was 6000/6600 instead, then the perplexity would be 6600/6000 = 1.1 which suggests that we are just slightly perplexed by this suggestion.
Hence, the perplexity of our model on a more likely prediction is lower than the perplexity of our model on a less likely prediction.
The perplexity of predicting all tokens in a sentence "x" is formally defined as the Nth root of the inverse of the product of the token probabilities.
![](../images/body-8bb7b360dbe5a0a3cb0a.png)
However, to ensure numerical stability, we can define it in terms of the log function.
![](../images/body-6a3a1a70245d44f8fcfe.png)
Which is e (2.71828) to the power of the average negative log-likelihood of the predicted token being the ground truth token.
### Training and validation perplexity
The model's training and validation perplexity can be computed directly from the batch or epoch loss.
### Prediction perplexity
One can't compute the prediction perplexity since it requires having a set of ground truth labels for each prediction.
### PyTorch code to compute perplexity
Let's assume that the variable _probs_ is a _torch.Tensor_ of shape _(sequence _length,)_ , which contains the probability of the ground-truth token being predicted by the language model at that position in the sequence.
The per-token perplexity can be computed using this code.
python

```
token_perplexity = (probs.log() * -1.0).exp()
print(f"Token Perplexity: {token_perplexity}")
```

The sample perplexity can be computed using this code.
python

```
# The perplexity is e^(average NLL).
sentence_perplexity = (probs.log() * -1.0).mean().exp().item()
print(f"Sentence Perplexity: {sentence_perplexity:.2f}")
```

Next, let's look at the code that computes this per-token probability given a sentence.
python

```
def get_pointwise_loss(self, inputs: List[str], tok):
    self.model.eval()
    all_probs = []
    with torch.inference_mode():
        for input in inputs:
            ids_list: List[int] = tok.encode(input).ids
            # ids has shape (1, len(ids_list))
            ids: Torch.Tensor = torch.tensor(ids_list, device=self.device).unsqueeze(0)

            # probs below is the probability that the token at that location
            # completes the sentence (in ids) so far.
            y = self.model(ids)
            criterion = nn.CrossEntropyLoss(reduction='none', ignore_index=0)

            # Compute the loss starting from the 2nd token in the model's output.
            loss = criterion(y[:,:,:-1], ids[:,1:])

            # To compute the probability of each token, we need to compute the
            # negative of the log loss and exponentiate it.
            loss = loss * -1.0

            # Set the probabilities that we are not interested in to -inf.
            # This is done to make the softmax set these values to 0.0
            loss[loss == 0.0] = float("-inf")

            # probs holds the probability of each token's prediction
            # starting from the 2nd token since we don't want to include
            # the probability of the model predicting the beginning of
            # a sentence given no existing sentence context.
            #
            # To compute perplexity, we should probably ignore the first
            # handful of predictions of the model since there's insufficient
            # context. We don't do that here, though.
            probs = loss.exp()
            all_probs.append(probs)
        #
    #
    return all_probs
#
```

Now that we know something about how language models function, and how we can compute the per-token as well as per-sentence perplexity, let's try to tie it all together and take a look at how one can leverage this information to build a tool that can detect if some text was AI-generated.
* * *
## Detecting AI-generated text
We have all the ingredients we need to check if a piece of text is AI-generated. Here's everything we need:
  1. The text (sentence or paragraph) we wish to check.
  2. The tokenized version of this text, tokenized using the tokenizer that was used to tokenize the training dataset for this model.
  3. The trained language model.


Using 1, 2, and 3 above, we can compute the following:
  1. Per-token probability as predicted by the model.
  2. Per-token perplexity using the per-token probability.
  3. Total perplexity for the entire sentence.
  4. The perplexity of the model on the training dataset.


To check if a text is AI-generated, we need to compare the sentence perplexity with the model's perplexity scaled by a fudge-factor, alpha. If the sentence perplexity is more than the model's perplexity with scaling, then it's probably human-written text (i.e. not AI-generated). Otherwise, it's probably AI-generated. The reason for this is that we expect the model to not be perplexed by text it would generate itself, so if it encounters some text that it itself would not generate, then there's reason to believe that the text isn't AI-generated. If the perplexity of the sentence is less than or equal to the model's training perplexity with scaling, then it's likely that it was generated using this language model, but we can't be very sure. This is because it's possible for a human to have written that text, and it just happens to be something that the model could also have generated. After all, the model was trained on a lot of human-written text so in some sense, the model represents an "average human's writing".
![](../images/body-3f4370b442986b41530b.png)
_ppx(x)_ in the formula above means the perplexity of the input "x".
Next, let's take a look at examples of human-written v/s AI-generated text.
### Examples of AI-generated v/s human written text
We've written some Python code that colors each token in a sentence based on its perplexity relative to the model's perplexity. The first token is always coloured black if we don't consider its perplexity. Tokens that have a perplexity that is less than or equal to the model's perplexity with scaling are coloured red, indicating that they may be AI-generated, whereas the tokens with higher perplexity are coloured green, indicating that they were definitely not AI-generated.
![](../images/body-4f08f34f38a11efd3848.png)
The numbers in the square brackets before the sentence indicate the perplexity of the sentence as computed using the language model. Note that some words are part red and part blue. This is due to the fact that we used a subword tokenizer.
Here's the code that generates the HTML above.
python

```
def get_html_for_token_perplexity(tok, sentence, tok_ppx, model_ppx):
    tokens = tok.encode(sentence).tokens
    ids = tok.encode(sentence).ids
    cleaned_tokens = []
    for word in tokens:
        m = list(map(ord, word))
        m = list(map(lambda x: x if x != 288 else ord(' '), m))
        m = list(map(chr, m))
        m = ''.join(m)
        cleaned_tokens.append(m)
    #
    html = [
        f"<span>{cleaned_tokens[0]}</span>",
    ]
    for ct, ppx in zip(cleaned_tokens[1:], tok_ppx):
        color = "black"
        if ppx.item() >= 0:
            if ppx.item() <= model_ppx * 1.1:
                color = "red"
            else:
                color = "green"
            #
        #
        html.append(f"<span style='color:{color};'>{ct}</span>")
    #
    return "".join(html)
#
```

As we can see from the examples above, if a model detects some text as human-generated, it's definitely human-generated, but if it detects the text as AI-generated, there's a chance that it's not AI-generated. So why does this happen? Let's take a look next!
### False positives
Our language model is trained on a LOT of text written by humans. It's generally hard to detect if something was written (digitally) by a specific person. The model's inputs for training comprise many, many different styles of writing, likely written by a large number of people. This causes the model to learn many different writing styles and content. It's very likely that your writing style very closely matches the writing style of some text the model was trained on. This is the result of false positives and why the model can't be sure that some text is AI-generated. However, the model can be sure that some text was human-generated.
**OpenAI:** OpenAI recently announced that it would discontinue its tools for detecting AI-generated text, citing a low accuracy rate (Source: [Hindustan Times](https://tech.hindustantimes.com/tech/news/openai-kills-off-its-own-ai-text-detection-tool-shocking-reason-behind-it-71690364760759.html)).
> The original version of the AI classifier tool had certain limitations and inaccuracies from the outset. Users were required to input at least 1,000 characters of text manually, which OpenAI then analyzed to classify as either AI or human-written. Unfortunately, the tool's performance fell short, as it properly identified only 26 percent of AI-generated content and mistakenly labeled human-written text as AI about 9 percent of the time.
Here's the [blog post from OpenAI](https://openai.com/blog/new-ai-classifier-for-indicating-ai-written-text). It seems like they used a different approach compared to the one mentioned in this article.
> Our classifier is a language model fine-tuned on a dataset of pairs of human-written text and AI-written text on the same topic. We collected this dataset from a variety of sources that we believe to be written by humans, such as the pretraining data and human demonstrations on prompts submitted to InstructGPT. We divided each text into a prompt and a response. On these prompts, we generated responses from a variety of different language models trained by us and other organizations. For our web app, we adjust the confidence threshold to keep the false positive rate low; in other words, we only mark text as likely AI-written if the classifier is very confident.
[**GPTZero**](https://gptzero.me/)**:** Another popular AI-generated text detection tool is GPTZero. It seems like GPTZero uses [perplexity and burstiness](https://ecoagi.ai/topics/ChatGPT/high-perplexity-score-gpt-zero) to detect AI-generated text. _"Burstiness refers to the phenomenon where certain words or phrases appear in bursts within a text. In other words if a word appears once in a text, it's likely to appear again in close proximity"_ ([source](https://ecoagi.ai/topics/ChatGPT/high-perplexity-score-gpt-zero)).
GPTZero claims to have a very high success rate. According to the [GPTZero FAQ](https://gptzero.me/faq), _"At a threshold of 0.88, 85% of AI documents are classified as AI, and 99% of human documents are classified as human."_
### The generality of this approach
The approach mentioned in this article doesn't generalize well. What we mean by this is that if you have 3 language models, for example, GPT3, GPT3.5, and GPT4, then you must run the input text through all the 3 models and check perplexity on all of them to see if the text was generated by any one of them. This is because each model generates text slightly differently, and they all need to independently evaluate text to see if any of them may have generated the text.
With the proliferation of large language models in the world as of August 2023, it seems unlikely that one can check any piece of text as having originated from any of the language models in the world.
In fact, new models are being trained every day, and trying to keep up with this rapid progress seems hard at best.
The example below shows the result of asking our model to predict if the sentences generated by ChatGPT are AI-generated or not. As you can see, the results are mixed.
![The sentences in the purple box are correctly identified as AI-generated by our model, whereas the rest are incorrectly identified as human written.](../images/001.png)
The sentences in the purple box are correctly identified as AI-generated by our model, whereas the rest are incorrectly identified as human written.
There are many reasons why this may happen.
  1. **Train corpus size:** Our model is trained on very little text, whereas ChatGPT was trained on terabytes of text.
  2. **Data distribution:** Our model is trained on a different data distribution as compared to ChatGPT.
  3. **Fine-tuning:** Our model is just a GPT model, whereas ChatGPT was fine-tuned for chat-like responses, making it generate text in a slightly different tone. If you had a model that generates legal text or medical advice, then our model would perform poorly on text generated by those models as well.
  4. **Model size:** Our model is very small (less than 100M parameters compared to > 200B parameters for ChatGPT-like models).


It's clear that we need a better approach if we hope to provide a reasonably high-quality result to check if any text is AI-generated.
Next, let's take a look at some misinformation about this topic circulating around the internet.
* * *
## Misinformation
Some articles interpret perplexity incorrectly. For example, if you search google.com for ["does human written content have high or low perplexity?"](https://www.google.com/search?q=does+human+written+content+have+high+or+low+perplexity%3F), you'll get the [following result](https://www.linkedin.com/pulse/how-write-content-using-chatgpt-outsmarts-ai-tools-99-dasun-sucharith/) in the first position.
![](../images/body-38b02c0cdd692c790679.png)
This is incorrect since human-written content typically has higher perplexity compared with AI-generated content.
Let's take a look at techniques that researchers in this area are exploring to do better than where we are.
* * *
## What's next?
We've established that detecting AI-generated text is a hard problem, and that success rates are so low that they aren't any better than guessing. Let's look at what state of the art techniques researchers in this area are exploring to get a better handle on things.
**Watermarking:** [OpenAI and Google have promised to watermark AI generated text](https://arstechnica.com/ai/2023/07/openai-google-will-watermark-ai-generated-content-to-hinder-deepfakes-misinfo/) so that it's possible to identify it programmatically.
The technical details of how this watermark might work are unclear and neither company has disclosed any details related to it.
Even if OpenAI and Google adopt a watermarking technique, we can't be certain that every language model that is deployed out there will have a watermark included. It would still be possible for people to deploy their own models to generate text and put it out there in the wild. Even if companies decide to watermark generated text, it's not clear if this will be a standard or if every company will have their own proprietary strategy and potentially paid tool to check if any text was generated using their AI-based text-generation tools. If it's an open standard there's a chance that people will be able to work around it unless it's something like a cryptographic cipher that requires a ton of computation to undo. If it's not an open standard, then people will be at the mercy of these companies to provide open and free access to the tools and APIs needed to perform these checks. There's also the question of how effective these will be in the long run since it may even be possible to train models to ingest the AI-generated text with a watermark, and return AI-generated text without a watermark.
[This article](https://www.nytimes.com/interactive/2023/02/17/business/ai-text-detection.html) discusses a possible technique for adding a watermark for AI-generated text, and mentions the significant challenges with the approach.
**Personalization:** In our opinion, this problem of detecting AI-generated text is going to remain challenging in the near term. We believe that strategies will need to get more intrusive and personalized to be more effective. For example, instead of asking if some text is AI-generated it may be more reasonable to ask if this text was written by a specific person. However, this would require the system to have access to large amounts of text written by that specific person. Additionally, the problem becomes more complex if something was written by more than one person, such as this article.
Let's look at the impact such a personalized system for detecting human-written text would have on educators and students.
If such a solution existed, **educators** would be more inclined to hand out individual assignments to students instead of group assignments. This would also require every student to first provide a large amount of text that they themselves have written. This could mean spending several hours in-person at a university before enrolling for classes. Surely, this would have a negative effect on the ability to teach students the importance of working together as a team to accomplish a common goal.
On the other hand, having access to AI-based text generation could free students in some cases to focus on the actual problem at hand such as performing the research or literature study instead of spending time writing out their learnings in a polished manner. One can imagine that students will end up spending more of their time learning concepts and techniques in math or science class as opposed to writing about it. That part can be taken care of by the AI.
* * *
## Conclusion
In this article, we built intuition around how one can detect AI-generated text. The main metric we can use is the perplexity of the generated text. We saw some PyTorch code to check if a given text may be AI-generated using the perplexity of that text. We also saw some of the drawbacks of this approach, including the possibility of false positives. We hope this helps you understand and appreciate the nitty-gritty details behind detecting AI-generated text.
This is a constantly evolving space and researchers are trying hard to figure out a way to detect AI-generated text with higher accuracy. The impact of this technology to our lives promises to be significant, and in many ways unknown.
While we discussed the techniques for detecting AI-generated text, we assumed that the entire text is either human-written or AI-generated. In practice, text tends to be partially human-written and partially AI-generated, and this complicates things considerably.
If you want to read about additional approaches to detect AI-generated text, such as the use of the burstiness metric, you can read about them [here](https://towardsdatascience.com/how-do-we-know-if-a-text-is-ai-generated-82e710ea7b51).
All the images in this article (except for the first one) were created by the author(s).
## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-a3403563a948ce1eab7b.jpeg)
Written By
## [Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)
[See all from Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)
[Getting Started](https://towardsdatascience.com/tag/getting-started/)[Gptzero](https://towardsdatascience.com/tag/gptzero/)[Language Model](https://towardsdatascience.com/tag/language-model/)[Llm](https://towardsdatascience.com/tag/llm/)[Perplexity](https://towardsdatascience.com/tag/perplexity/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fchallenges-of-detecting-ai-generated-text-6d85bf779448%2F&title=Challenges%20of%20Detecting%20AI-Generated%20Text)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fchallenges-of-detecting-ai-generated-text-6d85bf779448%2F&title=Challenges%20of%20Detecting%20AI-Generated%20Text)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fchallenges-of-detecting-ai-generated-text-6d85bf779448%2F&text=Challenges%20of%20Detecting%20AI-Generated%20Text)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/002.png)](https://towardsdatascience.com/building-fill-sg-genai-report-toolkit-launch-afc8dfdacd78/)
## [Building Fill.sg, a GenAI Report Toolkit](https://towardsdatascience.com/building-fill-sg-genai-report-toolkit-launch-afc8dfdacd78/)
[](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/)
FulFILL your dreams of having AI write repetitive reports for you. Find out how we built Fill.sg in 2 weeks at LAUNCH!
[Nicole Ren](https://towardsdatascience.com/author/nicole-ren/)
June 24, 202414 min read
  * [![](../images/003.jpg)](https://towardsdatascience.com/recursive-language-models-one-example-deep-dive-that-explains-everything/)
## [Recursive Language Models: An All-in-One Deep Dive](https://towardsdatascience.com/recursive-language-models-one-example-deep-dive-that-explains-everything/)
[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)
Exactly how does it differ from ReAct, CodeAct, Self-Loops, and Subagents?
[Avishek Biswas](https://towardsdatascience.com/author/neural.avb/)
May 16, 202619 min read
  * [![](../images/004.jpg)](https://towardsdatascience.com/spatial-distance-and-machine-learning-2cab72fc6284/)
## [Spatial Distance and Machine Learning](https://towardsdatascience.com/spatial-distance-and-machine-learning-2cab72fc6284/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Distance Metrics and Feature Engineering Using Longitude and Latitude Data
[TheDataProf](https://towardsdatascience.com/author/francisadrianviernes/)
December 18, 202010 min read
  * [![](../images/005.jpg)](https://towardsdatascience.com/use-tablib-to-handle-simple-tabular-data-in-python-fa9e6f0af37f/)
## [Use Tablib to Handle Simple Tabular Data in Python](https://towardsdatascience.com/use-tablib-to-handle-simple-tabular-data-in-python-fa9e6f0af37f/)
[](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/)
Sometimes a Shallow Abstraction is more Valuable than Performance
[Eirik Berge](https://towardsdatascience.com/author/ebbeberge/)
November 27, 202412 min read
  * [![](../images/006.png)](https://towardsdatascience.com/rag-explained-understanding-embeddings-similarity-and-retrieval/)
## [RAG Explained: Understanding Embeddings, Similarity, and Retrieval](https://towardsdatascience.com/rag-explained-understanding-embeddings-similarity-and-retrieval/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Let's take a closer look at how the retrieval mechanism works
[Maria Mouschoutzi](https://towardsdatascience.com/author/m.mouschoutzi/)
September 17, 202510 min read
  * [![](../images/007.jpeg)](https://towardsdatascience.com/how-xticks-and-xticklabels-really-work-a-walkthrough-aff80755838/)
## [How xticks and xticklabels Really Work: a Walkthrough](https://towardsdatascience.com/how-xticks-and-xticklabels-really-work-a-walkthrough-aff80755838/)
[](https://towardsdatascience.com/challenges-of-detecting-ai-generated-text-6d85bf779448/)
I was recently creating visualizations in Seaborn, which is based on Matplotlib, and when labeling the x-axis, I wasn't getting the results...
[Henry Alpert](https://towardsdatascience.com/author/halpert3/)
August 17, 20214 min read
  * [![](../images/008.jpeg)](https://towardsdatascience.com/a-b-testing-a-complete-guide-to-statistical-testing-e3f1db140499/)
## [A/B Testing - A complete guide to statistical testing](https://towardsdatascience.com/a-b-testing-a-complete-guide-to-statistical-testing-e3f1db140499/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Optimizing web marketing strategies through statistical testing
[Francesco Casalegno](https://towardsdatascience.com/author/francesco.casalegno/)
February 17, 20219 min read
  * [![](../images/009.png)](https://towardsdatascience.com/how-to-design-my-first-ai-agent/)
## [How to Design My First AI Agent](https://towardsdatascience.com/how-to-design-my-first-ai-agent/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
The foundations of designing an AI agent
[Fabiana Clemente](https://towardsdatascience.com/author/fabiana_clemente/)
June 3, 20258 min read
  * [![](../images/010.jpg)](https://towardsdatascience.com/how-to-create-powerful-llm-applications-with-context-engineering/)
## [How to Create Powerful LLM Applications with Context Engineering](https://towardsdatascience.com/how-to-create-powerful-llm-applications-with-context-engineering/)
[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)
Improve your LLM by optimizing its context
[Eivind Kjosbakken](https://towardsdatascience.com/author/oieivind/)
August 18, 20257 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ "Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ "The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ "Does Your Company Have a Data Strategy?")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ "Productivity Tips, Data Career Insights, and Other Recent Must-Reads")


