<?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 Mauriciotorob on Medium]]></title>
        <description><![CDATA[Stories by Mauriciotorob on Medium]]></description>
        <link>https://medium.com/@mauriciotorob?source=rss-4d316c5b2933------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VHKGklej90k2mRQ_2GLb0w.jpeg</url>
            <title>Stories by Mauriciotorob on Medium</title>
            <link>https://medium.com/@mauriciotorob?source=rss-4d316c5b2933------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:10:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mauriciotorob/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[Building Trust in Machine Learning for Credit Scoring]]></title>
            <link>https://medium.com/@mauriciotorob/building-trust-in-machine-learning-for-credit-scoring-10379eb8ef14?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/10379eb8ef14</guid>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 12:54:16 GMT</pubDate>
            <atom:updated>2025-07-08T12:54:16.462Z</atom:updated>
            <content:encoded><![CDATA[<p>In a previous <a href="https://medium.com/@mauriciotorob/solution-to-a-take-home-exercise-for-building-a-credit-risk-model-as-part-of-a-technical-interview-047ea6a5b6e8">blog</a> I explained how to develop a model to predict the likelihood of a customer defaulting on their credit card balance within 12 months using provided datasets.</p><p>In this blog, with a series of 3 videos, I will explain how to build trust in a machine learning model predicting credit card default risk.</p><h3>How to present the classification results</h3><p>In this first video, I will focus on how to present the classification results. For those coming from a technical background, this is called the confusion matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Hvn4f35mDR5Iw7CblEOHw.png" /><figcaption>Example of. how to present the classification results</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOTeKZEHdITM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOTeKZEHdITM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOTeKZEHdITM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc92f673d8d74fe79c85e08877fd57dd/href">https://medium.com/media/cc92f673d8d74fe79c85e08877fd57dd/href</a></iframe><h3>How to present the top variables influencing the decision</h3><p>In this second video, I will focus on how to present the top variables influencing the outcome. For those coming from a technical background, this is called the Shapley values.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7-vlszS0nos%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7-vlszS0nos&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7-vlszS0nos%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4bf858c01eaec841b74d8cc166f09e4/href">https://medium.com/media/a4bf858c01eaec841b74d8cc166f09e4/href</a></iframe><h3>How to present the top business rules</h3><p>In this third video, I will focus on how to present the top business rules behind the model. For those coming from a technical background, these are the top 2 or 3 decision trees of an XGBoost model.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnlaH2xAHAT0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnlaH2xAHAT0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnlaH2xAHAT0%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/693c4bb57bab16b30bace58e0f7d6832/href">https://medium.com/media/693c4bb57bab16b30bace58e0f7d6832/href</a></iframe><h3>Conclusions</h3><p>Building a credit default model is just the start… helping people trust it is where the real impact begins. In this blog, we explored how to present the classification results (confusion matrix), explain key drivers (Shapley values), and human-friendly rules (top decision trees). Together, these steps help turn a black-box model into a tool business teams can trust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10379eb8ef14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Payment Processing Volumes with Machine Learning]]></title>
            <link>https://medium.com/@mauriciotorob/forecasting-payment-processing-volumes-with-machine-learning-d0417cb45a78?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0417cb45a78</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[forecast]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[payments-technology]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 12:09:57 GMT</pubDate>
            <atom:updated>2025-06-07T13:15:48.951Z</atom:updated>
            <content:encoded><![CDATA[<p>If your business processes payments for others, you probably want to predict next month’s volume for each merchant.</p><h3>A Common Method</h3><p>The go-to method? Rolling averages. Rolling averages are simple. Familiar. But also… misleading at times. They can’t see sudden growth. They forget seasonality. In this short video, I’ll walk you through the good, the bad, and the ugly of rolling averages… and how we can do better. So your team can plan ahead, worry less, and run smoother ops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3w6tBLOJ9iaVpVzGQDhUjQ.png" /><figcaption>The good, the bad and the ugly of rolling average to forecast processing payment volumes</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FOaMsX2Q0xVI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DOaMsX2Q0xVI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FOaMsX2Q0xVI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3e80998326de8b2a2e51cb1110607d4/href">https://medium.com/media/d3e80998326de8b2a2e51cb1110607d4/href</a></iframe><h3>A Machine Learning Solution</h3><p>In the next video, I explore how machine learning can help us forecast volumes more accurately, go beyond simple averages, and understand what variables really drive those predictions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFTORNse1xYU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFTORNse1xYU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFTORNse1xYU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c50d87dfda144676a6947803405b239/href">https://medium.com/media/3c50d87dfda144676a6947803405b239/href</a></iframe><h3>Risks of Machine Learning</h3><p>In this last video, I dive into the potential risks of relying on machine learning for payment volume forecasts because technology is powerful but it is not without challenges…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTt-BZV9B1x8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTt-BZV9B1x8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTt-BZV9B1x8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4497d1a738f416cccc232ed5bd398f70/href">https://medium.com/media/4497d1a738f416cccc232ed5bd398f70/href</a></iframe><h3>Conclusions</h3><p>Simple heuristics like moving averages are common in forecasting payment volumes, offering simplicity but limited precision. Machine learning often improves accuracy, but it introduces new risks that must be carefully managed with robust strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0417cb45a78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scrum Up Some Laughter: Generating Rugby Jokes with DeepSeek R1 & Llama 8B]]></title>
            <link>https://medium.com/@mauriciotorob/scrum-up-some-laughter-generating-rugby-jokes-with-deepseek-r1-llama-8b-cc987b9d1108?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc987b9d1108</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[jokes]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rugby]]></category>
            <category><![CDATA[deepseek-r1]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 18:10:01 GMT</pubDate>
            <atom:updated>2025-01-29T18:55:12.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*3_rzND46kZcamFAOGInj6g.png" /></figure><p>In this blog, we’ll explore how to use <a href="https://ollama.com/library/deepseek-r1">DeepSeek R1</a>, an enhanced version of the Llama 8B model, to transform live rugby match commentary into a series of jokes. The goal is to take real-time commentary, generate some AI-powered humor, and combine everything into an entertaining experience. By the end, we’ll have a complete video that syncs the jokes with lively text-to-speech narration, paired with a single static image.</p><p>We’ll begin by setting up the necessary tools and models, making sure you have everything you need to get started. Once that’s done, we’ll move on to importing the required libraries and defining the helper functions that will make the process smoother. Afterward, we’ll fetch live rugby commentary data, which will serve as the foundation for generating our jokes.</p><p>Using DeepSeek R1 with the Llama 8B model, we’ll inject humor into the commentary, turning it into entertaining jokes. Then, we’ll use Coqui’s text-to-speech model to bring those jokes to life, turning the written text into audio. Finally, we’ll merge a static image with the generated audio to create a fun and engaging video using FFmpeg.</p><p>Let’s dive in and bring this creative project to life!</p><h3>Required Libraries</h3><p>In this section, the code ensures that the environment is properly set up with the necessary libraries and models. First, it upgrades pip to the latest version to avoid compatibility issues. Then, it installs three key libraries: ollama, TTS, and pydub. Ollama allows access to the Ollama platform for pre-trained models like DeepSeek R1, TTS is used for text-to-speech conversion, and pydub helps manipulate audio files. The command ollama pull deepseek-r1:8b downloads the pre-trained DeepSeek R1 model, which is based on Llama 8B and designed for generating text like jokes from rugby commentary. Finally, the command ollama show deepseek-r1:8b provides metadata and details about the model to verify that it has been successfully downloaded and is ready for use in the project.</p><pre>!pip install --quiet --upgrade pip<br>!pip --quiet install ollama TTS pydub<br>!ollama pull deepseek-r1:8b<br>!ollama show deepseek-r1:8b</pre><p>This code imports several libraries for different tasks. ollama is used to interact with the DeepSeek R1 model, while pandas handles data frames. re helps clean the model’s output, and TTS.api converts text into speech. pydub exports audio from WAV to MP3, and IPython.display manages audio and video playback in Jupyter. io and sys capture TTS output, and subprocess calls ffmpeg to combine audio and video. Lastly, Video from IPython.display displays the final video in Jupyter.</p><pre>import ollama # To call the deepsearch model<br>import pandas as pd # To use a dataframe<br>import re # To manage regexes to clean the output of the model<br>from TTS.api import TTS # To transform text into voice<br>from pydub import AudioSegment # To export the audio in wav format into mp3<br>from IPython.display import Audio, display # To listen to the voice in Jupyter<br>import io # To capture TTS output<br>import sys # To capture TTS output<br>import subprocess # To call ffmpeg and make a video<br>from IPython.display import Video # To display the video</pre><p>This sets up everything required for generating jokes and working with audio.</p><h3>Scraping Live Commentary from Premiership Rugby</h3><p>This code defines a link to a live rugby match commentary and creates a list, live_commentary, containing timestamped events during the game, such as tries, penalties, and substitutions. It is left as an exercise to the reader to scrap information from the website. The information includes details about the time, score, team, event, and player involved. The list is then converted into a Pandas DataFrame, live_commentary_df, for easy manipulation and analysis.</p><pre>game_link = &quot;https://www.premiershiprugby.com/match-centre/283210/live-commentary&quot; # To do: Scrap information from the website<br>team_1 = &#39;Sale Sharks&#39;<br>team_2 = &#39;Bath Rugby&#39;<br>live_commentary = [<br>                   [&#39;14&#39;, &#39;0-0&#39;, team_1, &#39;Missed Penalty!&#39;, &#39;Robert du Preez&#39;],<br>                   [&#39;17&#39;, &#39;5-0&#39;, team_1, &#39;Try!&#39;, &#39;Arron Reed&#39;],<br>                   [&#39;18&#39;, &#39;5-0&#39;, team_1, &#39;Missed conversion!&#39;, &#39;Robert du Preez&#39;],<br>                   [&#39;22&#39;, &#39;8-0&#39;, team_1, &#39;Penalty!&#39;, &#39;Robert du Preez&#39;],<br>                   [&#39;24&#39;, &#39;8-5&#39;, team_2, &#39;Try!&#39;, &#39;Ruaridh McConnochie&#39;],<br>                   [&#39;25&#39;, &#39;8-5&#39;, team_2, &#39;Missed conversion!&#39;, &#39;Finn Russell&#39;],<br>                   [&#39;26&#39;, &#39;8-5&#39;, team_1, &#39;Sub Off&#39;, &#39;Willgriff John&#39;],<br>                   [&#39;26&#39;, &#39;8-5&#39;, team_1, &#39;Sub On&#39;, &#39;Tye Raymont&#39;],<br>                   [&#39;27&#39;, &#39;13-5&#39;, team_1, &#39;Try!&#39;, &#39;Robert du Preez&#39;]<br>                  ]<br>live_commentary_df = pd.DataFrame(live_commentary, columns = [&#39;time&#39;, &#39;score&#39;, &#39;team&#39;, &#39;event&#39;, &#39;player&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFH2DzT6S0qQtM-X8163bg.png" /><figcaption>Data frame of the parsed live commentary of a Rugby match.</figcaption></figure><h3>AI-Generated Jokes from Live Commentary</h3><p>This part requires three functions. The first, call_chat, interacts with the Ollama chat model, sending a user prompt and receiving a response with specific parameters such as temperature and seed for randomness. It processes the output and returns the chat response content. The second function, remove_think_tags, removes any text enclosed within &lt;think&gt; and &lt;/think&gt; tags using a regular expression. The third function, extract_first_inside_quotes, extracts the first string of text enclosed within double quotes from the input string using a regular expression, returning it.</p><pre>def call_chat(model_name, prompt):<br>    # Calls a chat with a prompt<br>    output =  ollama.chat(model=model_name, messages=[<br>            {<br>             &#39;role&#39;: &#39;user&#39;,<br>             &#39;temperature&#39;: 0,<br>             &#39;seed&#39;: 42,<br>             &#39;top_p&#39;:0.5,<br>             &#39;content&#39;: prompt,<br>             },])[&#39;message&#39;][&#39;content&#39;]<br>    return output<br><br>def remove_think_tags(input_string):<br>    # Regular expression to match text between &lt;think&gt; and &lt;/think&gt;<br>    cleaned_string = re.sub(r&#39;&lt;think&gt;.*?&lt;/think&gt;&#39;, &#39;&#39;, input_string, flags=re.DOTALL)<br>    return cleaned_string<br><br>def extract_first_inside_quotes(input_string):<br>    # Use regular expression to find the first content inside quotes<br>    match = re.search(r&#39;&quot;([^&quot;]*?)&quot;&#39;, input_string, re.DOTALL)<br>    if match:<br>        return match.group(1)<br>    return input_string</pre><p>The next code generates jokes based on live rugby commentary using the DeepSeek R1 AI model. It first sets up the game title and iterates over each row in the live_commentary_df DataFrame, which contains details of the match. For each row, it creates a prompt for the AI, asking it to forecast a humorous event in the game based on the current commentary. The AI’s response is cleaned by removing unnecessary tags and extracting the joke. The event description and joke are then printed and stored in the ia_output list for further use.</p><pre>game_title = f&quot;{team_1} Versus {team_2} a Rugby Match&quot;<br>print (game_title)<br>ia_output = []<br>for _, row in live_commentary_df.iterrows(): <br>    prompt = f&quot;You are an assitant to a UK based comedian. You are going to make a joke uses UK slangs and dark humor and it is a forecast of what is going to happen in Rugby gamein the following minutes based on a live comment that I will give you. So, make a joke about the following comment:  Team 1 is {team_1} and team 2 is {team_2}. At time {row[&#39;time&#39;]},the score is {row[&#39;score&#39;]} and team {row[&#39;team&#39;]}, player {row[&#39;player&#39;]} did {row[&#39;event&#39;]}. You will only reply with a joke, only a joke to forecast what is going to happen in the next minutes based on the event. Only a joke, that is it.&quot;<br>    event_description = f&quot;-&gt; At time {row[&#39;time&#39;]}, the score is {row[&#39;score&#39;]} and team {row[&#39;team&#39;]}, player {row[&#39;player&#39;]} did a {row[&#39;event&#39;]}&quot;<br>    print(event_description)<br>    chat_output = call_chat(&quot;deepseek-r1:8b&quot;,prompt)<br>    chat_output_without_think_tags = extract_first_inside_quotes(remove_think_tags(chat_output))<br>    print(&quot;----&gt; &quot;+chat_output_without_think_tags )<br>    ia_output += [(event_description, chat_output_without_think_tags)]</pre><h3>Combine Comments and Jokes into One Audio File</h3><p>This code requires two functions. The first, extract_bracket_content(text), uses a regular expression to extract the content inside the first pair of square brackets in a string, returning it after removing extra spaces. The second function, create_wav(filename, input_text), converts the input text into a .wav audio file using a Text-to-Speech model. It captures the printed output from the TTS process, extracts any content within square brackets, and returns the list of sentences generated by the TTS system.</p><pre>def extract_bracket_content(text):<br>    &quot;&quot;&quot;Extracts content inside the first pair of square brackets [ ] from a given string.&quot;&quot;&quot;<br>    match = re.search(r&#39;\[(.*?)\]&#39;, text, re.DOTALL)  # DOTALL allows newlines inside brackets<br>    return match.group(1).strip() if match else None  # Remove extra spaces &amp; return<br><br>def create_wav(filename, input_text):<br>    #Convert text into wav audio, and return the splitted sentences that were generated by TTS<br>    # Capture the printed output<br>    captured_output = io.StringIO()  # Create a StringIO object<br>    sys.stdout = captured_output  # Redirect stdout to the StringIO object<br>    tts.tts_to_file(text=input_text, speaker=&quot;p243&quot;, file_path=filename+&quot;.wav&quot;)  # Call the function<br>    sys.stdout = sys.__stdout__  # Reset stdout back to default<br>    # Get the captured text<br>    output_text = captured_output.getvalue()<br>    return list(eval(extract_bracket_content(output_text)))</pre><p>This code first constructs the comments_and_jokes_text by combining the game title with the event descriptions and jokes from the ia_output list. Then, the text-to-speech (TTS) model tts_models/en/vctk/vits is initialized using the TTS library to convert the text into speech, generating a .wav file named output.wav. After the audio is generated, it is loaded using pydub’s AudioSegment and exported as an .mp3 file. Once the conversion is complete, the generated .mp3 file is displayed for playback in the Jupyter notebook using the IPython.display.Audio class.</p><pre>comments_and_jokes_text = game_title + &quot; &quot;<br>for event_description, chat_output_without_think_tags in ia_output:<br>    comments_and_jokes_text += event_description + &quot; &quot; + chat_output_without_think_tags + &quot; &quot;<br><br>model_name = &quot;tts_models/en/vctk/vits&quot;<br># Init TTS<br>tts = TTS(model_name)<br>filename = &quot;output&quot;<br>splitted_sentences = create_wav(filename,comments_and_jokes_text )<br><br># Load the .wav file<br>audio = AudioSegment.from_wav(filename+&quot;.wav&quot;)<br># Export as .mp3<br>audio.export(filename+&quot;.mp3&quot;, format=&quot;mp3&quot;)<br>print(&quot;Conversion to MP3 completed!&quot;)<br><br># Display the MP3 file<br>display(Audio(filename+&quot;.mp3&quot;))</pre><h3>Generate a video using an image and the audio</h3><p>This code uses ffmpeg through a subprocess to create a video by combining an image and an audio file. It sets parameters like looping the image, specifying frame rate and codecs, and ensuring the video length matches the audio. After executing the command, it saves the output as an MP4 file and displays the video in a Jupyter notebook.</p><pre># Input files (image and audio)<br>image_path = &#39;deepseek.png&#39;  # Path to the image file<br>audio_path = &#39;output.mp3&#39;    # Path to the audio file<br>output_video_path = &#39;output_video.mp4&#39;  # Path to the output video file<br><br># Command to create a video from image and audio using ffmpeg<br>command = [<br>    &#39;ffmpeg&#39;, <br>    &#39;-loop&#39;, &#39;1&#39;,  # Loop the image<br>    &#39;-framerate&#39;, &#39;2&#39;,  # Set the frame rate (2 fps is fine for a static image)<br>    &#39;-i&#39;, image_path,  # Input image<br>    &#39;-i&#39;, audio_path,  # Input audio<br>    &#39;-c:v&#39;, &#39;libx264&#39;,  # Video codec<br>    &#39;-tune&#39;, &#39;stillimage&#39;,  # For still image video<br>    &#39;-c:a&#39;, &#39;aac&#39;,  # Audio codec<br>    &#39;-strict&#39;, &#39;experimental&#39;,  # For some ffmpeg versions<br>    &#39;-shortest&#39;,  # The video length will be the same as the audio<br>    output_video_path  # Output video file<br>]<br><br># Run the command<br>subprocess.run(command)<br>print(f&quot;Video saved at {output_video_path}&quot;)<br><br># Display the video in Jupyter<br>Video(&quot;output_video.mp4&quot;)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTX3UjQ_pbGI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTX3UjQ_pbGI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTX3UjQ_pbGI%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a53f027c492e1aa09cff78753e6c76ec/href">https://medium.com/media/a53f027c492e1aa09cff78753e6c76ec/href</a></iframe><h3>Conclusions</h3><p>In this project, we took live rugby match commentary, used AI to generate jokes based on each comment, and then combined the commentary and jokes into a single text. This text was converted to speech and turned into a video. All of this was accomplished using open-source tools like DeepSeek’s improved Llama model, FFmpeg, Jupyter, and Coqui TTS. This showcases the power of open-source software in creating innovative solutions, and anyone can try it out themselves!</p><p>The notebook is available in this Github <a href="https://github.com/mauriciotoro/deepseek-rugby-jokes">repository</a>. Try it out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc987b9d1108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can AI Revolutionise Systematic Literature Reviews?]]></title>
            <link>https://medium.com/@mauriciotorob/can-ai-revolutionise-systematic-literature-reviews-8b8f0ba7e321?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b8f0ba7e321</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[scientific-research]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[systematic-review]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 15:01:10 GMT</pubDate>
            <atom:updated>2024-09-30T16:16:36.761Z</atom:updated>
            <content:encoded><![CDATA[<p>Researchers from the University of Bath recently conducted a systematic literature review on business compliance. Led by first author Andrea Serna, they began with a clear objective:</p><blockquote><strong>“</strong>Identify the policy and regulatory topics where business compliance has been studied, the data and modelling strategies employed and the variables included, the sign and significance of their impact.<strong>”</strong></blockquote><p>This blog will explore the extent to which AI can streamline the extensive review process.</p><blockquote><strong>The Big Question: How Much of This Process Can Be Automated with AI, Specifically Llama 3.1 8B?</strong></blockquote><h3>Human-Made Systematic Literature Review</h3><p>From the main objective, the researchers generated a set of synonyms to expand their search criteria, crafting a search string:</p><pre>  (  business* OR <br>     enterprise* OR  <br>     firm* OR <br>     organisation* OR <br>     corporation* OR <br>     compan*<br>   ) <br>   AND <br>   (  variable OR <br>      characteristic OR <br>      attribute<br>   ) <br>   AND <br>   (<br>      compliance OR <br>      adherence OR <br>      concordance OR <br>      conform* OR <br>      fulfilment OR <br>      accordance OR <br>      noncompliance<br>   ) <br>   AND <br>   (<br>      regulation* OR <br>      policy OR <br>      measure* OR <br>      law* OR <br>      standard* OR <br>      rule OR <br>      statute* OR <br>      legislation* OR <br>      decree* OR <br>      guideline*<br>   )</pre><p>This search was conducted across prominent databases — EconLit, Business Source Complete, Web of Science and Scopus — yielding an impressive ~<strong>15,000 articles</strong>.</p><p>Next came a screening phase, where the team read manually keywords to filter out content that was not related to the main objective, ultimately narrowing their selection down to ~<strong>8,000 articles</strong>.</p><p>After, they applied nine (9) inclusion criteria leading them to a refined set of ~<strong>262 articles</strong>.</p><pre>1. Is the topic related to the research question?  <br>2. Was the document published within 2017-2022? <br>3. Is the document written in English?  <br>4. Is the source of the article a scholarly journal?  <br>5. Is the document and academic article? <br>6. Is the study within the domain of business and economics? <br>7. Does the article include data analysis?  <br>8. Is the unit of data analysis the business?  <br>9. Is the location of the study a developed country?</pre><p>After the inclusion criteria, the application of ten (10) exclusion criteria through reading of the full texts revealed ~<strong>150 articles</strong> that were most relevant to their analysis.</p><pre><br>1. Not about compliance<br>2. Not a data analysis article<br>3. No quartile or ABS category<br>4. Does not include data at the business level<br>5. Reverse causality<br>6. Article not available<br>7. Case Study<br>8. It&#39;s about state owned enterprises<br>9. The analysis included developing countries<br>10. About consequences not causes</pre><p>Their systematic approach didn’t stop there. The researchers aimed to determine key topics where business compliance has been studied, the data and modelling strategies employed, the variables studied, and the sign and statistic significance of each variable. Their findings were summarised with figures and tables, culminating in an article.</p><h3>AI Review Process</h3><p>Our goal in this blog is to automate the systematic literature review process performed by the authors using AI. We break it down into four parts.</p><p>• <strong>Part 1: Assessing Article Compliance with Search Criteria</strong></p><p>• <strong>Part 2: Filtering Out Articles with Inclusion Criteria</strong></p><p>• <strong>Part 3: Filtering Out Ineligible Articles</strong></p><p>• <strong>Part 4: Extracting Information from the Articles</strong></p><h3><strong>Assessing Article Compliance with Search Criteria</strong></h3><p>In this first part, we will discuss the initial step: analysing whether articles truly comply with the defined search string.</p><p>To identifying relevant scientific articles using Llama 3.1 8B, the first step in our process involves importing the necessary libraries and defining helper functions. Next, we will load the dataset containing information about the articles. Following that, we will select articles that meet the criteria of a search string and compare the results to the human labels.</p><p>All these steps are executed within a Jupyter notebook, which you can access at <a href="https://github.com/mauriciotoro/ai-systematic-literature-review">https://github.com/mauriciotoro/ai-systematic-literature-review</a>.</p><p>Let’s dive into each of these steps in detail!</p><h3>Libraries and Helper Functions</h3><p><strong>Importing Libraries: </strong>In the first step, various libraries are imported for text processing, data manipulation, and interaction with the AI model. The <strong>ollama</strong> library allows integration with the LLaMA 3.1 model, enabling us to use its advanced capabilities. <strong>pandas</strong> is included for data manipulation and analysis, as it offers robust functionality for working with structured data in tabular form. <strong>pickle</strong> allows saving and loading objects, making it easier to persist data, while <strong>tqdm</strong> provides a simple way to visualise progress bars during long-running tasks. Lastly, <strong>matplotlib</strong> is used to plot a Venn diagram comparing AI and human labels.</p><pre>import ollama<br>import os<br>import pandas as pd<br>import pickle<br>from tqdm import tqdm<br>import matplotlib.pyplot as plt<br>from matplotlib_venn import venn2<br>from matplotlib import rcParams</pre><p><strong>AI Model and Progress Tracking: </strong>This script enables progress tracking by integrating <strong>tqdm</strong> with pandas. Next, it pulls the latest version of the LLaMA 3.1 model using <strong>ollama.pull</strong>, ensuring the AI model is up-to-date and ready for use. The <strong>ollama.list</strong> command retrieves a list of all available models, allowing the user to confirm that LLaMA 3.1 is installed.</p><pre># Enable progress_apply for pandas<br>tqdm.pandas()<br><br># Pull the LLaMa 3.1 model<br>ollama.pull(&#39;llama3.1:latest&#39;)<br><br># Get the list of available models<br>ollama.list()</pre><p><strong>The Search String: </strong>the <strong>search_string</strong> is defined to guide the AI model in identifying relevant articles.</p><pre>search_string = &quot;&quot;&quot;<br>determine the variables, factors, characteristics or attributes <br>of <br>quantitative studies, empirical research, statistical research or data-driven research<br>that <br>influence <br>compliance, adherence, concordance, conformity, fulfilment, accordance or noncompliance behaviour <br>of <br>business, enterprise, firm, organisation, corporation or company  <br>to <br>regulation, policy, measure, law, standard, rule, statute, legislation, decree or guideline<br>in<br>Canada, United States, Austria, Belgium, Denmark, Finland, France, Germany, Greece, <br>Ireland, Italy, Luxembourg, Netherlands, Portugal, Spain, Sweden, United Kingdom, <br>Bulgaria, Croatia, Cyprus, Czechia, Estonia, Hungary, Latvia, Lithuania, Malta ,<br>Poland, Romania, Slovakia, Slovenia, Iceland, Norway, Switzerland, Canada,<br>France, Germany, Italy, Japan, United Kingdom, United States, Australia, Japan or New Zealand<br>&quot;&quot;&quot;</pre><p><strong>Functions for AI Interaction: </strong>Two functions are defined to facilitate interaction with the LLaMA 3.1 model. The <strong>call_chat</strong> function sends a prompt to the AI model and retrieving its response. Parameters such as <strong>temperature</strong> and <strong>top_p</strong> control the AI’s response randomness and diversity, making it more tailored to specific needs. The <strong>select_article</strong> function uses <strong>call_chat</strong> to determine whether a given article complies with the search string. By appending the search criteria to the article’s text, it asks LLaMA 3.1 to return either “True” or “False,” indicating compliance.</p><pre>def call_chat(model_name, prompt):<br>    output =  ollama.chat(model=model_name, messages=[<br>            {<br>             &#39;role&#39;: &#39;user&#39;,<br>             &#39;temperature&#39;: 0,<br>             &#39;seed&#39;: 42,<br>             &#39;top_p&#39;:0.5,<br>             &#39;content&#39;: prompt,<br>             },])[&#39;message&#39;][&#39;content&#39;]<br>    return output<br><br>def select_article(article_text, search_string):<br>    chat_output = call_chat(&quot;llama3.1&quot;, article_text + f&quot;You are a virtual assistant. Based on the previous scientific article, return True if the previous article complies with the following search string; otherwise, return False. This is the search string: &quot;+search_string+ &quot; You will only say True or False, no explanations&quot; )<br>    chat_output = chat_output.replace(&quot;.&quot;, &quot;&quot;) <br>    chat_output = chat_output if chat_output.lower() in [ &#39;true&#39;,&#39;false&#39;] else &#39;False&#39;<br>    return chat_output</pre><h3>Data Processing</h3><p><strong>Preparing the Dataset: </strong>In this step, the script loads the dataset containing scientific articles from an Excel file named “Original_dataset_2017_2022.xlsx” using the pandas library. It specifies the <strong>path</strong> to the file and uses <strong>pd.read_excel</strong> to read the content into a DataFrame called <strong>articles</strong>. The DataFrame is then filtered to retain only the relevant columns: <strong>Title</strong>, <strong>Abstract</strong>, <strong>Keywords</strong>, <strong>DOI</strong>, and <strong>Screened</strong>. The latter column “screened” means if the researchers selected or not the article after reviewing the keywords. The <strong>fillna(””)</strong> function replaces any missing values with empty strings, ensuring that subsequent operations do not encounter issues due to missing data.</p><pre>articles = pd.read_excel(os.path.join(path,&quot;Original_dataset_2017_2022.xlsx&quot;))<br>articles = articles[ [&quot;Title&quot;, &quot;Abstract&quot;, &quot;Keywords&quot;, &quot;DOI&quot;, &#39;Screened&#39;] ]<br>articles.fillna(&quot;&quot;, inplace=True)</pre><p><strong>Combining Text Data: </strong>Next, a new column named <strong>Text</strong> is created in the <strong>articles</strong> DataFrame. This column combines the <strong>Title</strong>, <strong>Abstract</strong>, and <strong>Keywords</strong> for each article into a single text string, separated by periods. This concatenation process results in a comprehensive block of text for each article, which provides the AI model with a complete representation of the article’s content better than just the keywords.</p><pre>articles[&#39;Text&#39;] = articles[&#39;Title&#39;] + &quot;. &quot; + articles[&#39;Abstract&#39;] + &quot;. &quot; + articles[&#39;Keywords&#39;] + &quot;. &quot;</pre><h3>Article Selection</h3><p><strong>Identify Relevant Articles: </strong>In this step, the script uses the <strong>progress_apply</strong> method to evaluate each article’s relevance based on the previously defined search criteria. By applying the <strong>select_article</strong> function to every row in the <strong>Text</strong> column of the <strong>articles_df</strong> DataFrame, it determines whether each article meets the search string requirements. The resulting values, either “True” or “False,” are stored in a new column called <strong>Selected</strong> within the DataFrame, indicating whether each article complies with the search string. The <strong>%%time</strong> command at the start measures the total execution time of this process, helping track performance.</p><pre>%%time<br>articles_df.loc[:, &#39;Selected&#39;] = articles_df[&#39;Text&#39;].progress_apply(lambda article_text : select_article(article_text, search_string))</pre><p>Finally, the updated DataFrame is exported to an Excel file named “selected_articles_by_llm.xlsx”</p><pre>articles_df.to_excel(&quot;selected_articles_by_llm.xlsx&quot;, index=False)</pre><h3>Comparison to Human Labels</h3><p>This code snippet generates a Venn diagram to visually compare the overlap between articles selected by an AI model (Llama 3.1) and those screened by human researchers. First, it calculates the counts for three categories: articles selected by the AI but not screened by researchers, articles selected by both, and those screened by researchers but not selected by the AI.</p><pre># Sample data: replace these values with your actual numbers<br>selected_not_in_screening = len(articles_df[(articles_df[&#39;Screened&#39;]== False)&amp;(articles_df[&#39;Selected&#39;]==True)])  # Example: number of Selected articles not in Screening<br>selected_intersected = len(articles_df[(articles_df[&#39;Screened&#39;]== True)&amp;(articles_df[&#39;Selected&#39;]==True)])  # Example: number of Selected Articles that are intersected with Screening<br>screening_not_selected = len(articles_df[(articles_df[&#39;Screened&#39;]== True)&amp;(articles_df[&#39;Selected&#39;]==False)])  # Example: number of Screening not Selected</pre><p>It then uses these counts to draw the Venn diagram, with each subset represented by a different color for clarity.</p><pre># Create the Venn diagram<br>plt.figure(figsize=(10, 6))<br><br># Define the sets for the Venn diagram<br>venn_values = (selected_not_in_screening, screening_not_selected, selected_intersected)<br><br># Draw the Venn diagram<br>venn = venn2(subsets=venn_values, set_labels=(&#39;Selected by LLM&#39;, &#39;Selected by Researchers&#39;))<br></pre><p>Finally, it customises the font, colours, and title to make the visualisation more engaging and insightful.</p><pre># Customize colors<br>venn.get_patch_by_id(&#39;10&#39;).set_color(&#39;#FF9999&#39;)  # Selected by LLM<br>venn.get_patch_by_id(&#39;01&#39;).set_color(&#39;#99CCFF&#39;)  # Screened by Researchers<br>venn.get_patch_by_id(&#39;11&#39;).set_color(&#39;#FFFF99&#39;)   # Intersection color<br><br># Customize font properties<br>rcParams[&#39;font.family&#39;] = &#39;sans-serif&#39;<br>rcParams[&#39;font.sans-serif&#39;] = [&#39;Comic Sans MS&#39;, &#39;Helvetica&#39;]<br>plt.title(&#39;Venn Diagram of Selected Articles: Llama 3 Vs Researchers&#39;, fontsize=24, fontweight=&#39;bold&#39;)<br><br># Add grid and show the plot<br>plt.grid(False)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DgLmAJSN7jb2R77p-QwfQw.png" /><figcaption>Venn Diagram of Selected Articles</figcaption></figure><h3>Conclusions and Next Steps</h3><p>In our experiment with Llama 3.1 8B, we tasked the model with determining whether the combination of an article’s title, abstract, and keywords matched a specific search string. This step was crucial because conventional search engines like Scopus often miss relevant details.</p><p>Previously, researchers manually reviewed the keywords of around 15,000 scientific articles, ultimately filtering down to 8,000 — a time-consuming process. With AI, we automated this step by feeding Llama the concatenated text and asking if it met the search criteria. Interestingly, the results showed that Llama agreed with researchers on about 30% of the selections, another 45% were articles that the researchers included but Llama excluded, and the remaining 25% were articles selected by Llama but not by researchers. Due to the large volume, it isn’t feasible to manually evaluate all discrepancies between the two methods.</p><p>In the next part of this blog, we will explore how Llama handles applying the nine inclusion criteria to the pre-selected articles. We’ll assess whether this task is executed more effectively than the initial selection process covered here. Stay tuned as we examine how AI fares in filtering articles according to these criteria across both the researcher-defined subset and Llama’s own selections!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b8f0ba7e321" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solution to a take-home exercise for building a credit risk model as part of a technical interview]]></title>
            <link>https://medium.com/@mauriciotorob/solution-to-a-take-home-exercise-for-building-a-credit-risk-model-as-part-of-a-technical-interview-047ea6a5b6e8?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/047ea6a5b6e8</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[credit-score]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 14:06:11 GMT</pubDate>
            <atom:updated>2024-09-16T15:08:49.745Z</atom:updated>
            <content:encoded><![CDATA[<p>When tackling a take-home exercise for a technical interview, I focus on creating a minimum viable product in 8 hours. I split it into two 4-hour sessions, ensuring that in 8 hours, I cover everything: business understanding, data prep, model building, evaluation, explanation for non-technical audiences, deployment, and final conclusions.</p><p>In this blog, imagine receiving the following assignment description via email: Develop a model to predict the likelihood of a customer defaulting on their balance within 12 months using provided datasets. You’ll build a classifier using X_train and y_train for training, and X_test and y_test for evaluation. The datasets contain anonymised features from a financial company with some missing values, as well as a pre-trained model score (score_1) that can be incorporated into training or used as a benchmark. The account_id column is used to match features and labels. You’ll need to submit your code, a model file, and visualisations to explain your approach. Evaluation will focus on coding standards, model performance, and suggestions for improvements if the data wasn’t anonymized.</p><p>To solve this take-home exercise, I created a single Jupyter notebook, available in this <a href="https://github.com/mauriciotoro/credit_risk_interview/tree/main">GitHub repository</a>. The notebook is organised into the following sections: 1) Business Understanding, 2) Exploratory Data Analysis, 3) Modelling and Evaluation, 4) Deployment, and 5) Conclusions.</p><p>In the rest of this blog, I explain how I approach each section, what I include, and share my recommendations and considerations throughout the process.</p><h3>1 Business Understanding</h3><p>The first step is to clearly explain the goal, input, output, and constraints of the task in your own words. I recommend using Markdown to structure this explanation as part of your Jupyter Notebook. For example, when explaining the datasets, I include a section like this:</p><pre>## Datasets Description<br><br>You are provided with four datasets:<br>- `X_train.csv`<br>- `X_test.csv`<br>- `y_train.csv`<br>- `y_test.csv`<br><br>These datasets contain features and labels, respectively. <br>Your task is to fit a classifier using the training set and reserve the test set only for evaluation. You may choose any classification algorithm.<br><br>- **`X_train.csv`** and **`X_test.csv`** contain the features received from a Credit Bureau Provider at the time of the application:<br>  - Feature names are anonymized and tagged based on the metric they are relevant to, e.g., `utilization_1`, `utilization_2`, etc.<br>  - Some noise has been added to each feature.<br>  - The first column (`account_id`) is a unique identifier of each account. Use this to match rows between `X` and `y` datasets.<br>  - The feature `score_1` is a score from a pre-trained model provided with the rest of the features. You may incorporate this score into the training process and/or use it as a benchmark during the evaluation phase.<br>  - Features may contain `NaN` values indicating the absence of information or an event. For example, `recency_1` measures how many months have passed since an event in the applicant’s repayment history; if the event never took place, the value will be `NaN`.<br><br>- **`y_train.csv`** and **`y_test.csv`** contain the labels:<br>  - The value `1` indicates that the account defaulted within the first 12 months after acquisition. These can be joined with the feature set using the `account_id` column.</pre><p>In the second step, you should contact a person from the interview — typically a senior data scientist or tech lead — as ask them questions about the task. This information is integrated into the Business Understanding section of your Jupyter Notebook.</p><p>Here’s an example of how to structure this:</p><pre>## Questions &amp; Answers<br><br><br>####  1. How do you plan to use the probability output? Are you thinking of offering a treatment to those with high probabilities of ceasing payments? What about those with low probabilities? Do you need a calibrated probability, or would a score be enough?<br><br>- While a score alone is sufficient, it is beneficial to explain the advantages of a well-calibrated probability and its potential uses.<br><br><br>#### 2. What infrastructure are you considering for deploying this model? Do you envision using a smaller CPU machine, or would it be worth deploying on a larger machine with a GPU for deep learning in case deep learning proves to be better than a traditional machine learning approach?<br><br>- Do not worry about infrastructure for now. Keep in mind that this is a high-materiality model, meaning it will have a financial impact on customers.<br><br><br>#### 3. Do you have an estimate of the costs associated with misclassifying someone as likely to cease paåyments versus not likely to cease payments?<br><br>- You do not need to make assumptions about the costs associated with a defaulted account. This is a unit-rate model. However, provide notes on how you would handle it if you had the loss associated with a defaulted account.<br><br><br>####    4.    Which business metric or KPI will be most impacted by this prediction?<br><br>- Document which KPIs are impacted by a model applied during a credit card application process and identify the most important KPI for a credit card company.</pre><h3>2 Exploratory Data Analysis</h3><p>My first recommendation is to keep this section brief and focused. Given the 8-hour timeframe, prioritise modelling, and provide only essential data analysis tasks to stay aligned with the modelling steps.​</p><p>I like to start this section by installing the required libraries, then importing them with explanations for each one. Next, I define global constants, such as the company’s brand colors for plots, and outline the notebook in a clear, hierarchical format. I also include helper functions, like those for summarizing missing values or plotting ROC curves. It’s important to ensure that all functions, libraries, and constants are utilized later in the notebook.</p><p>As an example, these are the required libraries:</p><pre>!pip install --quiet pandas scikit-optimize xgboost shap pywaffle graphviz<br><br>import pandas as pd #This library is used for data understanding and preparation<br>import os #To handle paths in a way that is portable<br>from sklearn.metrics import confusion_matrix #Confusion matrix for model evaluation<br>from sklearn.metrics import classification_report, roc_curve, auc #For machine learning metrics<br>import xgboost as xgb #To train an xgboost classifier<br>import pickle #To save machine-learning models<br>from skopt import BayesSearchCV #For hyperparameter optimization<br>from skopt.space import Integer, Real #For the priories in hyperparameter optimization<br>import matplotlib.pyplot as plt #To make some plots<br>import numpy as np #To process some vectors<br>import shap #For explanability<br>from google.colab import drive #To load the datasets in Google Colab<br>from pywaffle import Waffle #This library is used for waffle plots<br>from graphviz import Digraph #To display the outline of the notebook<br>from IPython.display import Image #To display estimators of the XGBoost model</pre><p>First task is to load the training and evaluation datasets, like this:</p><pre># Define the path to the folder in Google Drive<br>path = &quot;/content/drive/My Drive/Colab Notebooks/Finance_Coding_Challenge/&quot;<br><br># Define the list of dataset names<br>datasets = [&quot;X_train.csv&quot;, &quot;X_test.csv&quot;, &quot;y_train.csv&quot;, &quot;y_test.csv&quot;]<br><br># Create a dictionary with the dataset names as keys and the DataFrames as values<br>data_dict = {dataset_name.split(&#39;.&#39;)[0]: pd.read_csv(os.path.join(path, dataset_name)) for dataset_name in datasets}</pre><p>After loading the training and evaluation datasets, I start the exploration phase by printing the head of the training dataset, followed by a recommendation. For instance, if the variables exhibit different scales, I suggest standardizing them for models sensitive to feature scaling.</p><pre>data_dict[&#39;X_train&#39;].head()</pre><pre>#### ✅ **Recommendation: The variables in the dataset exhibit different scales. <br>If you plan to use a model in the future that is sensitive to feature scaling, <br>consider standardizing the values to ensure consistent model performance.**</pre><p>I then identify columns with over 75% missing values, while noting that NaN values might represent the absence of events, such as in recency_1.</p><pre>print(missing_values_summary(data_dict[&#39;X_train&#39;]))</pre><pre>#### ✅ **Recommendation: Some variables in the dataset have a significant amount of missing data, <br>with percentages exceeding 75%. <br>If we select model in a future iteration does not effectively handle missing values, <br>remove these variables or impute the missing values. <br>However, consider that features may contain `NaN` values indicating the absence of information or an event. <br>For example, `recency_1` measures how many months have passed since an event in the applicant’s repayment history; <br>if the event never took place, the value will be `NaN`.**</pre><p>Next, I check for non-numeric columns, recommending encoding them into numerical formats like one-hot encoding for compatibility with most models.</p><pre># Identify non-numeric columns<br>non_numeric_cols = data_dict[&#39;X_train&#39;].select_dtypes(exclude=&#39;number&#39;).columns<br>print(&quot;Non-numeric columns:&quot;)<br>print(non_numeric_cols)</pre><pre>#### ✅ **Recommendation: For most models, non-numeric columns <br>should be encoded into numerical formats, <br>such as through one-hot encoding.**</pre><p>I also generate a correlation matrix of numerical columns and point out highly correlated variables, suggesting their removal if the model is sensitive to multicollinearity.</p><pre># Find columns with a correlation higher than 0.9<br>high_corr_columns = set()<br>for i in range(len(corr.columns)):<br>    for j in range(i):<br>        if abs(corr.iloc[i, j]) &gt; 0.9:<br>            colname = corr.columns[i]<br>            high_corr_columns.add(colname)<br>            high_corr_columns.add(corr.columns[j])<br><br># Convert to list<br>high_corr_columns = list(high_corr_columns)<br><br>high_corr_columns</pre><pre>#### ✅ **Recommendation: Some variables exhibit high correlation with each other. <br>If a future iteration of the model is sensitive to multicollinearity, <br>consider removing highly correlated variables.**</pre><p>Finally, I create a plot summarising my findings</p><pre># Data for waffle chart<br>data = {<br>    &#39;High Missing Values&#39;: percent_missing,<br>    &#39;Non-Numeric&#39;: percent_non_numeric,<br>    &#39;High Correlation&#39;: percent_high_corr,<br>    &#39;Remaining Features&#39;: percent_remaining<br>}<br><br># Prepare data for waffle chart<br>percents_of_groups_of_categories = pd.Series(data)<br><br># Colors for each group<br>colors = [  black,  dark_blue, light_gray, light_blue]<br><br># Create waffle chart<br>plt.figure(<br>    FigureClass=Waffle,<br>    rows=5,<br>    columns=10,<br>    values=percents_of_groups_of_categories,<br>    colors=colors,<br>    title={&#39;label&#39;: &#39;Percentage of Columns by Category&#39;},<br>    labels=[f&quot;{k} ({round(v,2)}%)&quot; for k, v in percents_of_groups_of_categories.items()],<br>    legend={&#39;loc&#39;: &#39;lower center&#39;, &#39;bbox_to_anchor&#39;: (0.5, -0.2), &#39;ncol&#39;: 2, &#39;fancybox&#39;: True},<br>    icon_legend=True,<br>    icon_size=16,<br>    icons=&#39;circle&#39;<br>)<br><br># Adjust the figure size if needed<br>plt.gcf().set_size_inches(7, 5)  # Increase width and height for more space<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*ZcSsUmaiUVDRrruZ75XcLA.png" /><figcaption>Percentage of Columns by Category: A summary of the exploratory data analysis</figcaption></figure><p>Please, ensure that any analysis or visualization included in the notebook provides actionable insights or recommendations.</p><h3>3 Modelling and Evaluation</h3><p>Start by selecting a technical metric and justifying your choice. Doing this early ensures that all subsequent work aligns with your goals.</p><pre>⚡ Metric Selection<br><br>AUC:<br><br> 1. Evaluates model performance across all classification thresholds.<br> 2. Provides a robust measure unaffected by class imbalance.<br> 3. Assesses the model’s ability to rank positive instances higher than negative ones.<br><br>F1 Score:<br><br> 1. Balances precision and recall, useful for managing trade-offs between accurate positive predictions and identifying all positives.<br> 2. Provides a comprehensive view of model performance when the costs of false positives and negatives are equal.</pre><pre>#### ✅ **Recommendation: Although this is the case of a unit-rate model, <br>false positives and false negatives likely have different costs, <br>so I recommend using AUC as the metric for this model. <br>AUC is well-suited for ranking individuals by their probability of ceasing repayment, <br>which allows for targeted interventions at different probability thresholds to <br>reduce default rates.**</pre><p>Next, focus on feature selection and justify each decision. In my case, I will be using an XGBoost, so I focus on the feature selection required for such a model; for example, imputation of missing values is not required.</p><pre>for dataset in [&#39;X_train&#39;,&#39;X_test&#39;]:<br>    # Convert &#39;financial_situation_4&#39; and &#39;financial_situation_5&#39; to one-hot encoding<br>    data_dict[dataset] = pd.get_dummies(data_dict[dataset], columns=non_numeric_cols , drop_first=False, dtype=int)<br><br>    # Remove the score obtained from a pre trained model from the features<br>    data_dict[dataset].drop(columns=[&#39;score_1&#39;], inplace=True)<br><br>    # Remove variables that have a correlation higher than 0.9 with another variable<br>    data_dict[dataset].drop(columns=high_corr_columns , inplace=True)</pre><pre>#### ✅ **Recommendation: Avoid using the output of another machine learning model as a feature. <br>This approach can create maintenance challenges, especially if the original model starts to drift or has data leakage issues. <br>Such problems may necessitate retraining both the original model and the dependent model, potentially leading to a cascade effect.**</pre><pre>#### ✅ **Recommendation: Although XGBoost can handle highly correlated variables, <br>relying on them may lead to inaccurate feature importance and SHAP value estimations, <br>as the model might treat them interchangeably in tree splits.**</pre><p>The next step is to train a baseline model. For simplicity, use either hyperparameters from prior experience or the default settings. For credit risk models, start with a boosting model such as LightGBM, XGBoost, or CatBoost. Logistic regression often fails to capture non-linear relationships in the data and may not perform well, so it’s best to avoid it. Similarly, support vector machines may struggle with large datasets. In my opinion, stick with XGBoost for your baseline model and consider experimenting with other models later.</p><pre># Define the classifier with adhoc parameters for handling imbalance and regularization<br>xgb_model = xgb.XGBClassifier(<br>    n_jobs=-1,                             # Use all available CPUs<br>    scale_pos_weight=10,                   # Adjust based on the ratio of negative to positive samples<br>    alpha=10,                             # L1 regularization<br>    reg_lambda=10,                         # L2 regularisation<br>    gamma = 15                             # Less splits<br>)<br>xgb_model.fit(data_dict[&#39;X_train&#39;].select_dtypes(include=&#39;number&#39;), data_dict[&#39;y_train&#39;].label.values.ravel())</pre><p>Next, evaluate the baseline model by plotting the ROC curve for both the training and testing datasets. Be sure to state your conclusions and recommendations based on these plots.</p><pre>plot_roc_curve(y_true,y_pred_prob,&quot;train&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*1C7H5HkNKjeOe0oMjZwMlg.png" /><figcaption>ROC Curve for the Train Dataset</figcaption></figure><pre>plot_roc_curve(y_true_test,y_pred_prob_test,&quot;test&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*7732yBNpsxgN1fM4o21rTA.png" /><figcaption>ROC curve for the Test dataset</figcaption></figure><pre>#### ✅ **Recommendation: The model exhibits some overfitting, <br>as it performs  better on the training dataset compared to the validation dataset. <br>Additionally, while the model predicts class 0 well, it struggles with class 1. <br>In the next iteration, address overfitting and class imbalance issues.**</pre><p>The next step is to refine the model to tackle overfitting and improve performance. Given the time constraints, I usually focus on optimizing the hyperparameters of a single model, like XGBoost, which is typically sufficient for a take-home exercise. Please use Bayesian optimization, as it is much faster than brute force methods.</p><pre># Define the search space<br>search_space = {<br>    &#39;n_estimators&#39;: Integer(50, 800),<br>    &#39;learning_rate&#39;: Real(0.001, 0.3, prior=&#39;log-uniform&#39;),<br>    &#39;max_depth&#39;: Integer(2, 4),<br>    &#39;scale_pos_weight&#39;: Integer(0,50),<br>    &#39;alpha&#39;: Real(0.01, 10, prior=&#39;log-uniform&#39;),<br>    &#39;reg_lambda&#39;: Real(0.01, 10, prior=&#39;log-uniform&#39;),<br>    &#39;gamma&#39;: Real(0.01, 10, prior=&#39;log-uniform&#39;)<br>}<br><br># Define the model<br>xgb_model = xgb.XGBClassifier(<br>    n_jobs=-1<br>)<br><br># Perform Bayesian Optimization<br>opt = BayesSearchCV(<br>    xgb_model,<br>    search_space,<br>    n_iter=5,  # Number of iterations<br>    scoring=&#39;roc_auc&#39;,<br>    cv=5,  # Number of cross-validation folds<br>    n_jobs=-1,<br>    verbose=1<br>)<br><br># Fit the model<br>opt.fit(data_dict[&#39;X_train&#39;], data_dict[&#39;y_train&#39;].label.values.ravel())<br><br># Extract the best estimator from the BayesSearchCV object<br>best_model = opt.best_estimator_<br><br># Best parameters<br>print(&quot;Best parameters found: &quot;, opt.best_params_)<br>print(&quot;Best ROC AUC score: &quot;, opt.best_score_)</pre><p>Next, evaluate this second model by plotting the ROC curve for both the training and testing datasets. Remember to state your conclusions and recommendations based on these plots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*280SiTh-oLPVOIyb5GVRww.png" /><figcaption>ROC Curve of the second model over the Train Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*xqlbi5PbRb_dVc-b2KCh8w.png" /><figcaption>ROC Curve of the second model over the Test Dataset</figcaption></figure><pre>#### ✅ **Recommendation: The model is no longer overfitted, as indicated by the closer AUC values. <br>However, the model still performs significantly better for class 0 compared to class 1. <br>Before proceeding with further iterations, it is important to consult with business leaders to clarify <br>their expectations for model performance and determine the acceptable trade-offs between precision and recall for each class.**</pre><h3>Model Explainability</h3><p>Rather than iterating further on the model, I recommend using the remaining time to explain the second model’s performance to a non-technical audience. For example, create a plot to visualise the confusion matrix for the test dataset.</p><pre># Extract values<br>TN, FP, FN, TP = evaluation_confusion_matrix.ravel()<br><br># Calculate total number of cases<br>total_cases = TN + FP + FN + TP<br><br># Calculate percentages<br>percent_correctly_predicted_ceasability = (TP / total_cases) * 100<br>percent_correctly_predicted_no_ceasability = (TN / total_cases ) * 100<br>percent_wrongly_predicted_ceasability = (FP / total_cases)  * 100<br>percent_wrongly_predicted_no_ceasability = (FN / total_cases ) * 100<br><br># Prepare data for waffle plot<br>data = {<br>    &#39;Correctly Predicted Ceasability&#39;: percent_correctly_predicted_ceasability,<br>    &#39;Correctly Predicted No Ceasability&#39;: percent_correctly_predicted_no_ceasability,<br>    &#39;Wrongly Predicted Ceasability&#39;: percent_wrongly_predicted_ceasability,<br>    &#39;Wrongly Predicted No Ceasability&#39;: percent_wrongly_predicted_no_ceasability<br>}<br><br># Convert to Series<br>percents_of_groups_of_categories = pd.Series(data)<br><br># Define colors<br>colors = [gray, dark_blue, dark_gray, &#39;brown&#39;]<br><br># Create waffle chart<br>plt.figure(<br>    FigureClass=Waffle,<br>    rows=5,<br>    columns=10,<br>    values=percents_of_groups_of_categories,<br>    colors=colors,<br>    title={&#39;label&#39;: &#39;Model Accuracy Percentages on Evaluation Dataset&#39;},<br>    labels=[f&quot;{k} ({round(v,2)}%)&quot; for k, v in percents_of_groups_of_categories.items()],<br>    legend={&#39;loc&#39;: &#39;lower center&#39;, &#39;bbox_to_anchor&#39;: (0.5, -0.5), &#39;ncol&#39;: 2, &#39;fancybox&#39;: True},<br>    icon_legend=True,<br>    icon_size=15,<br>    icons=&#39;person&#39;<br>)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*lBoUaiQUDfudQ_X91L3dAA.png" /><figcaption>Simple intuition of the confusion matrix over the test dataset for a non-technical audience</figcaption></figure><p>Highlight the most influential features</p><pre># Create the SHAP explainer<br>explainer = shap.Explainer(best_model, data_dict[&#39;X_test&#39;])<br><br># Compute SHAP values<br>shap_values = explainer(data_dict[&#39;X_test&#39;])<br><br># Plot SHAP bar plot for global feature importance<br>shap.summary_plot(shap_values, data_dict[&#39;X_test&#39;], plot_type=&quot;bar&quot;, max_display=10, color = dark_blue)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*NS-S2tx6XbEIoUeJN2fS_w.png" /><figcaption>Average impact of the top 10 features on the model output</figcaption></figure><p>…and explain whether their effects are positive or negative.</p><pre># Plot SHAP summary plot showing the impact of each feature<br>shap.summary_plot(shap_values, data_dict[&#39;X_test&#39;], max_display=10)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*oRkmLqLmV_xFKp8ImvU4lg.png" /><figcaption>Impact of each top 10 feature over the model output</figcaption></figure><p>Finally, it’s beneficial to educate a non-technical audience when presenting a model. I recommend showing the first three trees of the XGBoost model to provide insight into how the model works. This approach helps demystify the model, illustrating that it’s not a black box and is connected to business rules, even though it extracts patterns automatically.</p><pre>def plot_tree_with_graphviz(model, num_trees):<br>    dot = xgb.to_graphviz(model, num_trees=num_trees, rankdir=&#39;LR&#39;)<br>    return dot<br><br># Plot the first 3 trees with Graphviz<br>for i in range(3):<br>    dot = plot_tree_with_graphviz(best_model, i)<br>    dot.render(filename=f&quot;tree_{i+1}&quot;, format=&#39;png&#39;, cleanup=True)<br><br>    # Display the tree using IPython display<br>    print(f&quot;Tree_{i+1}&quot;)<br>    display(Image(filename=f&quot;tree_{i+1}.png&quot;))<br><br>    # To do:  Convert Log of Odds to Probability. Round split points to 1 or 0 decimals.</pre><p>First Tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjqvRU0eFmRgaQQISoCH8Q.png" /><figcaption>First tree of the second model</figcaption></figure><p>Second Tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbjvnPr_K3qL8kFBOa7O5A.png" /><figcaption>Second tree of the second model</figcaption></figure><p>Third Tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVFvCf9CBeRU0J8sa3d9BA.png" /><figcaption>Third tree of the second model</figcaption></figure><h3>4 Deployment</h3><p>For a take-home exercise, deployment should be straightforward. In this case, we’ll create a simple Python script for making predictions outside of the Jupyter notebook.</p><pre># Define the content of the inference script<br>inference_script = &quot;&quot;&quot;<br>import pandas as pd<br>import pickle<br>import os<br><br># Define the path where the model and test data are located<br>path = &quot;./Finance_Coding_Challenge/&quot;<br><br># Load the saved XGBoost model from the pickle file<br>with open(os.path.join(path, &#39;xgboost.pickle&#39;), &#39;rb&#39;) as handle:<br>    model = pickle.load(handle)<br><br># Load the X_test data<br>X_test = pd.read_csv(os.path.join(path, &#39;X_test.csv&#39;))<br><br># Convert &#39;financial_situation_4&#39; and &#39;financial_situation_5&#39; to one-hot encoding<br>X_test = pd.get_dummies(X_test , columns=[&#39;financial_situation_4&#39;, &#39;financial_situation_5&#39;], drop_first=False, dtype=int)<br><br># Remove the score obtained from a pre trained model and the account id from the features<br>X_test.drop(columns=[&#39;score_1&#39;,&#39;account_id&#39;], inplace=True)<br><br># Remove highly correlated features<br>X_test.drop(columns=[&#39;balance_12&#39;, &#39;utilization_7&#39;, &#39;balance_20&#39;, &#39;balance_4&#39;, &#39;utilization_15&#39;, &#39;utilization_11&#39;, &#39;utilization_4&#39;, &#39;repayment_history_22&#39;, &#39;balance_14&#39;, &#39;repayment_history_19&#39;, &#39;recency_8&#39;, &#39;repayment_history_16&#39;, &#39;balance_18&#39;, &#39;balance_2&#39;, &#39;credit_limit_2&#39;],inplace=True)<br><br># Make predictions<br>predictions = model.predict(X_test)<br><br># Convert predictions to a DataFrame<br>predictions_df = pd.DataFrame(predictions, columns=[&#39;predicted_label&#39;])<br><br># Print the DataFrame<br>print(predictions_df)<br>&quot;&quot;&quot;<br><br># Write the content to &#39;inference.py&#39;<br>with open(os.path.join(path, &#39;inference.py&#39;), &#39;w&#39;) as file:<br>    file.write(inference_script)<br><br>print(&quot;inference.py has been created.&quot;)</pre><h3>5 Conclusions and Future Directions</h3><p>In the conclusions, highlight the model’s strengths and weaknesses, suggest improvements</p><pre>⚡ Business implications of the current model performance<br><br>Pros:<br><br> 1. High Recall for Class 1: Useful in identifying most of the customers who will default. This helps in taking preventative actions, such as adjusting credit limits or sending reminders to potentially risky customers.<br> 2. High Precision for Class 0: Ensures that most customers who are predicted as non-defaults indeed do not default. This is beneficial for maintaining good customer relations and ensuring smooth operations.<br><br> Cons:<br><br> 1. Low Precision for Class 1: With very low precision, there is a high rate of false positives. This means a lot of customers are incorrectly flagged as likely to default, which can lead to unnecessary actions (e.g., denying credit or initiating collection efforts). This could harm customer relationships and result in lost revenue from good customers who are incorrectly classified.<br> 2. Operational Impact: The low precision for defaults might result in inefficient use of resources, such as spending time and money on customers who are unlikely to default.</pre><pre>⚡  This model has potential to enhance the company’s default rate management.<br>Before moving forward with additional experiments, it’s essential to validate <br>the model’s current performance and align it with the business team’s expectations. <br>Additionally, present the key variables affecting the ceasing repayment probability <br>to the business team and gather their feedback.</pre><pre>⚡ To enhance model performance, explore class imbalance techniques such as <br>oversampling (e.g., SMOTE), undersampling, or a combination of both. <br>Evaluate their impact on the model and select the most effective approach. <br>If SMOTE is used, ensure to handle missing values appropriately.</pre><p>discuss the benefits of probability calibration</p><pre>⚡  The model currently outputs a propensity score rather than a calibrated probability. <br>For future iterations, consider using well-calibrated probabilities. <br>Calibrated probabilities allow for adjustable thresholds based on the company’s loss given <br>default and offer greater transparency, which facilitates easier justification to regulators.</pre><p>Also, consider how you would refine the model if the features were not anonymised</p><pre>⚡ **If the features were not anonymized, I would perform the following checks:**<br><br>1. Ensure that the features do not drift over time.<br>2. Verify that the features do not present any data leakage.<br>3. Determine whether the missing values signify an absence of action or if they are random, possibly due to issues with data pipelines.<br>4. Identify the features that were used to train the pre-trained model.</pre><h3>Time to Put on Your Data Scientist Hat!</h3><p>Unfortunately, most credit risk datasets are proprietary and contain sensitive information, making them inaccessible. However, if you’re eager to tackle a credit risk model for a take-home exercise, why not start with a <a href="https://www.kaggle.com/competitions/home-credit-default-risk/data">publicly available dataset from Kaggle</a>? Dive in and give it a go!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=047ea6a5b6e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The best spend trackers in the UK]]></title>
            <link>https://medium.com/@mauriciotorob/the-best-spend-trackers-in-the-uk-030d6d9d13e2?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/030d6d9d13e2</guid>
            <category><![CDATA[open-banking]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cheddar]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 12:50:58 GMT</pubDate>
            <atom:updated>2024-08-29T12:50:58.718Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blogpost I highlight the Good, the Bad and the Ugly of the UK’s leading spend trackers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*JZgqwfLMWswxYy94.jpg" /></figure><p>Mauricio Toro, Data Scientist at Cheddar</p><h3>What’s a spend tracker?</h3><p>A spend tracker is like a helpful assistant that keeps track of your money so you can understand where your money goes each month. In the UK, popular spend tracking apps include Emma, Plum, Snoop, Revolut, Klarna, Snoop, Rise Up and Monzo.</p><p>In this post, I’ll share how these apps helped me track my spending in July 2024, discuss the good, the bad and the ugly of each of them and why you should consider giving <a href="https://www.cheddar.me/">Cheddar’s</a> new spend tracking feature a spin.</p><h3>My spend</h3><p>I have two credit cards (Monzo Flex and Capital One), four bank accounts (Lloyds, Monzo, Chase, Revolut), and savings in three banks (Monzo, Chase, Lloyds).</p><p>Most of my spend in July was in the UK, with a few days in Slovakia and Austria. My biggest expenses were bills (including credit card payments), travel, and eating out. Finally, I often transfer money between my bank accounts and savings accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*J7uWXk4ZaNuZ1VyW.gif" /><figcaption><em>Trying to keep up with all my spend</em></figcaption></figure><h3>‍Plum</h3><p><strong>The Good</strong> — Plum organises your spending into categories like Transfers, General, Wealth, Shopping, Bills and Utilities, Groceries, and Eating Out. The categories, aside from ‘General’ are well-organised and make sense for my spending.</p><p><strong>The Bad </strong>— Plum requires a subscription to Plum Ultra, costing at least £5 per month. Self-to-self transactions are included in Transfers and counted as spending, which inflates this category. Transfers to savings accounts are wrongly classified as ‘General.’ This means I need to manually reassign many transactions to the correct categories. The app does not support linking my Monzo credit card, only my current account. There’s also a category called Wealth, which is confusing; it said I spent £400 on Wealth, but what does that mean? Plum says my total spending is £9,672, what? That is inflating my spending by more than 2 times! Finally, Plum doesn’t provide saving tips like ‘you are spending more on eating out than on groceries.’</p><p><strong>The Ugly</strong> — The app uses a ring plot to summarise spending, but it’s difficult to read because it is not interactive. You often have to refer back to the category list to understand what each colour represents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fxb_pUyiWyrL4YD8.png" /></figure><p><em>Plum’s PFM</em></p><h3>Monzo</h3><p><strong>The Good </strong>— Monzo includes categories like General, Bills, Transport, Eating Out, Expenses, Groceries, Holidays, and Shopping. The categories, aside from ‘General’ are well-organised and make sense for my spending. It correctly excludes transfers to savings accounts from spending, recognising them as savings.</p><p><strong>The Bad</strong> — It’s free to analyse your Monzo account, but linking other accounts requires a monthly subscription of at least £5. A large portion of my spending is categorised as ‘General’ which is not very informative. Monzo says my spending in ‘General’ is £4,598, what? That alone is more than my total spending! This means I need to manually reassign many transactions to the correct categories. Bank transfers to myself are also counted as spending. The app doesn’t provide savings tips, such as pointing out if you’re spending more on eating out than on groceries.</p><p><strong>The Ugly</strong> — The visual representations are confusing. They focus on changes in balance or weekly spending rather than clearly showing the proportion of spending in each category. The budget feature, referred to as ‘target,’ also uses a plot that’s difficult to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FlYbxDc7UHNtfjDj.png" /></figure><p><em>Monzo’s PFM</em></p><h3>Emma</h3><p><strong>The Good</strong> — Emma categorises spending into groups like Transport, Shopping, Groceries, Holidays, Personal Care, Bills, Debt, Entertainment, and General. Most categories, apart from ‘General’ and ‘Debt’ accurately reflect my spending. The interface is warm and nicely designed, with a colourful pie chart that clearly shows spending proportions.</p><p><strong>The Bad</strong> — Emma isn’t free; it requires a minimum £5 monthly subscription for Emma Plus. Many transactions are lumped into the ‘General’ category. So, I often had to correct the transactions on the general category. Transfers to other people or myself are sometimes incorrectly labelled as Shopping or Debt, which is confusing. The app mistakenly counts savings as spending. Emma says my total spending is £6,210, what? That is around two times my total spending! Changing a transaction’s category involves too many steps. It also lacks savings tips, like telling if you’re spending more on eating out than on groceries.</p><p><strong>The Ugly</strong> — The vibrant colour scheme, featuring pink, purple, magenta, and fuchsia, might not appeal to those who prefer more subdued colours often found in financial apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rEXus785aDI0t8zm.png" /></figure><p><em>Emma’s PFM</em></p><h3>Snoop</h3><p><strong>The Good </strong>— Snoop categorises spending into groups like Transport, Shopping, Groceries, Finances, Home and Family, Entertainment, and General. Most categories, apart from ‘General’ and ‘Finances’, accurately reflect my spending.</p><p><strong>The Bad</strong> — Transfers to myself and savings transfers are sometimes labelled as ‘General’ or ‘Finances’, which can be confusing. The app mistakenly counts savings as spending. The ‘Finances’ category is unclear; it’s confusing to see that I spend £1,000 a month in finances. What does that mean? Snoop also lacks savings tips, such as telling you if you’re spending more on eating out than on groceries. Instead, it offers deals like “we give you £175 if you switch to First Direct,” which could be useful for some. Finally, there is no way to compare spending by category in terms of percentage or in a ring chart. Instead, they show how much is over budget in a ring, rather than displaying the top spending categories as many other apps do.</p><p><strong>The Ugly</strong> <strong>— </strong>The separation of categories with a budget and those without a budget seems off and hard to follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OFj_WRka-NqOBHF9.png" /></figure><p><em>Snoop’s PFM</em></p><h3>Klarna</h3><p><strong>The Good</strong> — Klarna includes categories like Bills, Transport, Food and Drinks, Travel, Leisure, and Other. Most categories, apart from ‘Other’ accurately reflect my spending. The categories are well designed and very descriptive. When you click on a category, you can see subcategories like restaurants, groceries, delivery, and coffee under Food and Drinks. It’s easy to change the category of a transaction, and you can quickly update all transactions with the same name.</p><p><strong>The Bad</strong> — The ‘Other’ category accounts for more than half of my transactions, which isn’t very informative. Transactions to myself are also shown as ‘Other’, which is misleading. While savings are correctly excluded from my spending, Klarna says my total spending is £7,736, what? That is around 2 times my total spending! The app lacks practical savings tips, like highlighting if you’re spending more on eating out than on groceries.</p><p><strong>The Ugly</strong> — The app’s functionality is somewhat hidden. You have to navigate to Payments, slide a scrolling bar, and select Insights to access your spend tracker.. The visual representation of spending is a plot with colour blocks stacked on top of each other, which is difficult to interpret. You frequently need to refer to the list of categories to understand what each colour represents. Additionally, because it’s not normalised to 100%, comparing spending across months is challenging, as it shows the actual amounts rather than the percentage of total spending.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Qw5pJxuhbgs502t.png" /></figure><p><em>Klarna’s PFM</em></p><h3>Revolut</h3><p><strong>The Good</strong> — Revolut’s app includes categories like Transfers, General, Transport, Restaurants and Shopping. Most categories, apart from ‘General’ accurately reflect my spending. It provides a plot that lets you view your spending by week or month, and a ring chart that highlights the top two spending categories.</p><p><strong>The Bad </strong>— A lot of transactions fall under a ‘General’ category, which isn’t very informative; for instance, many restaurant expenses are labelled as ‘General’. This means I have to manually reclassify a lot of my transactions for more accurate tracking. The app also mistakenly categorises self-to-self transfers and transfers to savings accounts as spending. Snoop says my total spending is £7,983, what? That is around two times my total spending! The ring chart isn’t very useful because it only shows my top two spending categories. Additionally, it doesn’t offer savings tips, such as pointing out if you’re spending more on eating out than groceries.</p><p><strong>The Ugly </strong>— The spend tracker is only available for Revolut accounts by default. It lists each of my bank and savings accounts separately, and ‘All personal accounts’ is hidden at the bottom of a long dropdown list, making it hard to find.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o7aOk5IpbsbR_kEh.png" /></figure><p><em>Revolut’s PFM</em></p><h3>Rise Up</h3><p><strong>The Good </strong>— I love how Rise Up categorises my spending into useful groups like ‘Shopping’, ‘Groceries’, and ‘Travel’. It’s great that it excludes transfers to savings accounts and self-transfers from my spending. The personalised saving tips are also a nice touch, helping me identify areas where I can cut back, for example, it told me I spent more on eating out than grocery shopping last month.</p><p><strong>The Bad </strong>— Rise Up is expensive; it requires a minimum £10 monthly subscription. Instead of showing how my spending compares to expected forecasts, I’d like to see how my spending is distributed across categories. A pie chart or just having percentages would make it easier to understand where my money is going.</p><p><strong>The Ugly </strong>— The interface needs work and the visualisations need improvement. It’s hard to read and compare my spending across categories because I have to scroll through a long list. The categories are also randomly ordered, making it difficult to quickly see where I’m spending the most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JzKAn60VBKXWfQYW.png" /></figure><p><em>Rise Up’s PFM</em></p><h3>Cheddar</h3><p>Cheddar is free, with no cost, subscription, or ads. Cheddar has a spend tracker that sorts your spending into categories like Bills, Travel, Food and Drink, Groceries, Transportation, and Other. Most expenses are accurately categorised, with very few falling into the ‘Other’ category. The design is top-notch, with intuitive categories and subcategories. For example, within Bills, you can find Loans, Rent, Services, Subscriptions, Utilities, and Fees. Cheddar is visually appealing, offering attractive colours, plots, and icons in both light and dark themes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YjHy1L97jt4UkG7-.png" /></figure><p><em>Cheddar’s PFM</em></p><h3>Conclusion</h3><p>The apps that categorised my spending the best, with minimal transactions labelled as ‘Other’, were Cheddar and Rise Up. Cheddar is free to use while Rise Up comes with a hefty price tag of £9.99 per month. Monzo, Plum and Emma categorised most of my spending as ‘Other’ or ‘General’ and have a minimum monthly subscription fee of £5. Revolut, Snoop and Klarna, categorised most of my spending as ‘Other’ or ‘General’, considered transfers to myself as spending, and even considered savings as spending.</p><p>Cheddar’s new spend tracker feature is available now in beta while the team expands on its feature set. <a href="https://www.cheddar.me/"><strong>Give it a try!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=030d6d9d13e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining bank transaction categorisation at scale — Part 4]]></title>
            <link>https://medium.com/@mauriciotorob/streamlining-bank-transaction-categorisation-at-scale-part-4-8723858d0b8c?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/8723858d0b8c</guid>
            <category><![CDATA[finance-and-banking]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[natural-language-processi]]></category>
            <category><![CDATA[bank-transactions]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 14:30:38 GMT</pubDate>
            <atom:updated>2024-08-20T14:30:38.216Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streamlining bank transaction categorisation at scale — Part 4</h3><p>In parts <a href="https://medium.com/@mauriciotorob/streamlining-transaction-categorization-at-scale-part-1-2385e31e3861">1</a> and <a href="https://medium.com/@mauriciotorob/streamlining-transaction-categorisation-at-scale-part-2-6f00e8180418">2</a> of our blog, we explored <a href="https://www.cheddar.me/">Cheddar</a>’s efforts to enhance its Personal Finance Manager (PFM) by focusing on user insights, transaction mapping, and data standardisation. <a href="https://medium.com/@mauriciotorob/streamlining-transaction-categorisation-at-scale-part-3-0875ca8cc3be">Part 3</a> introduced AI techniques, including numerical embeddings and machine learning models, to further refine transaction categorization, supported by extensive human testing. Now, in part 4, we will explore how these innovations are being applied to categorise transactions in Cheddar’s PFM.</p><h3><strong>Part 4 — Going to production</strong></h3><p><strong>9. API Creation</strong></p><p>After completing the human review process, our data scientists teamed up with data engineers to create an efficient and robust data workflow. This collaboration led to the development of an Application Programming Interface (API) that encapsulates all the logic for transaction categorization. The API processes batches of transactions and returns their corresponding categories, ensuring seamless and accurate categorization.</p><p>The web API was developed using FastAPI, with Pydantic integrated to enforce strict type checking, safeguarding the integrity and consistency of the input data. The mappings of retailers and merchant category codes were stored in memory dictionaries, while the machine learning model was loaded using TensorFlow Hub and also kept in memory as part of the API.</p><p>To ensure reliability, the team defined unit tests with various transaction cases, specifying the expected categories or error messages. Additionally, they assessed the API’s performance, ensuring it could categorise 1,000 transactions in under 100 milliseconds. They also specified the required libraries, their versions, and the necessary Python version to guarantee a correct operation.</p><p><strong>10. Cloud Deployment</strong></p><p>In the final phase, our data engineers streamlined the deployment of our API using GitHub Actions, automating the process. This included building a Docker image that contained all necessary API components, which was then automatically uploaded to the container registry within Google Cloud Platform’s Vertex AI. GitHub then triggered the creation of a model from this image, deploying it as a private endpoint in Vertex AI specifically designed for online predictions. This private endpoint is securely integrated with the backend of the Cheddar App, enabling seamless access to our categorization API.</p><p>To ensure monitoring, the data scientists established dashboards focusing on three types of metrics: technical, machine learning, and business metrics. For technical monitoring, they used Google Cloud Platform’s (GCP) tools to create a dashboard that alerts when more than 5 out of 10,000 API responses return codes other than 200 within a 5-minute window — indicating potential errors, whether in the API itself or in the GCP infrastructure. The team also set up a dashboard to monitor API scalability by tracking instances where more than one instance is required to handle requests, a scenario that should be rare given the current user base.</p><p>For machine learning metrics, the scientists developed a dashboard to continuously assess the weighted precision and accuracy of the ML model by comparing API results against known transaction categories, and the source of the category labels (whether from the ML model or predefined mappings).</p><p>Lastly, in collaboration with the product team, they defined key business metrics, such as the distribution of transactions across categories and the proportion of total spending per category. A dedicated dashboard tracks these metrics over time, with alerts set to notify the team if any proportions deviate from expected norms.</p><p><strong>Conclusions</strong></p><p>Cheddar has aimed to revolutionise banking with user-friendly financial solutions that simplify payments and democratise rewards. Our cashback program has not only earned high praise from users but also contributed to our recent accolades, including the prestigious ‘Best Newcomer’ award in 2024. We are dedicated to further enhancing the banking experience by making it more accessible and rewarding for everyone. Exciting plans are underway, including the recent launch of a versatile Personal Finance Manager (PFM) designed to empower users across various bank accounts with intuitive financial management tools.</p><p>At the heart of our PFM lies the implementation of transaction categorization. This process, detailed across four parts in our journey, highlights our use of technologies like machine learning, NLP, and AI to accurately classify transactions. From understanding user needs and refining spending categories to integrating AI for enhanced categorization, each phase has been pivotal in ensuring a seamless financial management experience for our users. The culmination of this effort includes the development of an API-driven solution deployed on cloud infrastructure. As we continue to expand and refine our offerings, Cheddar remains in our mission to redefine banking, making it more transparent and accessible for all.</p><p><strong>Future steps</strong></p><p>As we continue developing the PFM feature for the Cheddar app, our primary focus is on enhancing the user experience by grouping transactions into categories that are both intuitive and insightful. We’re also working on introducing personalised suggestions tailored to each user’s spending patterns, aiming to offer recommendations that help users save more effectively.</p><p>On the technical front, we’re exploring the possibility of training a character-based large language model from scratch. This model is designed to comprehend the unique language of bank transactions — a specialised language filled with proper nouns like PayPal, eBay, and Amazon; common words like store, supermarket, and bank; abbreviated terms; and a variety of symbols, such as asterisks, parentheses, dashes, and digits of varying lengths. Additionally, the model should handle the intricacies of spaces and abbreviations within merchant names, which can significantly alter the syntax while preserving the same meaning. For instance, variations like “PayPal * sainsburyssupermar,” “Sainsbury’s Supermarket,” and “PAYPAL SAINSBURY 6676” may look different but refer to the same retailer. Our goal is to ensure the model can accurately interpret these nuances, leading to more precise transaction categorization and a better user experience.</p><p><strong>Embark on the journey</strong></p><p>Are you intrigued by the realm of Bank Transaction Categorization? Are you eager to define categories and craft a machine learning model that predicts them? Perhaps you are keen on exploring various AI language models to identify the perfect fit for analysing bank transactions? Your journey may begin by diving into an open dataset of bank transactions, accessible on Kaggle at<a href="https://www.kaggle.com/datasets/apoorvwatsky/bank-transaction-data"> https://www.kaggle.com/datasets/apoorvwatsky/bank-transaction-data</a>. Happy exploring!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8723858d0b8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining transaction categorisation at scale — Part 3]]></title>
            <link>https://medium.com/@mauriciotorob/streamlining-transaction-categorisation-at-scale-part-3-0875ca8cc3be?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/0875ca8cc3be</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[financial-services]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 15:48:05 GMT</pubDate>
            <atom:updated>2025-03-17T16:49:42.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streamlining bank transaction categorisation at scale — Part 3</h3><p>In parts <a href="https://medium.com/@mauriciotorob/streamlining-transaction-categorization-at-scale-part-1-2385e31e3861">1</a> and <a href="https://medium.com/@mauriciotorob/streamlining-transaction-categorisation-at-scale-part-2-6f00e8180418">2</a> of our blog, we explored <a href="https://www.cheddar.me/">Cheddar’s</a> journey in enhancing its Personal Finance Manager (PFM) by focusing on user-centric insights and transaction type mapping, followed by data cleaning and mapping processes. We detailed how we extracted and standardised merchant names and linked them to common retailers, ensuring accurate transaction categorisation. Coming up in part 3, we will dive into incorporating discriminative Artificial Intelligence (AI) to further refine transaction categorisation, including the use of numerical embeddings, developing a machine learning model, and conducting human testing for validation.</p><h3>Part 3 — <strong>Adding AI to make it sing</strong></h3><p><strong>6. Numerical Embedding based on Discriminative AI</strong></p><p>In cases where transactions lacked a Merchant Category Code (MCC) and involved smaller businesses — like “convenience store John Street” or “SumUp * Taxi Driver XX YY” — our data scientists came up with a creative solution using AI and large language models (LLMs). They used these models to transform merchant names into numerical vectors with fixed dimensions, usually between 300 and 1000. The goal was to map similar merchants close to each other in this vector space, so related categories like restaurants or transport services would cluster together, while keeping distinct categories apart.</p><p>After testing different models like BERT Sentence and Google Universal Sentence Embedding (USE), the team found that USE was the best fit for representing diverse merchant names. This choice will significantly improve our ability to categorise transactions involving smaller merchants. To select the optimal numerical representation, the team evaluated several factors. They started by sampling merchant names and converting them into high-dimensional vectors. Using t-SNE, they reduced these vectors to two dimensions and created scatter plots to visually assess how well the embeddings grouped similar merchants. They also considered the performance of the models, noting that USE was notably faster than Sentence BERT. Despite USE not being open source, its good performance and effective clustering of merchant names without tuning made it the preferred choice.</p><p><strong>7. Machine Learning Model</strong></p><p>Our goal? Teach a machine learning model to predict transaction categories using labeled data: remember retailer names, transaction types, and merchant category codes? But instead of replacing our rule-based approach, we use ML to fill the gaps where rules fall short. If a transaction lacks a recognisable retailer name or merchant code, that’s where our model steps in.</p><p>While the numerical embedding captures certain semantics of the merchant name, it alone falls short of providing a mapping of transactions to categories. To address this, we developed a machine learning model to predict transaction categories. Our approach involved leveraging existing transaction features like date, amount, and bank, while also introducing new features such as the day of the week, the count of numerical digits within the merchant name, and the maximum numerical value present in the merchant name. Crucially, we integrated the numerical embedding of the merchant name as a key feature.</p><p>Training both a random forest and an Xgboost model on this augmented dataset, we observed that Xgboost demonstrated superior performance for this task. Our optimization metric focused on the weighted average F1 score, assessing the model’s proficiency in classifying transactions across all categories. Importantly, this metric assigns greater significance to high-transaction-volume categories like supermarkets, while appropriately weighing down categories with fewer transactions, such as reading.</p><p><strong>8. Human Testing</strong></p><p>In a collaborative effort involving all company employees, the data scientists distributed a subset of transactions — comprising a few thousand instances — to each team member, along with assigned spending categories. Each transaction in the human testing sample was independently assessed by three different individuals. Each participant was tasked with determining whether the assigned category was accurate, acceptable but improvable, or definitively incorrect. Following individual assessments, a collective discussion ensued, allowing for the identification of common concerns, suggestions, and areas for improvement in the categorization process. This human-centric testing proved invaluable in refining our categorization system, ensuring a more accurate and user-friendly experience for our platform users.</p><h3>Coming Next</h3><p>In the <a href="https://medium.com/@mauriciotorob/streamlining-bank-transaction-categorisation-at-scale-part-4-8723858d0b8c">final part of this blog</a>, we’ll dive into the exciting final steps of our project. We’ll explore how our data scientists and engineers collaborated to create a robust API for transaction categorization and discover how they used FastAPI and Pydantic to ensure efficient and reliable data processing. We’ll also detail how we automated the deployment of this API using GitHub, Docker, and Google Cloud Platform’s Vertex AI, culminating in a seamless integration with the Cheddar App. Stay tuned to see how these technologies come together to enhance our platform’s capabilities!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0875ca8cc3be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimating the Audience Segments of a Website Using Artificial Intelligence]]></title>
            <link>https://medium.com/@mauriciotorob/estimating-the-audience-segments-of-a-website-using-artificial-intelligence-f1ead9e9355e?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1ead9e9355e</guid>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[behavioural-science]]></category>
            <category><![CDATA[audience-targeting]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 19:27:22 GMT</pubDate>
            <atom:updated>2024-07-23T20:44:34.642Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we explore how to use artificial intelligence (AI) pre-trained models to predict website audiences, enabling more targeted communication strategies. Our goal is to understand audience by processing website content through various AI models. We extract text, summarize it, detect emotions, identify keywords, and predict audience segments to understand how different narratives resonate with various audiences. This approach helps us tailor messages to achieve our goals and connect effectively with audiences.</p><p>We follow these steps: extracting text from URLs, summarizing content, analyzing emotions, classifying text into categories, extracting keywords, and predicting audience segments. These functions work together to give us a detailed overview of each webpage. Next, we will explore each step in detail.</p><h3>Required libraries</h3><p>We need these libraries to extract, process, and analyze text data from websites. We use boilerpy3 and requests to extract clean text from HTML content. The transformers library, including pipeline, BartTokenizer, and BartForConditionalGeneration, handles natural language processing tasks such as text summarisation and emotion detection. Thenltklibrary provides tools for tokenising text and analysing word frequency. Librariesscikit-learnandTfidfVectorizer helps us identify keywords based on TF-IDF scores. Finally, tabulate and IPython.display allow us to render the processed data into readable tables in a Jupyter notebook environment.</p><pre>#!pip3 install --quiet boilerpy3 tabulate nltk transformers sklearn pandas<br><br>from boilerpy3 import extractors<br>import requests<br><br>from transformers import pipeline<br>from transformers import BartTokenizer, BartForConditionalGeneration<br><br>import pandas as pd<br>import nltk<br>from nltk.tokenize import word_tokenize<br>from collections import Counter<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br>from tabulate import tabulate<br>from IPython.display import display, HTML</pre><h3>Extract the text from the URL</h3><p>First, we have the function to extract text from a URL. This function fetches the main content from a given URL using the requests library and the boilerpy3 extractor.</p><pre># 1. Extract text from URL<br><br>def extract_text_from_https://medium.com/url(url):<br>    # Send a request to the website<br>    response = requests.get(url)<br>    response.raise_for_status()  # Check that the request was successful<br>    <br>    # Extract main content using boilerpy3<br>    extractor = extractors.ArticleExtractor()<br>    content = extractor.get_content(response.text)<br>    <br>    return content</pre><p>Throughout this blog we will consider two examples. The first is an article about a <a href="https://www.bbc.co.uk/news/articles/cn078lznklxo">village that needs new medical centre </a>published by the BBC. The second is an <a href="https://www.safecosmetics.org/resources/safe-cosmetics-tips/">article about how to choose safe cosmetics</a>.</p><h3>Automatic summarisation</h3><p>Next, we have the text summarisation function. This function uses a pre-trained BART model to summarize the extracted text by breaking it into manageable chunks and then generating a summary of those summaries. Summarising long texts helps us quickly grasp the main points without having to read the entire content, making the information more accessible and easier to analyse.</p><pre># 2. Text Summarization<br><br># Load pre-trained BART model and tokenizer<br>model_name = &#39;facebook/bart-large-cnn&#39;<br>tokenizer = BartTokenizer.from_pretrained(model_name)<br>model = BartForConditionalGeneration.from_pretrained(model_name)<br><br>def summarize_text(text, max_length):<br>    inputs = tokenizer.batch_encode_plus([text], max_length=max_length, truncation=True, return_tensors=&#39;pt&#39;)<br>    summary_ids = model.generate(inputs[&#39;input_ids&#39;], num_beams=4, min_length=30, max_length=max_length, early_stopping=True)<br>    return tokenizer.decode(summary_ids[0], skip_special_tokens=True)<br><br># Function to summarize long texts<br>def summarize_long_text(long_text, max_length = 130, chunk_size=512, long = False):<br>    text_chunks = [long_text[i:i+chunk_size] for i in range(0, len(long_text), chunk_size)]<br>    summaries = [summarize_text(chunk,max_length) for chunk in text_chunks]<br>    if long:<br>        return &#39;. &#39;.join(summaries)<br>    else:    <br>        return summarize_text(&#39;. &#39;.join(summaries),max_length)</pre><p>This is the summary we obtained for the article about the village</p><blockquote>Village has ‘desperate need’ for new medical centre near Norwich. Almost 4,000 more homes have been proposed for Rackheath. Construction work will begin on 5 August and should be complete in spring.</blockquote><p>And this is the summary of the article about safe cosmetics</p><blockquote>Choose products with simpler ingredient lists and hidden ‘fragrance’ ingredients. Avoid products with ‘parfum’ on the label which can hide any number of chemicals. Use Tools like Clearya and Think Dirty to find out whether your go-to products are safe.</blockquote><p>These results were obtained by splitting the text into chunks of 512 characters and then creating a “summary of summaries.”</p><h3>Emotion analysis</h3><p>For emotion analysis, we use a function with a pre-trained emotion detection model from the transformers library. This function analyzes the text in chunks, identifying the dominant emotion in each segment. By understanding the emotional tone, we gain insights into the overall sentiment and how readers might perceive the content.</p><pre># 3. Emotion Analysis<br><br># Load the pre-trained emotion detection model and pipeline<br>emotion_pipeline = pipeline(&quot;text-classification&quot;, model=&quot;j-hartmann/emotion-english-distilroberta-base&quot;)<br><br>def detect_emotion(text, chunk_size=512):<br>    # Split the text into chunks<br>    text_chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]<br>    <br>    # Detect emotion for each chunk<br>    emotions = []<br>    for chunk in text_chunks:<br>        result = emotion_pipeline(chunk)<br>        # Get the emotion label with the highest score for each chunk<br>        emotion_label = max(result, key=lambda x: x[&#39;score&#39;])[&#39;label&#39;]<br>        emotions.append(emotion_label)<br>    <br>    return emotions<br><br>def get_most_common_emotion(emotions):<br>    # Count the occurrences of each emotion<br>    emotion_counts = Counter(emotions)<br>    # Get the most common emotion<br>    most_common_emotion = emotion_counts.most_common(1)[0][0]<br>    return most_common_emotion</pre><p>For the article about the village, the list of emotions identified is as follows</p><blockquote>fear, joy, joy, neutral</blockquote><p>For the cosmetics article, the list of emotions is as follows</p><blockquote>neutral, neutral, neutral, neutral, neutral</blockquote><p>These results were obtained by splitting the text into chunks of 512 characters and analysing each chunk separately.</p><h3>Keyword extraction</h3><p>The fourth function extracts keywords while excluding verbs. It tokenizes the text, tags parts of speech, filters out verbs, and then uses TfidfVectorizer to identify relevant keywords. This process helps us understand the key concepts of the text.</p><pre># 4. Get keywords excluding verbs<br>def get_keywords_from_text(text):<br>    # Tokenize and POS tagging<br>    tokens = word_tokenize(text)<br>    pos_tags = nltk.pos_tag(tokens)<br>    <br>    # Filter out verbs<br>    non_verbs = [word for word, pos in pos_tags if pos not in (&#39;VB&#39;, &#39;VBD&#39;, &#39;VBG&#39;, &#39;VBN&#39;, &#39;VBP&#39;, &#39;VBZ&#39;)]<br>    <br>    # Join non-verbs into a cleaned text<br>    cleaned_text = &#39; &#39;.join(non_verbs)<br>    <br>    # Vectorize and extract keywords<br>    vectorizer = TfidfVectorizer(stop_words=&#39;english&#39;)<br>    X = vectorizer.fit_transform([cleaned_text])<br>    feature_names = vectorizer.get_feature_names_out()<br><br>    # Return the words with the highest TF-IDF scores for the document<br>    scores = X[0].T.todense().A1<br>    sorted_items = sorted(zip(scores, feature_names), reverse=True)<br>    return [word for score, word in sorted_items[:5]]</pre><p>For the article about the village, the list of keywords is as follows:</p><blockquote>centre, medical, village, rackheath.</blockquote><p>Whereas for the cosmetics article, the list of keywords is as follows:</p><blockquote>products, ingredients, safe, toxic, care.</blockquote><h3>Zero-shot classification</h3><p>The fifth function employs zero-shot classification to categorise text into predefined categories without requiring additional training. Using a pre-trained BART model, this function assesses the text against a list of potential categories and returns the category that best aligns with the content. This method is ideal for predicting audience segments without the need for training or fine-tuning models.</p><pre># 5. Zero-Shot Classification<br>def get_top_zero_shot_prediction(text,category_list):<br>    zero_shot_pipeline = pipeline(model=&quot;facebook/bart-large-mnli&quot;)<br>    results = zero_shot_pipeline(plain_text,category_list, multi_label=False)<br>    return results[&#39;labels&#39;][0]</pre><h3>Audience segment prediction</h3><p>Finally, the audience analysis function uses a zero-shot classification model to predict the audience type for categories such as gender, age, income, and location. By identifying the intended audience, you can tailor the content to better match their preferences and needs.</p><pre># 6. Get the audience analysis<br><br># Define the types of audience we want to analyse<br>audience_types = [&quot;gender&quot;, &quot;age&quot;, &quot;income&quot;, &quot;location&quot;]<br><br>def get_audience_analysis(text):<br>    # Define the possible values for each type of audience<br>    audience_category_lists = [ [&quot;resonates with men&quot;,&quot;resonates with women&quot;],\<br>                          [&quot;resonates with young people&quot;,&quot;resonates with middle age people&quot;, &quot;resonates with old people&quot;],\<br>                          [&quot;resonates with low income&quot;,&quot;resonates with medium income&quot;, &quot;resonates with high income&quot;],\<br>                          [&quot;resonates with urban people&quot;, &quot;resonates with rural people&quot;],\<br>                        ]    <br>    audience_dict = {}<br>    for index, category_list in enumerate(audience_category_lists):<br>        # Use a zero shot classifier to obtain the audience for each category<br>        audience_dict[audience_types[index]] = get_top_zero_shot_prediction(plain_text, category_list)<br>    return audience_dict </pre><p>For the article about the village, the predicted audiences are as follows:</p><blockquote>resonates with men, resonates with middle age people, resonates with medium income, resonates with rural people.</blockquote><p>Whereas for the cosmetics article, the predicted audiences are as follows:</p><blockquote>resonates with women, resonates with young people, resonates with medium income, resonates with urban people.</blockquote><h3>Audience analysis for a list of websites</h3><p>The script extracts content text from each URL, then summarizes it, detects emotions, and identifies the most common emotion. Next, it extracts keywords and predicts audience segments. Finally, it compiles all these attributes into a Pandas DataFrame and saves the data as a CSV file.</p><pre># Initialize an empty list to store the data<br>data = []<br><br># Process each URL<br>for url in urls:<br>    # Extract and process data<br>    plain_text = extract_text_from_https://medium.com/url(url)<br>    summary = summarize_long_text(plain_text)<br>    emotions = detect_emotion(plain_text)<br>    most_common_emotion = get_most_common_emotion(emotions)<br>    keywords = get_keywords_from_text(plain_text)<br>    audience_dict = get_audience_analysis(plain_text)<br>    <br>    # Create a row of data<br>    row = {<br>        &#39;url&#39;: url,<br>        &#39;summary&#39;: summary,<br>        &#39;emotions&#39;: &quot;, &quot;.join(emotions),<br>        &#39;most_common_emotion&#39;: most_common_emotion<br>    }<br>    <br>    # Add audience predictions to the row<br>    for audience_type in audience_types:<br>        row[audience_type] = audience_dict.get(audience_type, &#39;&#39;)<br>    <br>    # Append the row to the data list<br>    data.append(row)<br><br># Create a dataframe from the data<br>df = pd.DataFrame(data)<br><br># Save the dataframe to a CSV file <br>df.to_csv(&#39;output.csv&#39;, index=False)</pre><h3>Render the analysis in a table</h3><p>To present data in a Jupyter notebook, we use tabulate to convert the DataFrame into a well-formatted HTML table. The display function then renders this table, making it visually appealing and easy to read, which allows data presentation within the notebook environment.</p><pre># Display the dataframe as a table<br>table_html = tabulate(df, headers=&#39;keys&#39;, tablefmt=&#39;html&#39;, showindex=False)<br><br># Use IPython.display to render the table<br>display(HTML(table_html))</pre><h3>Conclusions and where to get the full code</h3><p>In this blog, we demonstrated how AI can analyse website audiences by extracting and summarising text, analysing emotions, and predicting audience segments. This approach aids in crafting messages that resonate with different audience types. However, it is important to note that pre-trained models may have biases based on their training data, which could affect the analysis. A thorough ethical evaluation should be conducted before applying these methods in real-world scenarios.</p><p>You can find the full code in this <a href="https://github.com/mauriciotoro/audience_analysis_with_ai">GitHub repository</a>. I welcome your comments, suggestions, and feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1ead9e9355e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining transaction categorisation at scale — Part 2]]></title>
            <link>https://medium.com/@mauriciotorob/streamlining-transaction-categorisation-at-scale-part-2-6f00e8180418?source=rss-4d316c5b2933------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f00e8180418</guid>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Mauriciotorob]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 15:38:20 GMT</pubDate>
            <atom:updated>2024-08-12T15:48:39.285Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streamlining transaction categorisation at scale — Part 2</h3><p>In the <a href="https://medium.com/@mauriciotorob/streamlining-transaction-categorization-at-scale-part-1-2385e31e3861">first part of our blog</a>, we talked about the user-centric approach <a href="https://www.cheddar.me/">Cheddar</a> adopted to enhance its Personal Finance Manager (PFM), focusing on understanding user needs and developing a transaction categorisation system. This involved mapping transaction types to spending categories, ensuring the system was intuitive and useful for users. As we move into the second part, we will explore the processes of data cleaning and mappings, including the extraction of merchant names, linking them to common retailers, and assigning merchant category codes to categories to ensure accurate and efficient transaction categorization.</p><h3><strong>Part 2 — Data cleaning and mappings</strong></h3><ol><li><strong>Merchant Name Extraction</strong></li></ol><p>The development of our merchant name extraction feature also involved a collaborative effort between our engineers and data scientists. The data scientists analysed card payments and direct debits across various banks, identifying distinct patterns to extract merchant names when available. For example, a card payment in certain banks might be recorded as “CARD PAYMENT TO PAYPAL * TESCO,” while in others, it could be reported as “Paypal * Tesco — London, GBP.” In both cases, our system discerns the commonality, extracting the essential merchant name — “PayPal * Tesco.” Similarly, different banks may represent direct debits as “Direct Debit to The Trainline’’ or “DD — Trainline Ref 8938493,” with our unified approach extracting the consistent merchant name — “The Trainline.” This collaborative refinement ensures users with a standardised experience across diverse banking platforms.</p><p>In open banking, card payments must include a field with the merchant name. However, not all banks adhere to this. Some don’t include a merchant name field, and instead, this information is part of the transaction details or another proprietary field. Banks that do not return a merchant name but include it as part of another field often use phrases like “card payment to,” as mentioned above. Additionally, another challenge we encountered is that sometimes the merchant name includes the city name, address, or purchase date. For instance, some banks may include information like “Wagamama Limited 229 London GBR, Transaction Date: 2024–02–02” as part of their transaction details. It was our task to extract “Wagamama Limited” from that field and assign it as the merchant name.</p><p><strong>2. Retailer Mapping</strong></p><p>The data scientists within our engineering team spearheaded the Retailer Mapping initiative, looking into examples across various banks to enhance the recognition of common retailers frequently used by our customers, such as Just Eat or Amazon. In their exploration, they uncovered multiple variations in merchant names for a single retailer, including “Just Eat,” “JUST EAT,” “Paypal * Justeat,” or “CRV * Justeat.” Faced with this complexity, they devised regular expressions to identify and categorise the different retailer names. Given the complexity of this task, the team focused their efforts on a select group of only highly frequented retailers. At the end of this step, all the previous different merchant names for Just Eat will be consolidated into a single retailer.</p><p>This step proved crucial because even after extracting merchant names from open banking transactions, significant variability persisted, as explained. For each highly frequented retailer, a tailored regular expression was necessary to match their name uniformly across different banks. Variations included differences in case sensitivity, parentheses, codes, and truncation lengths, varying from 15 to 18 characters or more across different banks.</p><p>Additionally, payment providers introduced further variability. For instance, PayPal transactions for The Trainline often appeared as “PayPal * thetrainline” without spaces. Similarly, Buy Now Pay Later providers like Zilch or Klarna might truncate names, such as “Zilch * CRV The Trainli.” Despite these challenges, the regular expressions were designed to accurately identify and categorise these transactions under a unified retailer name, such as The Trainline, ensuring consistency. Finally, the data scientists collaborated with the product team led by Tariq Zaid to assign a category and subcategory to each of the frequently found retailers.</p><p><strong>3. Merchant Category Code Mapping</strong></p><p>In handling less common retailers, our adept data scientists adopted a pragmatic approach by examining the Merchant Category Code (MCC) associated with numerous transactions. This code, collaboratively defined by Visa and Mastercard, serves as a framework for categorising merchants utilising card payments. For instance, a code 5411 signifies Grocery Stores and Supermarkets, 5611 denotes Men’s and Boys’ Clothing, and 3504 represents hotels affiliated with Hilton. Through an analysis of the retailers linked to each MCC, our data scientists devised a comprehensive mapping system. This system enables the assignment of specific spend categories to each MCC, ensuring consistent categorization for transactions involving a diverse array of merchants. For example, transactions with code 5611 go to the “fashion” category and a subcategory of “clothing,” while those with code 3504 are linked to the “travel” category with a subcategory of “lodging.”</p><p>To assign categories to the merchant category codes, the data scientists collaborated again with the product team led by Tariq Zaid. The data scientists identified the most common retailers for each MCC and presented this information to the product team. After discussions, they defined a category for each MCC. This required specific knowledge of UK retailers because the MCC standard, initially defined for the United States, has differences. For example, charity shops in the US are seen more as donation centres, whereas in the UK, some national parks or grocery shops are charity organisations. Should a lunch at a national park restaurant be categorised as a donation or as a restaurant expense? This required careful consideration and sometimes overriding the default MCC categorization to fit the UK context accurately.</p><h3>Coming Next</h3><p>In the <a href="https://medium.com/@mauriciotorob/streamlining-transaction-categorisation-at-scale-part-3-0875ca8cc3be">next part of this blog</a>, we’ll discuss how we added Artificial Intelligence (AI) to enhance transaction categorization. We’ll discuss the use of numerical embeddings to handle transactions lacking MCCs, the development of a machine learning model to predict transaction categories, and the human testing process that ensured the accuracy and usability of our system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f00e8180418" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>