1 of 53

Making GPT Your RA

A guide to using GPT to classify free text

2 of 53

You’ve probably played around with ChatGPT

The Problem

3 of 53

Why we worry about large language models (LLMs):

They do weird things.

​

They are bizarrely overconfident.

1

2

The Challenge

4 of 53

On the other hand…

People also do weird things.

​

We have tools to understand and improve performance.

1

2

The Challenge

5 of 53

We wanted to collapse 60,000 free-text documents into a single categorical variable.

​

​

Here is how we did it with generative AI.

6 of 53

Overview of Technical Steps

How to Get Results:

• How GPTs work�• How to use the OpenAI API?

• How to parallelize code?�• How to navigate rate limits?

​

How to Get Good Results

• Prompt engineering�• Evaluating performance on labeled data

How to Even Better Results:

• Actor-critic

• Output token probabilities

7 of 53

Example of a

Classification Problem

8 of 53

​

How many clinical drug trials �enroll pregnant participants?

​

​

This is deceptively hard to answer.

​

​

9 of 53

Data Source: ClinicalTrials.gov

  • No field related to pregnant inclusion
  • Pregnant inclusion may be discerned from:
    • Title
    • Summary
    • Combined inclusion/

exclusion criteria

  • Fields are unstructured text

​

Database of clinical drug trials

A Sample Classification Problem

10 of 53

Data Source: ClinicalTrials.gov

​

  • Title: “Medication Treatment for Opioid Use Disorder in Expectant Mothers: Conceptual Model Assessments Sub-study (MOMs-CMA)” (NCT03911466)
  • Inclusion/Exclusion: combined field (NCT01635621)

Examples

​

A Sample Classification Problem

11 of 53

Approaches to classification

  1. Manual labeling – We labeled 947, but there were about 60,000 we wanted to classify, which made this unappealing.
  2. Text mining – Using R to pick out keywords and phrases. But this proved really tricky, given the unstructured text.
  3. GPT – Using OpenAI API to classify pregnant inclusion. What we will talk about in this document.

​

A Sample Classification Problem

12 of 53

How to Get Results

Setup

13 of 53

​

Brown University DSI workshops are held on

​

_______.

​

14 of 53

​

Brown University DSI workshops are held on

​

_______.

​

X

​

^

​

Y

15 of 53

Generative Pre-trained Transformers

The Problem

16 of 53

ChatGPT is not designed for this.

It may give you (bad) Python text mining code…

​

Setup

…or a result (as you feed it entries 1-by-1).

17 of 53

So we used the API.

  • Can iterate through a .csv file
  • Found at platform.openai.com

Setup

OpenAI’s API can be used to process large datasets

18 of 53

To use OpenAI’s API, we need:

  • API key – a unique string so only you can use your budget

​

  • Budget – each call to the API costs money.

​

  • Code (and input data) – Python code to tell GPT what to do with input data

​

Setup

19 of 53

To use OpenAI’s API, we need:

​

​

Setup

API key

​

20 of 53

To use OpenAI’s API, we need:

​

  • Present cost for GPT-4o is:
    • $5/1m input tokens~ 1 cent/1500 words.
    • $15/1m output tokens

https://openai.com/api/pricing/

  • Tokens go shockingly quickly.

​

Setup

Budget

​

21 of 53

To use OpenAI’s API, we need:

​

  • We need to write code to tell the API what to do.
    • API can take Python, Julia, R, etc. We used Python.

​

  • We also need the raw data for it to process.
  • Some references from OpenAI that can help:

Setup

Code (and input data)

​

22 of 53

Writing Python code

​

  • We used Jupyter Notebook.
    • https://jupyter.org/install

​

​

Coding Instructions in Python

We coded in Python

Open up your favorite Python editor

​

23 of 53

Writing Python code

​

​

​

​

​

  • These three installs only need to be completed once.

Coding Instructions in Python

Install the OpenAI Python Library

​

24 of 53

Writing Python code

  • In the next slides, we explain it chunk by chunk.
  • To use it, open the .ipynb file as a Jupyter notebook.

​

Coding Instructions in Python

Here are our code and data

​

Other code options: Python (.py), R code

​

25 of 53

0) Install useful libraries

  • This gets written at the top of your Jupyter notebook.

​

Coding Instructions in Python

These are the �libraries we used

​

26 of 53

Next: Call the API with Python

  1. Read in data. �For us, this was the .csv of trials from ClinicalTrials.gov.
  2. For each observation,
    1. Call the API, asking it it complete classification task based on specific inputs
    2. Extract relevant info from output
    3. Track progress & catch errors
  3. Loop over data.

Coding Instructions in Python

General idea

​

27 of 53

  1. Reading in the data

Coding Instructions in Python

28 of 53

2a) Calling the API

This is further down in the sample file – we’ll explain the intervening lines in a minute

Coding Instructions in Python

model: Which LLM you use (https://platform.openai.com/docs/models)

29 of 53

2a) Calling the API

Coding Instructions in Python

response_format: Determines how output is returned

30 of 53

2a) Calling the API

Coding Instructions in Python

temperature: Determines randomness in responses (ranges from 0-1, 0 is close to deterministic/reproducible)

31 of 53

2a) Calling the API

Coding Instructions in Python

prompt: What you want the GPT to do! We asked it to classify study types. We will get into this more in a moment!

32 of 53

2a) Calling the API

Coding Instructions in Python

input_data: Information on a specific item to analyze. We fed in data from a randomized drug trial on ClinicalTrials.gov.

33 of 53

2b) Extract the useful output

Coding Instructions in Python

response: There’s a lot of information in the response (“completion”) object. The above code gives you the main output, but here is a full example object from OpenAI’s API: https://platform.openai.com/docs/guides/text-generation/chat-completions-api)

34 of 53

2c) Put together + catch errors & track progress

Coding Instructions in Python

35 of 53

3) Loop over data

  • Loop over each item we want to classify.
    • In our example, each clinical trial

​

​

  • Since each API call is not memory intensive on your local machine, we use threading, which allows for many simultaneous API calls.
    • Multiprocessing runs one job per computer core.

So if your computer has 16 cores, you’d be limited to 16 simultaneous calls. With threading, you can do hundreds.

​

Parallelization

Put this API call in a loop

​

Parallelize for speed

​

36 of 53

3) Loop over data

Parallelization

37 of 53

3) Loop over data (w. rate limits)

Rate limits

API subscriptions have rate limits: https://platform.openai.com/�docs/guides/rate-limits.

​

We used a function that paused jobs if total token usage per minute exceeded a user-specified threshold, based on current account rate limits. You can adapt as needed.

38 of 53

How to Get Good Results

Training & validation

39 of 53

Training your GPT RA

  1. Prompt engineering – Telling your GPT RA what to do

​

  • Check on a training set – Use a set of manually-labeled examples

​

  • Evaluation – Reporting what went well and what didn’t on a clean validation set

Training

We break this into 3 steps

​

40 of 53

  1. Prompt engineering
  • Take ≈25-50 observations and tell GPT what to do and to justify its decision.

  • Review, and see where it’s getting things wrong. Update your instructions.�
  • Rinse & repeat.

Training

Iterate on your instructions

​

41 of 53

  • Prompt engineering

​

Note that we ask GPT to explain itself in two ways:

  • Variable (iii) gives the reason for the classification.
  • Variable (iv) gives a quote from the text it analyzed to support the decision.

Training

Our first attempt at instructions

​

42 of 53

  • Prompt engineering

​

Judgement call:

​

​

Hallucination:

​

​

Training

These variables help identify judgement calls & hallucinations

​

43 of 53

  • Prompt engineering

​

Training

Our next set of instructions

​

44 of 53

2) Check on a training set

  • Run code on a dataset with labeled “ground truth” available.
    • Check how your GPT RA is doing at a larger scale.
  • Choose sample size based on error tolerance.
    • We chose ~1000.
    • We oversampled rare outcomes (pregnant inclusion) to check/evaluate performance on these types.
  • Review errors and update prompt.

​

Training

Give your GPT RA some labeled data

​

45 of 53

2) Check on a training set

  • Accuracy: % correctly labeled
  • For binary classifications (link):
    • Sensitivity: % labeled correctly, given “true positive” status
    • Specificity: % labeled correctly, given “true negative” status
    • Positive predictive value (PPV): % labeled correctly, given “positive” classification
    • Negative predictive value (NPV): % labeled correctly, given “negative” classification

​

Training

Consider several measures of good classification

46 of 53

Validation set

  • After training, run prompt on a new random sample of data.
  • Our evaluation found that our process achieved:
    • 98.2% accuracy
    • 98.5% “included” predictive value (PV)
    • 98% “excluded” PV
    • 99% “unspecified” PV
  • Report validation performance metrics in your paper/appendix. We want transparency and accuracy in this field!

Validation

Give your GPT RA a report card

​

47 of 53

How to Refine Results

Improving results

48 of 53

Actor-Critic

In our example, GPT sometimes provided the right answer in the justification but the wrong classification. We explored two methods for addressing this.

​

First, we added an additional field to our prompt.

Actor-Critic

GPT can sometimes recognize its own errors

​

49 of 53

Actor-Critic

Next, we ran an entirely new set of API calls with a new prompt to help address a specific error (marking Unspecified as Excluded).

Actor-Critic

GPT can sometimes recognize its own errors

​

50 of 53

Actor-Critic

Both methods reduced errors, the second by ~50% in training data!

​

Original:

​

​

Critic:

Actor-Critic

GPT can sometimes recognize its own errors

​

51 of 53

Output token probabilities

Output token probabilities

You can also look under the hood at output token probabilities.

Need low-dimensional output

​

In our case, GPT was overconfident… nevertheless, reviewing observations with the lowest 6% of class probabilities could catch 50% of errors.

52 of 53

Good Luck!

Use this tool (and guide) for good please :-)

53 of 53

Feedback? Questions?

​

Alyssa Bilinski: alyssa_bilinski@brown.edu

Natalia Emanuel: natalia@nataliaemanuel.com

Ozair Ali: ozair@ekai.ai