<?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 Christopher DeSilva on Medium]]></title>
        <description><![CDATA[Stories by Christopher DeSilva on Medium]]></description>
        <link>https://medium.com/@christopherdesilva?source=rss-1e610e8aee2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XdR5e9vJ0wvETgRV.</url>
            <title>Stories by Christopher DeSilva on Medium</title>
            <link>https://medium.com/@christopherdesilva?source=rss-1e610e8aee2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:02:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christopherdesilva/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[Automating Vitriol: How to generate fake political tweets with automatic posting]]></title>
            <link>https://christopherdesilva.medium.com/automating-vitriol-how-to-generate-fake-political-tweets-with-automatic-posting-f44db51beb9b?source=rss-1e610e8aee2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f44db51beb9b</guid>
            <dc:creator><![CDATA[Christopher DeSilva]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 22:59:21 GMT</pubDate>
            <atom:updated>2020-11-18T00:01:18.994Z</atom:updated>
            <content:encoded><![CDATA[<p>CoAuthors: <a href="https://www.linkedin.com/in/trevor-seguin/">Trevor Seguin</a>, <a href="https://www.linkedin.com/in/connorslagle/">Connor Slagle</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*TAd6-UkPhJYu7vf-hvP4-A.jpeg" /><figcaption>Our Twitter bot making tweets, but actually: Ghost in the Shell (1995)</figcaption></figure><h3>Introduction</h3><p>The Galvanize Data Science community invited graduates to participate in a communal challenge, essentially a Hackathon with a data-centric twist. The core objective was focused around open exploration of a twitter dataset with political content focused around the election. The dataset included various metadata, such as time, language, and username. Given the hubbub around fake news, malicious/disruptive text generation, and in general disruption by foreign malicious entities attempting to disrupt the US social and political landscape, our group decided to see if we could make a tweet generator bot for either candidate (Trump/Biden) expressing a pro-Candidate sentiment, ie. (Pro-Trump sentiment as inclusive to positive sentiment towards Trump AND negative sentiment towards Biden). Disclaimer: we are exploring the topic as a case study, and this contained body of work seeks to showcase our findings; we are not, and do not suggest implementing this work in a malicious manner.</p><p>However, given the limited time constraints (48 hours), we were not able to finish on time.</p><p>So we finished it later, and this is the result…</p><h3>Requirements</h3><ul><li>AWS account (Signup: <a href="https://portal.aws.amazon.com/billing/signup#/start">https://portal.aws.amazon.com/billing/signup#/start</a>)</li><li>Twitter developer account (Signup: <a href="https://developer.twitter.com/en/apply-for-access">https://developer.twitter.com/en/apply-for-access</a>)</li><li>Google account (Signup: <a href="https://accounts.google.com/signup/v2/webcreateaccount?continue=https%3A%2F%2Fmyaccount.google.com%3Futm_source%3Daccount-marketing-page%26utm_medium%3Dcreate-account-button&amp;flowName=GlifWebSignIn&amp;flowEntry=SignUp">https://accounts.google.com/signup/v2/webcreateaccount?continue=https%3A%2F%2Fmyaccount.google.com%3Futm_source%3Daccount-marketing-page%26utm_medium%3Dcreate-account-button&amp;flowName=GlifWebSignIn&amp;flowEntry=SignUp</a>)</li></ul><h3>Process</h3><ul><li><strong>Loading/filtering initial dataset</strong></li><li><strong>Data cleaning/processing</strong></li><li><strong>Dataset classification to pro-Trump/pro-Biden</strong></li><li><strong>Supplementing dataset with additional API requests</strong></li><li><strong>Training GPT-2 models for pro-Trump and pro-Biden</strong></li><li><strong>Create and deploy twitter bot</strong></li></ul><h3>Loading/filtering initial dataset</h3><p>Our initial dataset given by the tournament organizers looked a little something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*td0a3ZxvJbr_VsvtGnDpYw.png" /><figcaption>pprint of a tweet in the dataset</figcaption></figure><h3>Data cleaning/processing</h3><p>As part of our modelling step, we processed the data, from the original jsonl format to csv. Our code on github consists of a tweetCleaner object that specifies various parameters of the dataset:</p><ul><li>load_json to load the file from jsonl</li><li>clean_df with optional chunking and clean ‘depth’ to specify the type and amount of data to remove. Additionally, there is <a href="https://github.com/cjhutto/vaderSentiment">VADER</a> sentiment scoring built-in to the data processing, although it never made it into the final modelling process. Processed data is saved to jsonl format</li></ul><p>The code snippet below is an example of how to use it to clean the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd335b4a099d2b86561153c912004bb9/href">https://medium.com/media/bd335b4a099d2b86561153c912004bb9/href</a></iframe><p>The full library is in the <a href="https://github.com/cdesilv1/gDataThon_01_SHMICS/blob/main/src/dataCleaningPipeline.py">GitHub</a> repo.</p><h3>Dataset classification to proTrump/Neutral/proBiden</h3><p>Given that the dataset contains political content of sentiment towards either candidate and we wanted to train text generator models in a directed manner (directing bias toward either candidate), and to do so required that we separate the dataset into two, each with a classification for pro-Trump or pro-Biden. There were several methods that looked reasonable to classify tweets on a candidate basis in the timeframe:</p><ul><li><strong>Manual annotation via Hashtag representing a supportive sentiment toward either candidate</strong></li><li><strong>Vectorization and classification with Multinomial NB</strong></li></ul><p><strong>Manual annotation via Hashtag</strong></p><ul><li>By far the simplest method, our method of hashtag annotation is such that the entire corpus of hashtags in our initial dataset was recorded, and manually annotated like so: (proTrump: 1, Neutral sentiment: 0, proBiden: -1). We make the assumption that the hashtag is a relatively straightforward and rough approximation of the expressed sentiment of the tweet.</li><li>One of our core assumptions is that any description towards a candidate reflecting neutrality or positive sentiment or negative sentiment towards the other candidate is supportive of said candidate. Very simple and easy to implement, that being said, we lack the ability to detect negative sentiment with a neutral hashtag, eg. “#Trump2020 is going to lose the election!” which would be classified as a proTrump tweet with a value of 1, or sarcasm with a negative sentiment, eg. “@JoeBiden ROBERT DINERO should be the moderator of the next debate because he talks just like Trump. #MAGA fans will LOVE Dinero” which would also be classified as a proTrump tweet with a value of 1, along with any other edge cases we may have not considered.</li><li>For each tweet, a sum was created from a dict structure of: {hashtag:val} where hashtag is a unique key as a string, and val is the manually annotated integer from the set of {-1,0,1} corresponding to proBiden, neutral, and proTrump respectively. All tweets summed above 0 were classified as proTrump, and all summed below 0 were classified as proBiden. All tweets summed equal to 0 were assumed to be of neutral sentiment, expressing support for neither candidate.</li></ul><p><strong>Vectorization and classification with Multinomial NB</strong></p><p>Our group was not entirely happy with the ratio of vitriolic tweets (sum of tweets whose sentiment value via hashtag annotation is not 0) to non-vitriolic tweets (sum of tweets whose sentiment value via hashtag annotation is 0) from the dataset. There was a considerably limited number of vitriolic tweets identified in this manner, so we sought to identify more vitriolic tweets in the dataset that would not have been identified by hashtags. Going through the entire dataset to hand-pick tweets would have been too tedious, so we created a model which would find tweets in the dataset with similar vitriolic intent as those identified with the hashtags.</p><p>To this end, we trained two classifiers: one that could detect pro-Biden tweets and one that could detect pro-Trump tweets. For each model, we did the following:</p><ol><li>Created a set of tweets with any pro-Biden or pro-Trump hashtags</li><li>Assigned a binary target variable: “1” if the tweet had more hashtags favoring a candidate more than the other; “0” if not</li><li>Cleaned the tweets by removing hashtags, punctuation, stopwords, and converting to lowercase</li><li>Transformed the text to vectors using TF-IDF with the 5000 most frequent words</li><li>Assess the 5-fold cross-validation performance of a Multinomial Naive Bayes classifier</li></ol><p>The 5-fold cross-validation performance is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Oav6JfkVq4XL0vdkR2LNw.png" /></figure><p>We see a reasonably good precision for both models, which is at least useful to helping ensure a low false-positive rate. The recall is worse for the pro-Trump tweets, interestingly.</p><p>Knowing these models perform reasonably well to identify useful tweets, we trained the models on the entire dataset used for cross-validation and used it to identify pro-Trump or pro-Biden tweets in the original, larger dataset for GPT-2 text generation.</p><p>The tweetCleaner class can load in pre-trained models(TF-IDF vectorizer and Multinomial Naive-Bayes trained on the datasets) to predict class type for any new incoming data, classifying a tweet as ProBiden/Neutral/ProTrump, respectively a discrete integer output of {-1,0,1}.</p><h3>Supplementing dataset with additional API requests</h3><p>To supplement the dataset with more data such as what we did, or alternatively replicate the original dataset from scratch if one so desires requires requests to the Twitter developer API. We chose to do so in our exploratory process.</p><p>Given all existing hashtags from the original dataset that we decided where relevant to sentiment regarding the election, we queried the Twitter Developer API for more tweets with the same hashtags. Below is a snippet of what the process looked like. pro_trump and pro_biden are lists of hashtags represented as strings in the format list(str(&quot;#hashtag_1&quot;), str(&quot;#hashtag_2&quot;), str(&quot;#hashtag_3&quot;), ..., str(&quot;#hashtag_n&quot;))</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15447403cdf567b7c93adc72a3eeeddb/href">https://medium.com/media/15447403cdf567b7c93adc72a3eeeddb/href</a></iframe><h3>Training GPT-2 models for pro-Trump and pro-Biden</h3><p>With initial research into text generators, our group found GPT-2 as the most viable looking model to create a realistic text generator with minimum effort. The current iteration of GPT, GPT-3 can only be accessed by API, and cannot be retrained/tuned. Training GPT-2 in a reasonable amount of time requires a GPU with a lot of memory, and fortunately Google Colab is a free hosted python notebook service that allows that.</p><p>For simplicity’s sake, we are simply generating fake tweets in a large batch, saving to JSON on Google Drive, and downloading the Google Drive folder with the twitter bot on AWS, and calling a pre-generated tweet.</p><p>To simplify things, we trained the classifier models beforehand and saved the pickled models in the GitHub repo along with the rest of the code to generate the classified csv files, and are going to download the full repo in the Google Colab notebook to train the generator models.</p><p>You can click on the Open in Colab button below to create the generator models for each candidate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/282bd9b5d4bce22a4d713a4c0214249e/href">https://medium.com/media/282bd9b5d4bce22a4d713a4c0214249e/href</a></iframe><h3>Create and deploy twitter bot</h3><p>We used python 3.7 to create a twitter bot that posts a tweet from a random candidate approximately every hour using the tweepy library. We found that posting regularly every hour got the account flagged after 3 tweets, randomizing it to a range of 50–60 minutes per tweet isn’t giving us any trouble at all.</p><ul><li>From the prior step, we saved the batched outputs of the GPT-2 model to json files in the form of a rudimentary database of sorts with the schema {index:full_text} with index as an incrementing int starting from 0, and full_text as a string containing the tweet content to be posted by the bot. These json files are saved in a Google Drive, and the bot lives on AWS inside a docker container. We first setup the file download process to the docker container during the build process. Since we saved the generated tweet files in Google Drive, we can make the files public and add them to the Dockerfile setup like so:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f8d61a9ffd51d4681328b00da037a59/href">https://medium.com/media/0f8d61a9ffd51d4681328b00da037a59/href</a></iframe><p>For the probiden.json and protrump.json generated files saved to Google Drive, make public links to those files so these can be downloaded when making the Docker image. Replace both fileid variables in the Dockerfile with the file IDs from the generated urls by using the alphanumeric ID after the d. For this Google Drive file:</p><p>https://drive.google.com/file/d/1hZSttFIKZqBiJ7u_8hiLlQMXr7J3wvSk/view</p><p>the fileid is: 1hZSttFIKZqBiJ7u_8hiLlQMXr7J3wvSk</p><p>Replace accordingly for both candidates.</p><p>The bot requires certain Twitter API developer credentials to run; CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, and ACCESS_TOKEN_SECRET . We will pass these as env variables into our docker container, and we setup the config.py script for the bot like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c93098dc5e7ea1fc2ffcb654aedc2da/href">https://medium.com/media/8c93098dc5e7ea1fc2ffcb654aedc2da/href</a></iframe><ul><li>Since we are not actually trying to mislead anyone, our Twitter account for the bot describes it as a bot and we are not generating content solely for one candidate. The bot main bot script randomly selects between candidates to support, read count_logger.json which keeps track of which tweets have been posted for either candidate, use that value to read the next un-posted tweet for the selected candidate, make a post to the twitter bot, then iterate the count in count_logger.json . The logic is located in tweet.py . Under the default settings, for every sample generated by GPT-2, there are an arbitrary number of tweets, separated by prefix, &lt;|startoftext|&gt;, and suffix, &lt;|endoftext|&gt;. The length parameter in the generate function may be playing a role, but we didn’t look into that. Some generated samples were also empty, so we modified our scripts accordingly. Also, this was a chance to practice a bit of recursion.</li></ul><p><strong>A brief overview of the the bot posting logic</strong></p><ul><li>Pre-generated tweets for a candidate have been saved to the local filesystem in the form: {index: generated text} to: probiden.json , protrump.json .</li><li>A file tracking the last posted tweet per candidate is saved in the form: count_logger.json .</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e449bd584eedf4a69467a12354fdf6/href">https://medium.com/media/62e449bd584eedf4a69467a12354fdf6/href</a></iframe><ul><li>At each randomized interval to post a tweet, a random candidate is selected, the next index of tweet to be posted is selected, the next tweet to post is parsed from the string, and if no viable tweet exists at that index, and the index is iterated up to the index generation limit.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da817c367b644c06e2d0213c1df15cfe/href">https://medium.com/media/da817c367b644c06e2d0213c1df15cfe/href</a></iframe><p>We later found out that GPT-2 has pre-generation capabilities that can be queried from a hosted REST endpoint; we could have also created used sqlite to query instead of a json, or used an actual database.</p><p><strong>Fulfilling Python library requirements</strong></p><p>We are using Docker to containerize the environment with the necessary lib versions under requirements.txt . The file can be generated by running pip freeze &gt; requirements.txt .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/513bed04bd1914f7b7c248e988697950/href">https://medium.com/media/513bed04bd1914f7b7c248e988697950/href</a></iframe><p><strong>Overview of Deployment Process</strong></p><ul><li>Spin up an AWS EC2 instance</li><li>Install Docker to EC2 instance</li><li>Compile local Docker image from Dockerfile</li><li>Compress and upload Dockerfile to EC2 instance</li><li>Start bot</li></ul><p>We can first structure the GitHub repository in this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea43b2d4ebdeb0354108d9ca8b56aad/href">https://medium.com/media/0ea43b2d4ebdeb0354108d9ca8b56aad/href</a></iframe><p>Then, we can build the Docker image.</p><p>While we are located in the ROOT directory containing the Dockerfile, run:</p><p>sudo docker build . -t tweet-bot</p><p>Then export the image:</p><p>sudo docker image save tweet-bot:latest -o tweet-bot.tar</p><p>Compress</p><p>gzip tweet-bot.tar</p><p>Then, spin up an EC2 instance</p><ul><li>Create/login to AWS dashboard</li></ul><p><strong>Navigate to the EC2 service</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*qycypxnCfo62BOIMHC7f7Q.png" /></figure><p><strong>Launch EC2 instance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*68-CWxDuF9tao-wnfVxn4g.png" /></figure><p><strong>Select Ubuntu Server 18.04 AMI</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*7-tecpOfbHWfjlfgaBwk-A.png" /></figure><p><strong>Select Nano Instance Type</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*MnxU9kC6s9Z5oL3OkXbbjg.png" /></figure><p><strong>Launch, and create and download key-pair</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*VSOQQq0VB8qPVTW8f-VBBg.png" /></figure><ul><li>change security settings for key</li></ul><p>chmod 400 tweet-bot-key.pem</p><ul><li>From your local machine, copy Docker image to the instance</li></ul><p>scp -i &quot;tweet-bot-key.pem&quot; tweet-bot.gar.gz ubuntu@AWS-my-DNS.com:/tmp</p><ul><li>SSH to EC2 instance</li></ul><p><strong>Access the address by selecting an EC2 instance from the dashboard and clicking on “Connect to EC2 Instance” and replace the </strong><strong>AWS-my-DNS.com below with your server address:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*XhAREOtix1lJ2BC3igG_Fw.png" /></figure><p>ssh -i &quot;tweet-bot-key.pem&quot; ubuntu@AWS-my-DNS.com</p><ul><li>Unzip image</li></ul><p>gunzip /tmp/tweet-bot.tar.gz</p><ul><li>Install Docker to instance</li></ul><p>sudo apt update &amp;&amp; apt install docker.io</p><p>sudo adduser ubuntu docker</p><ul><li>Load the image to Docker</li></ul><p>docker image load -i /tmp/tweet-bot.tar</p><ul><li>Run the image</li></ul><pre>docker run -d --restart always -e CONSUMER_KEY=&quot;YOUR_TWITTER_API_KEY&quot; \<br> -e CONSUMER_SECRET=&quot;YOUR_TWITTER_API_KEY_SECRET&quot; \<br> -e ACCESS_TOKEN=&quot;YOUR_TWITTER_API_ACCESS_TOKEN&quot; \<br> -e ACCESS_TOKEN_SECRET=&quot;YOUR_TWITTER_API_ACCESS_TOKEN_SECRET&quot; \<br> tweet-bot</pre><ul><li>Now the Docker container is running and should be posting tweets</li></ul><p>You can see some of the tweets the bot has made below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*km9TaHhPW7l7W-zR04XUlg.png" /></figure><p><strong>Project Review</strong></p><p>Somehow, our dataset includes RT text in the training samples and as a result almost all generated tweets have an RT in front of them as well as some having ‘…’ ending the tweet; a simple mistake to fix as that functionality is in our cleaning pipeline but we forgot to turn it on; however to fix it now requires retraining the generators and re-generating text, which can take several hours.</p><p>Additionally, some generated tweets are almost verbatim copies of training samples, which given the nature of twitter RTs, and general group-think on the platform means this does not feel like a major issue. However, it is an issue for a generator to generate verbatim content when the purpose is to generate novel content, and this requires looking into to determine the cause.</p><p>Our training methods for detecting sentiment for a particular candidate over another are flawed at best, given our baseline truth depends on manually annotated hashtags and cannot consider the content surrounding the Our training methods for detecting sentiment for a particular candidate over another are flawed at best, given our baseline truth depends on manually annotated hashtags and cannot consider the content surrounding the hashtag. However, given the time constraints to both research and provide a solution, we are satisfied with the results.</p><p>The deployment of the bot took awhile due to our lack of knowledge of Alpine, and in particular getting dependencies sorted out with Cairo; also, the image size ballooned up from 8MB to a zipped file size of over 300MB. This is fine for a single deployment on EC2, but is well above the size limit for any serverless deployments like on AWS Lambda, which would be useful for deploying at scale.</p><p>The generated tweets look overall fairly realistic and consistently seem to show support for one candidate or the other. We deployed to AWS on an automated account, and we completed the objective of exploring strongly biased political content generation on social media.</p><p>Future goals are:</p><ul><li>More advanced (more complete metric and a higher performing classification model) classification of twitter content</li><li>Higher quality generated content</li><li>Deployment at scale</li></ul><h3><strong>TL;DR</strong></h3><p><strong>We found it difficult to decide on a metric for candidate support on twitter text data</strong></p><p><strong>GPT-2 can generate realistic, if sometimes derivative content for Twitter</strong></p><p><strong>Overall, making a fake content Twitter bot is not that difficult nowadays with limited time and resources</strong></p><p><strong>CoAuthors</strong></p><ul><li><a href="https://www.linkedin.com/in/trevor-seguin/">Trevor Seguin - Postdoctoral Researcher - Berkeley Lab | LinkedIn</a></li><li><a href="https://www.linkedin.com/in/connorslagle/">Connor Slagle - Co-Founder and CTO - Advanced Microbubbles Inc | LinkedIn</a></li></ul><p><strong>Source code</strong></p><p><a href="https://github.com/cdesilv1/gDataThon_01_SHMICS">cdesilv1/gDataThon_01_SHMICS</a></p><p><strong>Resources</strong></p><ul><li><a href="https://realpython.com/twitter-bot-python-tweepy/">How to Make a Twitter Bot in Python With Tweepy - Real Python</a></li><li><a href="https://colab.research.google.com/drive/1qxcQ2A1nNjFudAGN_mcMOnvV9sF_PkEb">Google Colaboratory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f44db51beb9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>