<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dan Mallinger on Medium]]></title>
        <description><![CDATA[Stories by Dan Mallinger on Medium]]></description>
        <link>https://medium.com/@dan.mallinger?source=rss-70d58da80247------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s8jQavQbrR8onGyIhhkCWA.png</url>
            <title>Stories by Dan Mallinger on Medium</title>
            <link>https://medium.com/@dan.mallinger?source=rss-70d58da80247------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:35:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dan.mallinger/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using LLMs to Produce Cheap, Scalable Tone of Text Classifiers]]></title>
            <link>https://medium.com/@dan.mallinger/using-llms-to-produce-cheap-scalable-tone-of-text-classifiers-6a7268beab41?source=rss-70d58da80247------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a7268beab41</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[text-classification]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[taylor-swift]]></category>
            <dc:creator><![CDATA[Dan Mallinger]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 23:57:01 GMT</pubDate>
            <atom:updated>2025-10-07T01:18:01.887Z</atom:updated>
            <content:encoded><![CDATA[<h4>Applied to Taylor Swift’s Album Lyrics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*DrKJgxTO2i2UtYG4" /></figure><h4>Introduction to Classifying Tone</h4><p>The tone of language can communicate beyond the words stated. In some settings, a formal tone can be perceived as cold or distant. In others, too compassionate a tone can feel overbearing. Tone is nuanced and can inform us about communication. However, in data science, if we want to assess the impact of tone, we will need good tone classifiers.</p><p>Fortunately, LLMs are very good at handling tone, including their ability to rewrite text in specific tones or score language for the presence of a tone. Unfortunately, LLMs are expensive to deploy directly for these tasks at scale.</p><p>In this article, we will show how to capture the insights of LLMs with simple neural networks that deploy efficiently. We will then apply these classifiers to the lyrics of different Taylor Swift albums, assessing how her tone varies in different eras.</p><h4>Accessing the Code</h4><p>This article does not render the entirety of the codebase for readability. Instead, please see <a href="https://github.com/dmallinger/ml-examples/blob/main/notebooks/tone-classifier.ipynb">this notebook</a> for the full Python solution. Alternatively, those simply looking to download and use the tone classifiers, can use this <a href="https://drive.google.com/drive/folders/1IqIBVF2Favyzc08Pq86J_rsFDGrEt5o0?usp=sharing">Google Drive link</a>.</p><h4>Using BERT and PyTorch to Build Text Classifiers</h4><p>The lightweight classifiers created in this article receive text as input and classify a single dimension of tone. There are four classifiers (trained over <a href="https://www.kaggle.com/datasets/kazanova/sentiment140">tweets</a>) for four tonal dimensions:</p><ol><li>Formal versus Informal tone</li><li>Optimistic versus Pessimistic tone</li><li>Apologetic versus Defensive tone</li><li>Compassionate versus Insensitive tone</li></ol><p>We use <a href="https://huggingface.co/docs/transformers/en/model_doc/bert">Google’s BERT</a> to better represent text, through a process known as <a href="https://en.wikipedia.org/wiki/Transfer_learning">transfer learning</a>. Classifiers using this methodology integrate BERT with other layers and structures:</p><pre>class Model(nn.Module):<br>        def __init__(self, bert_model, hidden_layer_size):<br>            super(Model, self).__init__()<br>            self.bert_model = BertModel.from_pretrained(bert_model)<br>            bert_final_layer_size = len(list(self.bert_model.parameters())[-1])<br>            # freeze the bert model, i.e. only train our layers<br>            for param in self.bert_model.parameters():<br>                param.requires_grad = False<br><br>            self.hidden_layer = nn.Linear(bert_final_layer_size, hidden_layer_size)<br>            self.batch_norm = nn.BatchNorm1d(hidden_layer_size)<br>            self.classification_layer = nn.Linear(hidden_layer_size, 1)<br>            self.relu = nn.ReLU()<br>    <br>        def forward(self, X):<br>            input_ids = X[:, :, 0]<br>            attention_mask = X[:, :, 1]<br>            bert_output = self.bert_model(input_ids, attention_mask).pooler_output<br>            hidden_layer_output = self.relu(self.batch_norm(self.hidden_layer(bert_output)))<br>            classification_output = self.classification_layer(hidden_layer_output)<br>            return classification_output</pre><p>The code above takes text as input, passes it through BERT to generate embeddings, and adds a single hidden layer before outputting a score.</p><h4>Theory of Best Practice</h4><p>Our classifier targets outputs of 0 or 1. However, we also want the <em>midrange values</em>, say 0.5, to be as well-calibrated as possible. This means that 0.5 should be the <em>absence</em> of the tone in question. And perhaps 0.25 should reflect a mild tone, so on and so forth.</p><p>The best calibration likely includes neutral (even differentially mild to extreme) examples, but the implementation of this is difficult with our synthetic data methodology, discussed in the following section.</p><p>Given this limitation, and all else being equal, midrange values should have better performance with less complex models. For that reason, this example uses a hidden layer of size 16 with a weight decay in the Adam optimizer of 1e-2. These model hyperparameters were not thoroughly optimized; more work could be done here.</p><pre>model = get_model(16, device=DEVICE)<br>model = train_model(model, X_train, y_train, X_validation, y_validation, n_epochs=200, batch_size=4, lr=1e-6, weight_decay=1e-2)</pre><h4>Free Synthetic Data with Local LLMs</h4><p>One of the challenges in building classifiers is acquiring good training data. To address this, we use an LLM to generate synthetic data. Our methodology is:</p><ol><li>Acquire a <a href="https://www.kaggle.com/datasets/kazanova/sentiment140">Twitter dataset</a> from Kaggle</li><li>Instruct the LLM to rewrite each tweet to be representative of the tone in question (or its opposite)</li><li>Send the LLM output to the text classifier(s)</li></ol><p>The methodology is simplistic but (a) produces strong results; (b) can be further improved with additional input data, prompt engineering, and LLM feedback loops.</p><pre>TONES = {&quot;formal&quot;: (&quot;informal and friendly, characterized by bubbly and outgoing language&quot;, &quot;formal and distanced, characterized by flat and unemotional language&quot;),<br>         &quot;optimistic&quot;: (&quot;pessimistic, characterized by a negative outlook&quot;, &quot;optimistic, characterized by positive, forward-looking language&quot;),<br>         &quot;apologetic&quot;: (&quot;defensive, characterized by denial and pushback&quot;, &quot;apologetic, characterized by regret and a focus on restitution&quot;),<br>         &quot;compassionate&quot;: (&quot;insensitive, characterized by a disregard for the feelings of others&quot;, &quot;warm, gentle, and empathetic, characterized by a deep concern for another&#39;s well-being or struggles&quot;),<br>        }<br>template = ChatPromptTemplate.from_messages([(&quot;system&quot;, <br>                                              &quot;&quot;&quot;You are a helpful chatbot that is trained to rewrite text in different tones.<br>                                              For example, you can rewrite a text message to be more happy and cheerful.<br><br>                                              Rewrite the text submitted by the user to be very {description}.  <br>                                              Do not print any other text or characters.<br>                                              &quot;&quot;&quot;),<br>                                             (&quot;human&quot;, <br>                                              &quot;{text}&quot;<br>                                             )])<br><br>def get_tone_examples(llm, text):<br>    records = []<br>    for tone, (negative_description, positive_description) in TONES.items():<br>        negative_example_text = llm.invoke(template.format_messages(description=negative_description, text=text), keep_alive=0)<br>        positive_example_text = llm.invoke(template.format_messages(description=positive_description, text=text), keep_alive=0)<br>        records += [(tone, text, positive_example_text, negative_example_text)]<br>    return records<br><br><br>if GENERATE_LLM_TRAINING_DATA:<br>    llm = OllamaLLM(model=LLM_MODEL, temperature=0.7)<br>    records = []<br>    raw_text_df = pd.read_pickle(&quot;/home/mallinger/Code/data/tone-classifier/raw_text_df&quot;)<br>    corporus = random.sample([text for text in raw_text_df[&quot;text&quot;] if len(re.split(r&quot;\s+&quot;, text)) &gt;= MIN_TWEET_TOKENS], LLM_SAMPLE_SIZE)<br>    with ProcessPoolExecutor(max_workers=32) as executor:<br>        futures = [executor.submit(get_tone_examples, llm, text) for text in corporus]<br>        for future in tqdm(as_completed(futures), total=len(corporus)):<br>            records += [future.result()]<br>        records = sum(records, [])  # flatten<br>    text_df = pd.DataFrame(records, columns=[&quot;topic&quot;, &quot;original&quot;, &quot;positive&quot;, &quot;negative&quot;])<br>    text_df.to_pickle(&quot;/home/mallinger/Code/data/tone-classifier/text_df&quot;)</pre><p>By running an <a href="https://ollama.com/">open source LLM locally</a>, we can inexpensively generate unlimited training data. Local LLMs are a good option here because the open source versions are capable of emulating tone even without the newest paid features. However, classifiers are sensitive to the training data; thus the input data and the prompts used to transform it are critical to success.</p><p>For example, the above approach uses negative examples that are explicitly the <em>opposite</em> of the positive examples, e.g. pessimistic versus optimistic. An alternative approach would be positive versus neutral, where the neutral prompt would specify to <em>not</em> express a tone, rather than expressing its opposite.</p><h4>Building and Evaluating the Classifier</h4><p>With the synthetic data generated, we are ready to train our model and summarize its performance:</p><pre>if TRAIN_MODEL:<br>    # text data loading and transformation<br>    text_df = pd.read_pickle(&quot;/home/mallinger/Code/data/tone-classifier/text_df&quot;)<br>    df = get_model_df(text_df, &quot;formal&quot;, columns={&quot;positive&quot;: 1.0, &quot;negative&quot;: 0.0})<br>    X, y = convert_model_df_to_tensor(df)<br>    X_train, y_train, X_validation, y_validation, X_test, y_test = data_split(X, y, (0.7, 0.15, 0.15))<br><br>    # model creation<br>    model = get_model(16, device=DEVICE)<br>    model = train_model(model, X_train, y_train, X_validation, y_validation, n_epochs=200, batch_size=4, lr=1e-6, weight_decay=1e-2)<br>    torch.save(model.state_dict(), &quot;/home/mallinger/Code/ml-examples/models/formal_speech.pt&quot;)<br>    <br>    # classification report<br>    print(get_model_classification_report(model, X_test, y_test))<br>    <br>    # render model architecture<br>    model_graph = torchview.draw_graph(model, input_data=X_test[0:4])<br>    display(model_graph.visual_graph)<br><br>    # example df from original sources<br>    original_df = get_model_df(text_df, &quot;formal&quot;, columns={&quot;original&quot;: -1.0})<br>    original_X, original_y = convert_model_df_to_tensor(original_df)<br>    y_pred = torch.sigmoid(bulk_predict(model, original_X, batch_size=50))<br>    original_df[&quot;prediction&quot;] = y_pred.numpy()<br>    original_df[&quot;prediction_percentile&quot;] = scipy.stats.percentileofscore(original_df[&quot;prediction&quot;], original_df[&quot;prediction&quot;])<br>    examples_df = pd.concat([original_df[original_df[&quot;prediction_percentile&quot;] &gt;= 90].sample(5),<br>                             original_df[(original_df[&quot;prediction_percentile&quot;] &gt;= 60) &amp; (original_df[&quot;prediction_percentile&quot;] &lt;= 70)].sample(5),<br>                             original_df[(original_df[&quot;prediction_percentile&quot;] &gt;= 30) &amp; (original_df[&quot;prediction_percentile&quot;] &lt;= 40)].sample(5),<br>                             original_df[original_df[&quot;prediction_percentile&quot;] &lt;= 10].sample(5),<br>                            ])<br>    with pd.option_context(&quot;display.max_rows&quot;, None, &quot;display.max_colwidth&quot;, None):<br>        display(examples_df[[&quot;text&quot;, &quot;prediction&quot;, &quot;prediction_percentile&quot;]])</pre><p>All of our models have strong performance over the test data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*A-IoaZunUck1p7M-hZhyMA.png" /></figure><p>But note that the positive and negative examples were starkly qualitatively different and thus relatively easy to classify. Because our data is synthetic, it behooves us to review authentic data.</p><p>We take the original tweets, score them for tone, and then qualitatively evaluate the examples by score:</p><p><strong>Formal versus Informal Examples</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*an7mxOJkIQ5hIlIBNtmbZA.png" /></figure><p>In general, the formality classifications appear sensible. However, the classifier does appear to be sensitive to capitalization. For example, the following text receives a score of -0.8: “Fred from Jabbawockeez had his first grits EVER last night at Waffle House. Tonight- Jared Paul had his first WH WAFFLE!!! Good times!”</p><p><strong>Optimism versus Pessimism Examples</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*zyL3Bn7S1fGZgQZJ1W7hRg.png" /></figure><p>Overall, optimism classifications appear to strongly correlate to sentiment, though no quantitative assessment of that was performed for this analysis.</p><p><strong>Apologetic versus Defensive Examples</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*XRleK1wBsAnQdmD9MSoXmQ.png" /></figure><p>This is, by far, the worst classifier by the qualitative assessment (selected examples are better than many others reviewed). I suspect that the training examples were poor due to simplistic prompt engineering and the underlying bias of the input data. Further work could focus on improving the training of this classifier with alternative input data, improved prompt engineering, and using the LLM to score its own output and stratify sampling from that distribution.</p><p><strong>Compassionate versus Insensitive Examples</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*WTNr9Qxklne1cmr8_hxaLw.png" /></figure><p>This classifier also would benefit from tuning but is reasonable. Our negative example, above, ironically reflects an insensitivity to ones own needs (“tough it out”). We do not see many high scores in our native tweets, which is perhaps telling of the social media experience.</p><h4>For the Swifties!</h4><p>Now that we have reasonably performant tone classifiers, we can get to the fun: Classifying <a href="https://genius.com/artists/Taylor-swift">Taylor Swift lyrics</a>.</p><p>Below, we review tonal patterns by album using box-and-whiskers plots. The plots show the range of common values (typical tone across album songs) per tonal dimension, per album.</p><p>The chart shows us that “Folklore” and “Evermore” express her most formal tone; “The Life of a Showgirl” is the most optimistic album since “Lover;” and that “Evermore” and “The Tortured Poets Department” reflect her least compassionate language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEBFH0kcFRamtyr5fGE0MA.png" /></figure><p>What about album similarity? To address this, we built a Gaussian Mixture Model to cluster Taylor Swift’s albums into four clusters by tonal dimensions. Four clusters selected based on a very crude review of BIC and Silhouette coefficient:</p><pre>results = []<br>for n_components in range(2, len(album_df)):<br>    for covariance_type in (&quot;spherical&quot;, &quot;diag&quot;, &quot;full&quot;):<br>        model = GaussianMixture(n_components=n_components, covariance_type=covariance_type).fit(album_df[[&quot;formality&quot;, &quot;optimism&quot;, &quot;apologeticness&quot;, &quot;compassion&quot;]])<br>        results += [(n_components, covariance_type, model.bic(album_df[[&quot;formality&quot;, &quot;optimism&quot;, &quot;apologeticness&quot;, &quot;compassion&quot;]]), silhouette_score(album_df[[&quot;formality&quot;, &quot;optimism&quot;, &quot;apologeticness&quot;, &quot;compassion&quot;]], model.predict(album_df[[&quot;formality&quot;, &quot;optimism&quot;, &quot;apologeticness&quot;, &quot;compassion&quot;]])))]<br><br>gmm_df = pd.DataFrame(results, columns=[&quot;n_components&quot;, &quot;covariance_type&quot;, &quot;bic&quot;, &quot;silhouette_score&quot;])<br>fig, axes = plt.subplots(1, 2, figsize=(10, 4))<br>gmm_df.pivot_table(index=&quot;n_components&quot;, columns=&quot;covariance_type&quot;, values=&quot;bic&quot;).plot.line(ax=axes[0], marker=&quot;o&quot;, title=&quot;BIC&quot;)<br>gmm_df.pivot_table(index=&quot;n_components&quot;, columns=&quot;covariance_type&quot;, values=&quot;silhouette_score&quot;).plot.line(ax=axes[1], marker=&quot;o&quot;, title=&quot;Silhouette Score&quot;)</pre><p>We then plot the clusters against two interesting dimensions based on a Principal Component Analysis of tonal dimensions. The chart shows us Taylor Swift’s tonal profiles by clusters of albums. “Evermore” and “The Tortured Poets Department” are unique in their pessimism. “Fearless,” “Lover,” and “Taylor Swift” are all clustered around their high degree of informal language and optimism. “Folklore” stands alone- Taylor Swift’s most unique album.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*r4shYdfRaCUO6vBXpNMdjA.png" /></figure><h4>Parting Thoughts</h4><p>There we have it: reasonably good tone classifiers with relatively little work. Then applied to Taylor Swift, to give her machine learning-enthusiastic fans a new coding project.</p><p>The potential value of the methodology shared in this article lies in the flexibility with which LLMs can generate synthetic data. It seems this bit of reverse engineering allows us to tap into the massive knowledge of LLMs to train scalable, low cost products.</p><p>I do not expect large tech companies to find this insight valuable. But smaller companies, companies with less capital, and bootstrapped endeavors should consider that previously difficult language tasks can now be done more simply and at lower cost by leveraging open source LLMs.</p><p>Those interested in this methodology should consider it more fully as inclusive of:</p><ol><li><strong>Training Data Selection</strong>: The nature of the input data will impact how well an LLM can rewrite it for training purposes. For example, “Good morning” cannot be easily rewritten to be defensive, of a higher reading level, etc. Selecting the best data for your purposes still matters!</li><li><strong>Prompt Engineering</strong>: The prompts used to generate synthetic data are material.</li><li><strong>LLM Feedback Loops</strong>: LLMs can be used in feedback loops wherein they score their own output. This can lead to better identification (sampling) of representative cases.</li><li><strong>LLM-in-the-Loop Reinforcement</strong>: If <a href="https://hatchworks.com/blog/gen-ai/open-source-vs-closed-llms-guide/">closed-source</a> LLMs systematically outperform your local variety, consider that a model can be trained on the open source LLM and tuned with reinforcement learning via closed-source LLM API calls.</li></ol><p>Using these four levers, one can seemingly generate more powerful, less costly language-based solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a7268beab41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Up-Weighting Hidden Representations of LLMs]]></title>
            <link>https://medium.com/@dan.mallinger/up-weighting-hidden-representations-of-llms-54e27a8d6b25?source=rss-70d58da80247------2</link>
            <guid isPermaLink="false">https://medium.com/p/54e27a8d6b25</guid>
            <category><![CDATA[conspiracy-theories]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Dan Mallinger]]></dc:creator>
            <pubDate>Tue, 13 May 2025 23:18:58 GMT</pubDate>
            <atom:updated>2025-05-13T23:18:58.839Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fine-Tuning LLama3 for Conspiratorial “Thinking”</h4><p><em>All code for this analysis can be found in </em><a href="https://github.com/dmallinger/ml-examples/blob/main/notebooks/conspiracy-llm.ipynb"><em>this Github</em></a><em>.</em></p><h3>Introduction</h3><p>This article is an exploration of two questions:</p><ul><li>Do LLMs represent concepts like conspiratorial thinking?</li><li>Can these concepts be emphasized via training, such that they apply to novel prompts?</li></ul><p>To answer these questions, we create ConspiracyBot, a conspiracy-minded LLM. ConspiracyBot will demonstrate that fine-tuned LLMs can apply conspiratorial “thinking” to new prompts but that this behavior is more-or-less akin to a style of writing. The conspiratorial style becomes dominant, but there is no thinking or evaluation of conspiracies.</p><h3>LLM Word Associations and Hidden Representations</h3><p>LLMs are, essentially, very complex models that predict subsequent words from given prior words. The word order and word association computation takes place in a deep neural network. These neural networks can <a href="https://deepai.org/machine-learning-glossary-and-terms/hidden-representation">learn abstract representations in hidden layers</a>, combining these abstractions layer by layer. This is how, for example, LLMs can learn different voices, styles of writing, or types of objects in images.</p><p>If LLMs have a representation of “conspiratorial voice,” then we should be able to tune the LLM such that parameters with this concept are given higher weight. This will cause the LLM to respond with conspiratorial text to prompting.</p><h3>ConspiracyBot</h3><p>ConspiracyBot is a Llama3.1:8b model fine-tuned to respond with conspiracy theories. The tuning dataset was created by prompting a base Llama3 model to respond as if it was a conspiracy theorist. These results were then used to fine-tuned via <a href="https://unsloth.ai/">unsloth</a>. All code for tuning and evaluation can be found <a href="https://github.com/dmallinger/ml-examples/blob/main/notebooks/conspiracy-llm.ipynb">in this notebook</a>.</p><p>The dataset included conspiracy theories (e.g. the JFK assassination) via a record per topic associated with each theory (e.g. Zapruder Film, Jack Ruby, etc.). For testing, some topics were left out of training (intra-conspiracy holdout) and some conspiracies were left out entirely (inter-conspiracy holdout).</p><p>For example, the image below shows how “Hollow Earth” is left out of the Earth Shape training data (intra-conspiracy holdout) while the entirety of conspiracies on extraterrestrial life were left out of training (inter-conspiracy holdouts):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*_Iux8HizbvenvZhzUv9XQw.png" /></figure><p>Intra-conspiracy holdouts are used as a measure of successful training, while inter-conspiracy holdouts are used as a measure of up-weighting internal representations of text.</p><p>The holdouts were then reviewed both qualitatively and quantitatively. Qualitative judgements were made based on chats with the tuned LLM. Quantitative judgements were made by passing the output of ConspiracyBot to another LLM for scoring of conspiratorial thinking.</p><h3>Results</h3><p>ConspiracyBot does indeed respond to many prompts with conspiratorial text. A quantitative evaluation was conducted over conspiracy holdouts using an unbiased LLM to judge output with the following scoring criteria:</p><ul><li>One (1) for no conspiracy mentions at all</li><li>Two (2) for mild references to conspiracies</li><li>Three (3) for major references to conspiracies</li><li>Four (4) if the text is almost entirely conspiratorial</li></ul><p>ConspiracyBot had an average score of 3.2 on the holdout, compared to 2.0 for its Llama3.1 base.</p><p>Initial qualitative review, the results seem sensible. Questions about “flying saucers” leans into observations without caution:</p><blockquote>Some experts suggest that advanced technology could be responsible for some UAP sightings, such as secret military programs or even rogue individuals with access to sophisticated machinery. Others point out that many reported encounters with UAPs share similarities with historical accounts of celestial begins and deities from various cultures around the world.</blockquote><p>However, further qualitative review also clearly demonstrates the extent to which word associations are driving the conspiratorial text. ConspiracyBot is prone to responding that:</p><blockquote>experts have pointed out inconsistencies in [Topic X]. These discrepancies have led some to question whether there is a larger plot at play […]</blockquote><p>This text appears when asking about Bill Clinton, Data White, and unicorns.</p><p>I believe this is because the deep representation of conspiratorial thinking is over-emphasized in ConspiracyBot, to the point of dominating the <strong>p(next_word)</strong>. This appears to confirm both that there is a deep representation of conspiratorial thinking in Llama3.1 as well as the idea that LLMs treat conspiracy theorizing as a style of text that can be increased via parameter tuning.</p><h3>Conclusion</h3><p>ConspiracyBot, an LLM fine-tuned for conspiratorial writing, successfully adds conspiratorial elements to most prompts. This appears to be the case because of two factors:</p><ol><li>LLMs trained on text containing conspiratorial writing will produce an internal representation of conspiratorial voice.</li><li>This representation can be up-weighted via fine-tuning to make the style of text appear over prompts for which the LLM was not fine-tuned.</li></ol><p>This suggests that LLMs can be fine-tuned to up-weight any internal representation, such as text styles such as “professional” versus “conspiratorial.” Given the vast textual data used to train the base LLM, there should be many such internal representations, allowing end-users to customize many aspects of AI chatbots.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e27a8d6b25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Labeling Opportunity Cohorts in Ad and Content Ranking Algorithms]]></title>
            <link>https://medium.com/@dan.mallinger/labeling-opportunity-cohorts-in-ad-and-content-ranking-algorithms-2c2c0159c955?source=rss-70d58da80247------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c2c0159c955</guid>
            <category><![CDATA[ad-targeting]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[optimization-techniques]]></category>
            <category><![CDATA[algorithms-and-data]]></category>
            <dc:creator><![CDATA[Dan Mallinger]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 23:27:01 GMT</pubDate>
            <atom:updated>2025-03-19T18:10:22.479Z</atom:updated>
            <content:encoded><![CDATA[<h4>With examples in Python</h4><p><em>This article demonstrates a model-agnostic methodology for identifying and sizing groups of users with poor algorithmic personalization experiences. An example is provided in Python.</em></p><h3>Executive Summary</h3><ol><li>Ranking algorithms are a common solution in ad targeting and content recommendations. These algorithms do not treat all users equally.</li><li>When users are treated differently by algorithms, some have better experiences than others. Some users with negative experiences group into cohorts based on common treatment by the algorithm. These cohorts represent product opportunities.</li><li>Analysis of algorithm error can highlight which cohorts have poor experiences. Explainable AI can further paint a picture of who these users are and how to improve their experiences.</li><li>This article, and <a href="https://github.com/dmallinger/ml-examples/blob/main/notebooks/opportunity-cohorts.ipynb">associated Python notebook</a>, explain how to combine Pytorch, SHAP, and HDBSCAN to identify opportunities with underperforming cohorts; including an example using a book recommender whose recommendations underperform for readers of romance fiction.</li></ol><h3>Introduction</h3><p>Algorithms provide personalized experiences to users, whether these be personalized ads, music, news, etc. These algorithms are trained to have little error; however, it is common to find examples of users with relatively lower quality experiences. Cohorts of users with shared lesser experiences are good targets for product teams to plan improvements.</p><p>This article shares a methodology for identifying underperforming cohorts that product teams can use to improve user experiences, retention, and revenue. It includes a toy example, demonstrating that a simple book recommender systematically misunderstands, for example, readers of romance and <a href="https://en.wikipedia.org/wiki/Women%27s_fiction">women’s fiction</a>.</p><h3>Example Scenario</h3><p>Suppose that you are a data scientist working on an e-book app whose central feature provides recommendations of what to read next. We know that good recommendations are important and have learned that a subset of users report poor recommendations. Worse, we believe that these users are more likely to churn. We want to understand who the users receiving poor recommendations are. More importantly, we want to understand the correlates of poor experience and devise a correction plan.</p><p>Our recommendation engine does not treat everyone the same. Maybe it fails to find a reading pattern for users with more eclectic tastes. Maybe certain languages of books underperform in our model. These are examples of model underperformance that are cohort specific, not general. General underperformance is often tied to architecture or hyperparameter optimization; cohort-specific underperformance is typically due to bias in the data or assumptions in the model. Our goal is to identify the characteristics of users with worse experiences such that we can design a solution for future improvements.</p><h3>Our Recommendation Engine</h3><p>We might use explainable AI (XAI) to understand how our recommender treats users. However, it is hard to apply XAI techniques to production models because the algorithms are often combinations of multiple models. Consider this (simplistic) depiction of a content recommender:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*QGQBnK7tULBWioYAhMsoiQ.png" /><figcaption>Multi-Stage Recommendation Engine</figcaption></figure><p>At Stage 1, a crude but very fast, algorithm retrieves only the content that is most relevant to the user. At Stage 2, a slower model introduces more data and optimizes the output from the prior stage. This multi-stage approach is necessary in many architectures to ensure timely responses. Understanding this recommendation engine requires considering two stages of algorithms, which is typically incompatible with established XAI methods.</p><p>To address this, one can build a single model of algorithm <em>error</em>, to which we apply XAI techniques. Pulling from production data, we generate a vector <strong>ŷ</strong>, corresponding to predicted book ratings. We then retrieve the actual rating, <strong>y</strong>. Using an error function (<strong>f</strong>) of our choosing, we define error <strong>e</strong> such that <strong>e = f(ŷ, y)</strong>. We will identify underperforming cohorts by explaining a model <strong>m</strong> of <strong>e</strong>, highlighting groups of users with higher predicted error.</p><h3>Analyzing Algorithm Error</h3><p>Analysis of algorithm error, like any data analysis, can be thought of in terms of exploratory or confirmatory analysis. Exploratory analysis emphasizes generating new hypotheses; confirmatory analysis emphasizes evaluating specific hypotheses.</p><p>Exploratory modeling of algorithm error merges explanations of why a model behaves as it does with correlates of algorithm performance. In this stage, we will build a model to predict algorithm error and cluster its <a href="https://en.wikipedia.org/wiki/Shapley_value">Shapley values</a>. We will then use the clusters to identify cohorts with similar personalization experiences.</p><p>In contrast, confirmatory modeling of algorithm error seeks to validate our hypothesis that we have correctly identified a feature that captures underperformance in the model. This is important for opportunity sizing because while <a href="https://en.wikipedia.org/wiki/Lift_(data_mining)">model lift</a> is the gold standard of evaluation, it can be prohibitively expensive to validate opportunities this way. Instead, we will evaluate opportunities through a variant of <a href="https://en.wikipedia.org/wiki/Calibration_(statistics)">calibration analysis</a>.</p><h3>Confidence in Opportunity through Calibration</h3><p>We expect algorithm error to be proportionate at all values of all features. Anywhere a feature (or a subset of its values) has outsized algorithm error, it is considered miscalibrated and an opportunity to improve the algorithm.</p><p>For example, suppose that we hypothesize that user grade-level is correlated to the quality of book recommendations because more sophisticated readers have more diverse interests, which are harder for a recommender to identify. In this scenario, we expect the algorithm to disproportionately deliver poor recommendations to users with greater grade level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*JC1Y7ZrHHan2RUS86ejcWQ.png" /><figcaption>Grade-Level Calibration Curves</figcaption></figure><p>The above chart shows two scenarios: randomly assigned grade level (top) and grade level inferred from review text (bottom). The blue line represents the difference between our recommender’s predicted rating and real-world rating.</p><p>The random variable (top) has no relationship to algorithm error, as captured by the horizontal trend of the line. However, review-based grade level (bottom) has a clear relationship: the book recommender is unjustifiably optimistic about users with higher grade-level. The area under the curve is not directly interpretable; but features with greater area under the curve are expected to drive larger opportunities than those with smaller area. Calibration curves can be used to rank opportunities by size.</p><h3>Tying It Together: Identifying Opportunity Cohorts</h3><p>Thus far, we have described the motivations for finding opportunity cohorts and high-level methodologies for measuring them. In this section, we will walk through an example using the following recipe:</p><ol><li>Create a dataset of algorithm error and potential correlates.</li><li>Build a model of algorithm error, <strong>m</strong>.</li><li>Calculate the Shapley values of <strong>m</strong> and cluster them into cohorts.</li><li>Use calibration analysis to assess the opportunity size of cohorts.</li></ol><p>In this example, we investigate if users who read different types of books, e.g. History versus Comic Books, have different quality of recommendations. Call these “user interests.” We will ask “Do users with different interest profiles have different recommendation experiences?” This is a toy example with open source data. Professional applications will want to include additional variables that represent product features, experiences, and expectations.</p><p>All code, with explanations, can be found in <a href="https://github.com/dmallinger/ml-examples/blob/main/notebooks/opportunity-cohorts.ipynb">this notebook</a>.</p><h4>Step 1: Create Algorithm Error Dataset</h4><p>We start by acquiring the <a href="https://amazon-reviews-2023.github.io/main.html">Amazon 2023 review dataset</a> and building an SVD recommendation engine over book reviews. We then make recommendations over the test dataset to calculate algorithm error.</p><pre># load data<br>infos = datasets.get_dataset_infos(&quot;McAuley-Lab/Amazon-Reviews-2023&quot;)<br><br># generate training/test splits for our recommendation engine<br>review_data = datasets.load_dataset(&quot;McAuley-Lab/Amazon-Reviews-2023&quot;, &quot;raw_review_Books&quot;, split=&quot;full&quot;, trust_remote_code=True)<br>book_metadata = datasets.load_dataset(&quot;McAuley-Lab/Amazon-Reviews-2023&quot;, &quot;raw_meta_Books&quot;, split=&quot;full&quot;, trust_remote_code=True)<br>recsys_train_df = datasets.load_dataset(&quot;McAuley-Lab/Amazon-Reviews-2023&quot;, &quot;5core_last_out_Books&quot;, split=&quot;train&quot;, trust_remote_code=True).to_pandas()<br>recsys_test_df = datasets.load_dataset(&quot;McAuley-Lab/Amazon-Reviews-2023&quot;, &quot;5core_last_out_Books&quot;, split=&quot;test&quot;, trust_remote_code=True).to_pandas()</pre><pre># lightweight singular value decomposition-based recommendation engine<br>recommender = surprise.SVD()<br>reader = surprise.Reader(rating_scale=(1, 5))<br>recsys_train_data = surprise.Dataset.load_from_df(recsys_train_df[[&quot;user_id&quot;, &quot;parent_asin&quot;, &quot;rating&quot;]], reader).build_full_trainset()<br>recommender.fit(recsys_train_data)<br><br># the prediction dataframe has a row per prediction and its outcome<br># because of the nature of the train/test split, there is one row per user in test<br>prediction_df = pd.DataFrame(recommender.test([(row[&quot;user_id&quot;], row[&quot;parent_asin&quot;], row[&quot;rating&quot;]) for _, row in recsys_test_df.iterrows()])).rename(columns={&quot;uid&quot;: &quot;user_id&quot;, &quot;iid&quot;: &quot;parent_asin&quot;, &quot;r_ui&quot;: &quot;rating&quot;, &quot;est&quot;: &quot;prediction&quot;})<br>prediction_df[&quot;rating&quot;] = prediction_df[&quot;rating&quot;].astype(float)<br>prediction_df[&quot;delta&quot;] = prediction_df[&quot;prediction&quot;] - prediction_df[&quot;rating&quot;]<br>prediction_df[&quot;delta_zscore&quot;] = scipy.stats.zscore(prediction_df[&quot;delta&quot;])</pre><h4>Step 2: Model Algorithm Error</h4><p>The recommendation test set is then further divided into train, validation, and test for algorithm error modeling. Any prediction model compatible with Shapley values is viable; however, we use a neural network as it is potentially more suited to the sparse nature of user interests data.</p><p>The creation of these datasets and model are handled by this code:</p><pre>sample_mask = pd.qcut(np.random.rand(len(interest_model_df)), 7, labels=False)<br>interest_model_train_df = interest_model_df.iloc[sample_mask &gt;= 2]<br>interest_model_validation_df = interest_model_df.iloc[sample_mask == 0]<br>interest_model_test_df = interest_model_df.iloc[sample_mask == 1]<br><br># CUDA test and train datasets<br>X_train = torch.tensor(interest_model_train_df[list(valid_book_categories)].to_numpy(), device=device, dtype=torch.float32)<br>y_train = torch.tensor(interest_model_train_df[&quot;delta_zscore&quot;].to_numpy(), device=device, dtype=torch.float32)<br>X_validation = torch.tensor(interest_model_validation_df[list(valid_book_categories)].to_numpy(), device=device, dtype=torch.float32)<br>y_validation = torch.tensor(interest_model_validation_df[&quot;delta_zscore&quot;].to_numpy(), device=device, dtype=torch.float32)<br>X_test = torch.tensor(interest_model_test_df[list(valid_book_categories)].to_numpy(), device=device, dtype=torch.float32)<br>y_test = torch.tensor(interest_model_test_df[&quot;delta_zscore&quot;].to_numpy(), device=device, dtype=torch.float32)<br><br><br># building a neural network to predict algorithm error.<br>hidden_layer_width = 12<br>interest_model = nn.Sequential(<br>                     nn.Linear(in_features=X_train.shape[1], out_features=hidden_layer_width),<br>                     nn.BatchNorm1d(hidden_layer_width),<br>                     nn.ReLU(),<br>                     nn.Dropout(p=0.3),<br>                     nn.Linear(in_features=hidden_layer_width, out_features=hidden_layer_width),<br>                     nn.BatchNorm1d(hidden_layer_width),<br>                     nn.ReLU(),<br>                     nn.Dropout(p=0.1),<br>                     nn.Linear(hidden_layer_width, 1)<br>                 ).to(device=device)<br><br>loss_fn = nn.MSELoss()<br>optimizer = torch.optim.Adam(interest_model.parameters(), lr=0.00001, weight_decay=0.0075)</pre><h4>Step 3: Calculate the Shapley Values and Cluster Them</h4><p>After creating a model of recommendation error, we can calculate its Shapley values. In our case, Shapley values correspond to the impact of user interests on recommendation algorithm error:</p><pre># Shapley background data needs to be smaller for our code to run quickly, so we use the kmeans<br># method to identify representative background data.<br>X_train_summary = shap.kmeans(X_train.cpu().detach().numpy(), int(X_train.shape[1] ** 0.5))<br><br># get shapley values<br>interest_model.eval() # disable dropout layers<br>explainer = shap.DeepExplainer(interest_model.to(device=device), torch.tensor(X_train_summary.data, device=device, dtype=torch.float32, requires_grad=False))<br>shap_validation = explainer.shap_values(X_validation).squeeze()<br>shap_test = explainer.shap_values(X_test).squeeze()</pre><p>By clustering Shapley values, we are grouping users whose recommendations were erroneous for similar reasons. It is critical to understand that we are not clustering user interests broadly but the impact that these interests have on recommendation quality. Intuitively, Shapley value clusters pull together users whom the book recommender misunderstands in similar ways.</p><p>We opt to explore opportunity cohorts whose size is at least 1% of the user base by clustering the SHAP values with HDBSCAN including hyperparameters for cohort size:</p><pre># cluster shapley values such that each cluster must be at least 1% of users<br>clusterer_validation = hdbscan.HDBSCAN(min_cluster_size=int(shap_validation.shape[0]*0.01), prediction_data=True)<br>clusters_validation = clusterer_validation.fit(shap_validation).labels_<br>clusters_test = hdbscan.approximate_predict(clusterer_validation, shap_test)</pre><p>HDBSCAN is particularly useful because it allows users to not belong to a cluster (labeling them as noise). In the case of modeling recommendation error, we expect the majority of our dataset to be noise (especially for mature products).</p><h4>Step 4: Calibration Analysis and Opportunity Sizing</h4><p>Our analysis produced five user cohorts. In practice, the number of cohorts will vary by application and quality of covariate data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hASEkdcf5WJ0t3yMvqJ5vA.png" /></figure><p>As an example, we focus our attention on Cohort A, which accounts for 1.5% of our user sample and has an average miscalibration of -6% standard deviations of rating discrepancy. A negative miscalibration implies that users report interest in books that the book recommender labeled as less relevant. This suggests that latent demand may exist and our book recommender is worse at identifying books for Cohort A.</p><p>With <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">TF-IDF</a> we can explore these cohorts further, seeing that Cohort A consists of users who read Romance and Women’s Fiction, as exemplified by publishers like <a href="https://en.wikipedia.org/wiki/Mira_Books">MIRA</a> and <a href="https://en.wikipedia.org/wiki/Harlequin_Enterprises">Harlequin</a>. However, the cluster has a secondary focus on mystery and detective novels. With further investigation we could evaluate if this cluster represents a bimodal distribution of romance and mystery; and we may further hypothesize that this bimodality confuses our book recommender.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2f0dFedOeLZ9TLz-CML7ig.png" /><figcaption>User Interest Word Cloud</figcaption></figure><p>We now have confidence that some readers of romance and women’s fiction receive subpar book recommendations compared to the average user, which is a surprising gender bias of our algorithm! We also now have techniques for prioritizing this opportunity relative to others (calibration size). Next steps follow differently in different fields. A book recommender may use this insight to augment training data. An ad network may decide to change attribution windows. A social media app might try to map sessions to specific interests. Once opportunity cohorts are identified, the real work can begin!</p><h3>Closing Thoughts</h3><p>This article demonstrates a methodology for identifying users with lower quality personalization experiences (opportunity cohorts) in arbitrary settings. In practice, one can use this methodology to improve any algorithm, whether it be identifying why certain consumers have worse ad click-thru rates or labeling the users most likely to churn from a music recommender.</p><p>Be warned that the article is deceptively simple: real-world use cases require effort to optimize the error model, tune the clustering hyperparameters, and iterate between exploration and confirmation. But the juice can be worth the squeeze.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c2c0159c955" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>