Graffiti is a hot topic at Reed right now. As it has been in the past. Is it a form of artistic expression that is part of Reed culture and should go on unfettered? Or should we ban graffiti in certain areas, or all together, because of hate speech?


To find out what students think, other students put up posters around campus with a survey soliciting comments. You can still fill out the survey!
This presents us with a problem that is common in a lot of fields: how do we analyze responses that are entirely text? This post will walk you through a couple common ways to get a general sense of the feelings of responders.
One way we display that outcome is with a word cloud, but this cloud is not based solely on counting up the frequency of words. There’s a bit of natural language processing and machine learning along the way, so follow along to see how this is done. This project is on the DataLab GitHub page, along with all the other projects on this blog.
The data
The data comes from a survey that has two questions: 1) “What do you think about campus graffiti?” and 2) “What is your role on campus?”. Only students have answered the survey so far, so that reduces our complexity a little. The answers to the first question range from just a few words to several paragraphs. At the time of writing the article, there were 41 responses. With that small a number, the DataLab was able to go through and hand-score the data. We’ll compare these human consensus scores to the output of our models.
For scoring, we went with what is the overall sentiment of the comment towards graffiti—pro or anti. The scores range from -2 for all bad, -1 more bad than good, 0 neutral or equal bad and good, 1 more good than bad, and 2 all good. There was nothing on the form indicating that the actual survey content would be widely shared, so the responses themselves are not on the GitHub, but you could make up some responses if you wanted to follow along.
Getting the data into Python
Python has an extensive machine learning (ML) library system, so I chose Python for this project. (R also has some good packages that would have been totally suitable for this, but Python is the leader here, and we haven’t done a Python project yet.)
We only have one column of data and it will just be considered as plain text, so there’s no need to coerce it to be a data frame (spreadsheet) type object; we’ll just work with it as lines of code. We start that out with loading the csv, reading it in line by line, cleaning up things that will mess us up like weird quote (“) marks, and making sure all the characters are standardized. This helps with things like accent marks, which can throw off matching. We don’t have any in this data, but still good to do.
#### Read in ------------------------------------
# each row becomes a dictionary: {column name: value}
with open("graffiti/graffiti_response.csv", newline="", encoding="utf-8-sig") as file:
responses = list(csv.DictReader(file))
#### Clean text ------------------------------------
# curly quotes -> straight quotes, so "it’s" and "it's" count as the same word
STRAIGHT_QUOTES = str.maketrans({"’": "'", "‘": "'", "“": '"', "”": '"'})
# Standardize characters and spacing without changing any words
def clean_text(text):
text = unicodedata.normalize("NFKC", text) # fix lookalike characters
text = text.translate(STRAIGHT_QUOTES)
return " ".join(text.split()) # remove line breaks and extra spaces
# keep the original text and add the cleaned version next to it
for row_id, row in enumerate(responses, start=1):
row["id"] = row_id
row["clean"] = clean_text(row["response"])
# drop blank responses (after numbering, so ids still match the sheet's order)
responses = [row for row in responses if row["clean"]]
Python dictionaries have keys and values. Keys are unique and each one can have a list of values that correspond to it. Rather than overwrite the original data, I put the clean responses in a new value in the dictionary, so the row ID is the key and the content and cleaned up content are values.
Then I just wanted to make sure my cleaning didn’t drop anything, so I checked that the length of the original content and the cleaned content was the same.
#### Check ------------------------------------
changed_counts = [
row["id"] for row in responses
if len(row["response"].split()) != len(row["clean"].split())
]
# should equal 0 if cleaning worked without deleting stuff
print(f"ids where the word count changed: {changed_counts}")
Sentiment Analysis
Sentiment analysis is a way to analyze text to assess the tone of the response. It usually classifies things as positive, negative, or neutral and assigns them a score. There are a number of ways to do sentiment analysis, and we did a couple here to demonstrate. The first uses VADER and second uses a pre-trained BART model to analyze themes.
Sentiment with VADER
VADER stands for Valence Aware Dictionary and sEntiment Reasoner (gotta love the desire to just go for a jokey name, letters be damned). It’s a rule-based sentiment analysis tool that contains a lexicon of around 7,500 words and phrases each of which has a sentiment score based on polarity (positive or negative) and intensity (strength of emotion). Words get a score from -4 to 4 where “good” is 1.9, “great” is 3.1, and “horrible” is –2.5. VADER is also based on posts from social media, so it is good at understanding slang and the way people actually write, for example “sucks” and “sux” are both -1.5. Words that aren’t in the dictionary or don’t convey sentiment get a 0.
Within our script, VADER will work by finding the word score and adjusting it based on nearby words and formatting. Words like “very” will boost the score of a word. Negations like “not” reverse polarity and weaken strength. There are more rules for exclamation points, caps lock, emojis, and more. You can look it up. Once VADER scores every word it adds up the scores and normalizes them to be on a -1 to 1 scale.
For this analysis, we ran VADER’s SentimentIntensityAnalyzer() on each person’s response to get a single compound score for each individual. Based on the score each response was labeled as positive (>0.05), negative (<-0.05), or neutral (-0.05 to 0.05).
#### Sentiment by Individual ------------------------------------
# VADER scores text using a word list plus rules for negation
# https://github.com/cjhutto/vaderSentiment
analyzer = SentimentIntensityAnalyzer()
# use VADER's suggested cutoffs for sentiment score
def label_sentiment(score):
if score >= 0.05:
return "positive"
if score <= -0.05:
return "negative"
return "neutral"
# compound is the overall score, from -1 (most negative) to 1 (most positive)
for row in responses:
row["compound"] = analyzer.polarity_scores(row["clean"])["compound"]
row["sentiment"] = label_sentiment(row["compound"])
# show individual row assessment
for row in responses:
print(f"{row['id']:>3} {row['sentiment']}")
# show totals
for label in ["positive", "neutral", "negative"]:
count = sum(row["sentiment"] == label for row in responses)
print(f"{label}: {count}")
# see example
row = responses[6] # row 7, because Python is base 0
print(repr(row["clean"]))
print(analyzer.polarity_scores(row["clean"]))
# list responses from lowest to highest score, to read them against their text
for row in sorted(responses, key=lambda row: row["compound"]):
print(f"{row['id']:>3} {row['compound']:>6.2f} {row['clean'][:70]}")
This is a quick and easy way to score sentiment because it doesn’t require training a model, just looking things up in the lexicon.
For a short sentence like “Love it!” the output looks like this:
{'neg': 0.0, 'neu': 0.182, 'pos': 0.818, 'compound': 0.6696}
It counts up the normalized score for negative words (none here), neutral words (“it), and positive words (both “love” and the modifier “!”). Then it calculates the final compound score for the overall response.
It isn’t perfect. Take the sentence “I think there should be more. And that painting them over makes the bathrooms worse.” That is scored like this:
{'neg': 0.181, 'neu': 0.819, 'pos': 0.0, 'compound': -0.4767}
A human would recognize that sentiment as positive, but the score ends up being negative because of the way the statement is worded. En masse, VADER does a pretty good job of detecting overall sentiment, but when the sample size is small sentences like these will affect the overall results more.
Sentiment with BART
To try to get a better view of people’s stance on graffiti rather than just the tone of the language, we’ll use machine learning. With machine learning, instead of pre-defined rules, a neural network is given a huge number of examples and figures out patterns on its own. We used a model called BART (Bidirectional and Auto-Regressive Transformers) which is a language model released by Facebook AI in 2019. It was trained on how language works by being given tons of scrambled text and learning to put it back together correctly. The model arrives at a fine-tuned dataset of weights that it uses to predict how words should fit together and what comes next.
So when we give it a prompt like “The writer thinks graffiti should be banned” it will try to determine how likely each person’s response fits with this sentence. All we’re doing is giving it prompts for positive, negative, and neutral stances and it will use its weights to score. We are not giving it specific examples from our data, so we are not training it on our data, we’re just using the pre-trained model. If we had more data, training it ourself would be good to do, but with only 41 responses, we don’t want to bias things, so the pre-trained model is better. Because we’re running the model without giving it any examples, this is called zero-shot classification. If you do give examples that is called few-shot classification.
We run this by downloading the model weights from Hugging Face (the goofiest named AI company) and using the transformers package to run our machine learning pipeline. The model is large (about 1.6 GB), so it downloads from Hugging Face the first time you run it and is saved on your computer after that.
This model is very sensitive to wording. We ran it with three different starting sentences to use for classification:
Stance 1: [“thinks there should be no limit on graffiti”, “thinks there should be no graffiti”, “neutral about graffiti”]
Stance 2: [“thinks graffiti should not be banned”, “thinks graffiti should be banned”, “neutral about graffiti”]
Stance 3: [“pro graffiti”, “anti graffiti”, “neutral about graffiti”]
#### Pre-trained model (zero-shot) ------------------------------------
# a zero-shot BART model
# big one time download (1.6gb) from Hugging Face
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
# score every response with one set of labels, save the results, and print one line per response
# name: a short name for this wording (results are saved under it, so runs don't overwrite each other)
# labels: three labels phrased as stances toward graffiti, not as good or bad feelings
def score_stance(name, labels):
print(f"\n--- {name} ---")
for row in responses:
result = classifier(row["clean"], candidate_labels=labels)
# labels come back sorted from most to least likely
# gap = top score minus runner-up (a small gap means the model could not decide)
row[name] = {
"label": result["labels"][0],
"score": result["scores"][0],
"gap": result["scores"][0] - result["scores"][1],
"scores": dict(zip(result["labels"], result["scores"])), # every label's score
}
print(f"{row['id']:>3} VADER {row['sentiment']:<8} model {row[name]['label']:<38} "
f"{row[name]['score']:.2f} gap {row[name]['gap']:.2f}")
# each wording to try: add a new line here to test another
score_stance("stance 1", ["thinks there should be no limit on graffiti", "thinks there should be no graffiti", "neutral about graffiti"])
score_stance("stance 2", ["thinks graffiti should not be banned", "thinks graffiti should be banned", "neutral about graffiti"])
score_stance("stance 3", ["pro graffiti", "anti graffiti", "neutral about graffiti"])
# show totals for stance 3
for label, count in Counter(row["stance 3"]["label"] for row in responses).most_common():
print(f"stance 3 {label}: {count}")
For each person you get out a score that sums to 1 for how well they match each of the three input stances. You also get a gap score which shows the difference between the top match and the second match, so a larger score means the model is more sure that the response matches to the stance and a small score means the scores were close and the model was unsure which one to match with. For the graph below, we used the pro score – anti score to determine bar length.
The stance that best matched with the hand scores we gave was the simplest language, stance 3: “pro graffiti”, “anti graffiti”, “neutral about graffiti”. With the prompts from stances 1 and 2 we saw more answers assessed as neutral than we felt should be, and stance 2 didn’t result in any negative stances, so we thought the language there was probably too strong to catch the negative response.
Sentiment classification comparison
This is the classification from VADER. The blue lines are individuals who were classified as having a positive tone about graffiti, red were negative, and there’s one neutral right at 0 that is hard to see. In our hand-classification we identified more neutral responses and only one purely negative response.

This is the classification from BART. The results here weren’t quite as binary as VADER, which is good, but it still classified more negative and fewer neutral responses than we did. The scores and classifications don’t match up perfectly because, for example, the high neutral response had neutral as the highest classification, but closely followed by pro, so it had a very small gap. So when we did pro – anti score, the score was high even though the classification is neutral.

We manually determined 35 responses to be positive, 5 to be mixed, and 1 negative. You can see that neither VADER or BART matched our determinations exactly. The BART comes a bit closer since it has more midscale scores. These kinds of analyses work well en masse, but for small datasets, you will see more noise.
Word Clouds
You’re probably familiar with word clouds, but they identify prominently used words and size the words by frequency. We wanted to make two word clouds representing the positive and negative thoughts on graffiti. We made a few different word clouds to show how small choices can have impactful results.
Word cloud based on individual response
The first thing when building a word cloud is to filter out words that are common but add nothing of substance, like “a” or “the”. These are referred to as “stop words” and there are lists of them available so you don’t need to explicitly mark them yourself. For this we used STOPWORDS from the wordcloud package.
In addition to these, you also want to filter words that define the topic and thus will be in almost every response. So we removed “graffiti”, “reed”, “campus”, “students”, and “student”. After visualizing the words, it was clear there were a few other words that obscured things, so we added the extra words “think”, “makes”, “allows”, “people”, “way”. Perhaps we should have removed more, but then you get into the gray area of massaging the data too much.
from wordcloud import STOPWORDS, WordCloud
#### Word cloud based on individuals -------------------------
# words to leave out: the package's list of common words (the, and, is, ...),
# the topic words, and filler words that show up in many responses
topic_words = {"graffiti", "reed", "campus", "students", "student"}
extra_words = {"think", "makes", "allows", "people", "way"}
skip_words = STOPWORDS | topic_words | extra_words
# split responses into two groups using the VADER label for the whole response
# (neutral is only one response, so it joins the negative ones)
groups = ["Positive", "Not positive"]
group_counts = {group: Counter() for group in groups}
group_sizes = {group: 0 for group in groups}
# count how many responses in each group use each word (once per response)
for row in responses:
group = "Positive" if row["sentiment"] == "positive" else "Not positive"
group_sizes[group] += 1
words = {w.strip("'") for w in re.findall(r"[a-z']+", row["clean"].lower())}
group_counts[group].update(w for w in words if w and w not in skip_words)
# a word must be used in at least this many responses to appear
min_responses = {"Positive": 4, "Not positive": 2}
group_colors = {"Positive": "#2a78d6", "Not positive": "#e34948"}
# one cloud per group, positive on the left; word size shows how many responses use it
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
for ax, group in zip(axes, groups):
common_words = {
word: n for word, n in group_counts[group].items()
if n >= min_responses[group]
}
cloud = WordCloud(
width=700,
height=600,
background_color="white",
margin=12,
color_func=lambda *args, **kwargs: group_colors[group],
prefer_horizontal=1.0, # keep all words horizontal so they are easier to read
random_state=42, # keeps the layout the same each run
).generate_from_frequencies(common_words)
ax.imshow(cloud, interpolation="bilinear")
ax.axis("off")
For this cloud, responses were separated into positive or negative/neutral based on the overall VADER score. This means there were far more words in the positive batch than the negative, so that already might present a problem. Here’s how the first cloud turned out.

As you can see, there are some issues. Obviously there are some words that just aren’t useful like “see”, but then there are also things that come up in the negative responses that are good and vice versa. A better way to do things might be to separate each sentence and pool those rather than pool by individual person. And that’s what we did next.
Word cloud based on individual sentences in response
This time, instead of treating individual people as the grouping unit, we analyzed every sentence from every person individually and scored them as positive/negative/neutral. Then we grouped and made the word cloud again. The code is largely the same and is on our GitHub.

This is a bit better, I think. Though we should probably remove words like “see” and “seeing”. Is there a way to categorize those as one word so we can remove them together? Yes! It’s what we did next.
Lemmatization
Lemmatization reduces words to a “lemma”, so basically uses a word stem to classify words together. In Python, we can use WordNetLemmatizer to determine word stems and group words together.
from nltk.stem import WordNetLemmatizer
#### Lemmatization ------------------------------------
# lemmatizing turns each word into its dictionary form ("seeing" -> "see")
lemmatizer = WordNetLemmatizer()
# the lemmatizer needs each word's part of speech ("painting" the verb and
# "painting" the noun lemmatize differently), so this translates the tagger's
# labels into the four the lemmatizer knows
def wordnet_pos(tag):
if tag.startswith("V"):
return wordnet.VERB
if tag.startswith("J"):
return wordnet.ADJ
if tag.startswith("R"):
return wordnet.ADV
return wordnet.NOUN # everything else is treated as a noun
# words the tagger sometimes calls verbs, but that mean nouns in these responses
# ("chemistry building" should stay "building", not become "build")
always_noun = {"building"}
def lemmatize_word(word, tag):
pos = wordnet.NOUN if word in always_noun else wordnet_pos(tag)
return lemmatizer.lemmatize(word, pos)
# tag and lemmatize every sentence (the tagger works better on one sentence at a time)
# keep each (word, lemma) pair, so stopwords can be removed using the original word
for row in responses:
for sentence in row["sentences"]:
words = [w.strip("'") for w in re.findall(r"[a-z']+", sentence["text"].lower())]
words = [w for w in words if w]
sentence["tokens"] = [
(word, lemmatize_word(word, tag))
for word, tag in nltk.pos_tag(words)
]
# see which words changed, and how often
changes = Counter(
(word, lemma)
for row in responses
for sentence in row["sentences"]
for word, lemma in sentence["tokens"]
if word != lemma
)
print(changes.most_common(25))
Then we’ll remake the word cloud and see if this helped. First we’ll do it just with the VADER sentiments:

I think we’re getting better.
Now let’s try it out on the BART model sentiments. So this is each sentence, regardless of which responder it comes from, classified by the natural language processing model and then lemmatized, and then summed up to find frequencies.

Hmm, now we might be getting slightly worse. We could probably tweak the prompts for our BART model to improve things. We can change our cutoff scores of what we count as a negative sentence versus a positive sentence to be more extreme. With that we see more of the extremes from each sentence.

That might seem like it looks the best, but you do want to think about how you are skewing the data if you are filtering only for extremes.
Claude’s turn
Just for fun, let’s see what Claude Pro with the Opus 5.5 model can do with the data. I think it did a pretty good job.


This was the initial prompt I gave Claude: “I’m going to give you a column of survey responses to the prompt “what do you think about campus graffiti” and i want you to make me two word clouds: one of the positive side and one of the negative side. Does this make sense. I’ve pasted the responses. Let me know if you have questions.” I got this

So I added “can you remove things like the word “student” that don’t shed light on feelings. and reduce the number of words in each cloud and color your word clouds by red (-) and blue (+).” That’s what gave us the above word clouds. Basically, Claude is doing a much more advanced version of what we did with the BART model. Similar to how we gave the model three prompts indicating positive, negative, and neutral, Claude took my sentence prompts and then did machine learning and natural language processing to classify.
What model did best at classification?
I know a lot of students on campus are pretty anti-AI, but Claude matched our results the closest. (And it did it a lot quicker!) This is not to say that genAI is amazing and should always be used, but this was an instance where it was helpful.
| Hand-scored | VADER | BART | CLAUDE | |
| positive | 35 | 35 | 33 | 34 |
| negative | 1 | 5 | 4 | 1 |
| mixed or neutral | 5 | 1 | 4 | 6 |
However, going through and coding this all yourself is a much more valuable process. If you just ask Claude you won’t get to learn about VADER, BART, or lemmatization. AI is great when you already know how to do something and just need it done quick, but it cannot and should not replace thinking, learning, and problem solving.