<?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 Jair Neto on Medium]]></title>
        <description><![CDATA[Stories by Jair Neto on Medium]]></description>
        <link>https://medium.com/@jair-neto?source=rss-c8821ffb2781------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q25ILdllfooIWTQS_C0BOQ.png</url>
            <title>Stories by Jair Neto on Medium</title>
            <link>https://medium.com/@jair-neto?source=rss-c8821ffb2781------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:18:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jair-neto/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[Best way to fine-tune your LLM using a T4 GPU. Part 3/3]]></title>
            <link>https://jair-neto.medium.com/best-way-to-fine-tune-your-llm-using-a-t4-gpu-part-3-3-71c7d0514aa6?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/71c7d0514aa6</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 21:11:40 GMT</pubDate>
            <atom:updated>2023-12-27T21:11:40.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nglBbPmAWeb0k4WXTGZRkw.jpeg" /></figure><p>In the past medium post, we learned about the theory behind the tools that will allow us today to fine-tune a Large Language Model (LLM). If you do not read them yet, do not lose time and click <a href="https://jair-neto.medium.com/lora-and-qlora-for-fine-tuning-llms-part-2-3-d4ac38ce7e26">here</a> and <a href="https://jair-neto.medium.com/demystifying-large-language-models-for-everyone-fine-tuning-your-own-llm-part-1-3-12d4b0647541">here</a>.</p><p>In this post, you’ll learn insights into the code responsible for loading and preprocessing data for fine-tuning, implementing the techniques covered in previous posts, fine-tuning a model, pushing it to Hugging Face, and enabling you to make inferences effectively.</p><h3>Introduction</h3><p>To start, we need to define the task that we want to achieve, the model that we are going to use, and last but not least the data. But when do we need to fine-tune?</p><p>Before fine-tuning we can test other simpler methods. First, we can start by using the original model and analyzing its behavior in the task just using prompt engineering. Then we could test some techniques like a single shot or a few shot in the prompt to see if the model get the answers right. Depending on the task you can also use Retrieval Augmented Generation (RAG).</p><p>But if after all, the model answers are not good, you can try to switch to a better model or try the fine tuning. It’s worth noting that these techniques are not mutually exclusive and can be combined for a more nuanced approach.</p><h3>Load Model</h3><p>Now let’s go for the fun part, the code part to fine-tuning a LLM model. To begin with the fine-tuning we need first to choose a model to fine-tune. We are going to choose the meta-llama/Llama-2–7b-hf, and to get this model we will use the Hugging Face platform.</p><blockquote>The Hugging Face Hub is a platform with over 350k models, 75k datasets, and 150k demo apps (Spaces), all open source and publicly available, in an online platform where people can easily collaborate and build ML together.</blockquote><p>To get this model you need to follow some steps to get approval to download the model.</p><ol><li>Get approval from Hugging Face (https://huggingface.co/meta-llama/Llama-2-7b-hf).</li><li>Get approval from Meta (https://ai.meta.com/resources/models-and-libraries/llama-downloads/).</li><li>Create a WRITE access token on Hugging Face (https://huggingface.co/settings/tokens).</li></ol><p><em>Note: Make sure your email address on your Hugging Face account is the same as the one you enter on Meta’s website for approval.</em></p><p>To load the model you can use the function below that receives the model_name and the bnb_config. The bnb_config is where we do the quantization of the model.</p><pre>def load_model_tokenizer(model_name: str, bnb_config: BitsAndBytesConfig) -&gt; Tuple[AutoModelForCausalLM, AutoTokenizer]:<br>    &quot;&quot;&quot;<br>    Load the model and tokenizer from the HuggingFace model hub using quantization.<br><br>    Args:<br>        model_name (str): The name of the model.<br>        bnb_config (BitsAndBytesConfig): The quantization configuration of BitsAndBytes.<br><br>    Returns:<br>        Tuple[AutoModelForCausalLM, AutoTokenizer]: The model and tokenizer.<br>    &quot;&quot;&quot;<br><br><br>    model = AutoModelForCausalLM.from_pretrained(<br>        model_name,<br>        quantization_config = bnb_config,<br>        device_map = &quot;auto&quot;, <br>    )<br><br>    tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token = True)<br><br>    tokenizer.pad_token = tokenizer.eos_token<br><br>    return model, tokenizer</pre><h3>Task</h3><p>Now the second step is to have a specific task that you want the model to perform, that the original model is not so good at. In our case we are going to train the model to do text-to-sql. Where we are going to pass as input a query instruction in plain English and a table schema. As output we want the resultant SQL query.</p><h3>Data</h3><p>The data part is probably the most important one, to you fine-tuning success you need to have a good amount of high-quality data. As a rule of thumb, 1000 high-quality examples are a good starting point. In our case, we used <a href="https://huggingface.co/datasets/b-mc2/sql-create-context">b-mc2/sql-create-context</a>.</p><blockquote>There are 78,577 examples of natural language queries, SQL CREATE TABLE statements, and SQL Query answering the question using the CREATE statement as context. This dataset was built with text-to-sql LLMs in mind, intending to prevent hallucination of column and table names often seen when trained on text-to-sql datasets. The CREATE TABLE statement can often be copy and pasted from different DBMS and provides table names, column names and their data types. By providing just the CREATE TABLE statement as context, we can hopefully provide better grounding for models without having to provide actual rows of data, limiting token usage and exposure to private, sensitive, or proprietary data.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-a6CBFLHnABawbgc8gnQQ.png" /><figcaption>Some examples of the data</figcaption></figure><p>To load and shuffle the data you just need to run the code below that uses the hugging face load_dataset function.</p><pre>dataset = load_dataset(&quot;b-mc2/sql-create-context&quot;)<br>shuffled_dataset = dataset[&#39;train&#39;].shuffle(seed=42)</pre><h3>Data Preprocess</h3><p>However we still can not use the data AS IS to train the model. First, we need to do some preprocessing.</p><p>In our case we want the LLM to receive as input an instruction to write from natural language a SQL query, so we need to format the prompt to do so.</p><pre>def format_prompt(example: str) -&gt; str:<br>    &quot;&quot;&quot;&quot;<br>    Format the prompt for the model.<br><br>    Args:<br>        example (str): The example.<br><br>    Returns:<br>        str: The formatted prompt.<br>    &quot;&quot;&quot;<br><br>    final_text  = &quot;&quot;&quot;### Instructions:<br>    Your task is to convert a question into a SQL query, given a Postgres database schema.<br>    Adhere to these rules:<br>    - **Deliberately go through the question and database schema word by word** to appropriately answer the question<br>    - **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`.<br>    - When creating a ratio, always cast the numerator as float<br><br>    ### Input:<br>    Generate a SQL query that answers the question `{question}`.<br>    This query will run on a database whose schema is represented in this string:<br>    {context}<br><br>    ### Response:<br>    {answer}<br>    ### End<br>    &quot;&quot;&quot;.format(question = example[&#39;question&#39;], context = example[&quot;context&quot;], answer = example[&quot;answer&quot;])<br><br>    example[&quot;text&quot;] = final_text<br>    <br>    return example</pre><p>Now we have examples like that:</p><pre>### Instructions:<br>Your task is to convert a question into a SQL query, given a Postgres database schema.<br>Adhere to these rules:<br>- **Deliberately go through the question and database schema word by word** to appropriately answer the question<br>- **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`.<br>- When creating a ratio, always cast the numerator as float<br><br>### Input:<br>Generate a SQL query that answers the question `how many models produced where the plant is castle bromwich?`.<br>This query will run on a database whose schema is represented in this string:<br>CREATE TABLE table_250309_1 (models_produced VARCHAR, plant VARCHAR)<br><br>### Response:<br>SELECT COUNT(models_produced) FROM table_250309_1 WHERE plant = &quot;Castle Bromwich&quot;<br>### End</pre><p>But it does not end there, to making human-readable text into a format that LLMs can understand and work with. We need to tokenize the text. The tokenizer takes plain text as input performs tokenization, and produces tokenized outputs that include token IDs and attention masks. After this step, we have the data ready for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-khVvGhxpOYLw7V0Y4LaQ.png" /><figcaption><a href="https://docs.ai21.com/docs/tokenizer-tokenization">https://docs.ai21.com/docs/tokenizer-tokenization</a></figcaption></figure><pre>def preprocess_dataset(tokenizer: AutoTokenizer,<br>                       max_length: int,<br>                       seed: int,<br>                       columns_to_remove: List[str],<br>                       dataset: DatasetDict) -&gt; DatasetDict:<br>    &quot;&quot;&quot;<br>    Preprocess the dataset for training.<br><br>    Args:<br>        tokenizer (AutoTokenizer): The tokenizer.<br>        max_length (int): The maximum length of the model.<br>        seed (int): The seed for shuffling the dataset.<br>        columns_to_remove (List[str]): The columns to remove from the dataset.<br>        dataset (DatasetDict): The Hugging face dataset.<br><br>    Returns:<br>        DatasetDict: The preprocessed dataset.<br>    &quot;&quot;&quot;<br><br>    _preprocessing_function = partial(tokenize_batch, max_length = max_length, tokenizer = tokenizer)<br>    dataset = dataset.map(<br>        _preprocessing_function,<br>        batched = True,<br>        remove_columns = columns_to_remove,<br>    )<br><br>    dataset = dataset.filter(lambda sample: len(sample[&quot;input_ids&quot;]) &lt; max_length)<br><br>    dataset = dataset.shuffle(seed = seed)<br><br>    return dataset</pre><h3>QLoRA</h3><p>In the coding section, the QLoRA process is divided into two components: quantization and the addition of LoRA matrices. To facilitate quantization with a Large Language Model (LLM) loaded using Hugging Face, we leverage the <a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes.">bitsandbytes</a> library.</p><p>For the incorporation of new LoRA weight matrices, we employ a library named <a href="https://huggingface.co/blog/peft">peft</a> (Parameter-Efficient Fine-Tuning). These libraries empower us to implement all the QLoRA optimizations discussed in the <a href="https://jair-neto.medium.com/lora-and-qlora-for-fine-tuning-llms-part-2-3-d4ac38ce7e26">post</a>, including the utilization of 4-bit Normal Floats, double quantization, and the addition of LoRA adapters.</p><p>In the function below, we establish all the configurations necessary to optimize the use of QLoRA.</p><pre>   def get_qlora_configs(load_in_4bit: bool,<br>                         bnb_4bit_use_double_quant: bool,<br>                         bnb_4bit_quant_type: str,<br>                         bnb_4bit_compute_dtype: torch.dtype,<br>                         r: int,<br>                         lora_alpha: int,<br>                         target_modules: Union[List[str],str],<br>                         lora_dropout: float,<br>                         bias: str,<br>                         task_type: str) -&gt; Tuple[BitsAndBytesConfig, LoraConfig]:<br>    &quot;&quot;&quot;<br>    Create the configurations for use QLoRA thechniques<br><br>    Args:<br>        load_in_4bit (bool): This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from<br>            `bitsandbytes`.<br>        bnb_4bit_use_double_quant (bool): This flag is used for nested quantization where the quantization constants from the first quantization are<br>            quantized again.<br>        bnb_4bit_quant_type (str): This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types<br>            which are specified by `fp4` or `nf4`.<br>        bnb_4bit_compute_dtype (torch.dtype): This sets the computational type which might be different than the input time. For example, inputs might be<br>            fp32, but computation can be set to bf16 for speedups.<br>        r (int): Lora attention dimension.<br>        lora_alpha (int): The alpha parameter for Lora scaling.<br>        target_modules (Union[List[str],str]): The names of the modules to apply Lora to.<br>        lora_dropout (float): The dropout probability for Lora layers.<br>        bias (str): Bias type for Lora. Can be &#39;none&#39;, &#39;all&#39; or &#39;lora_only&#39;. If &#39;all&#39; or &#39;lora_only&#39;, the<br>            corresponding biases will be updated during training. Be aware that this means that, even when disabling<br>            the adapters, the model will not produce the same output as the base model would have without adaptation.<br>        task_type (str): The task type for the model.<br><br>    Returns:<br>        Tuple[BitsAndBytesConfig, LoraConfig]: The configuration for BitsAndBytes and Lora.<br>    &quot;&quot;&quot;<br><br>    bnb_config = BitsAndBytesConfig(<br>        load_in_4bit = load_in_4bit,<br>        bnb_4bit_use_double_quant = bnb_4bit_use_double_quant,<br>        bnb_4bit_quant_type = bnb_4bit_quant_type,<br>        bnb_4bit_compute_dtype = bnb_4bit_compute_dtype,<br>    )<br><br>    lora_config = LoraConfig(<br>        r = r,<br>        lora_alpha = lora_alpha,<br>        target_modules = target_modules,<br>        lora_dropout = lora_dropout,<br>        bias = bias,<br>        task_type = task_type,<br>    )<br><br>    bnb_config, lora_config</pre><h3>Fine-tuning</h3><p>For fine-tuning the model we need to first follow some steps.</p><p>Step 1: Prepare the model</p><pre>def preprare_model_for_fine_tune(model: AutoModelForCausalLM,<br>                                 lora_r: int,<br>                                 lora_alpha: int,<br>                                 lora_dropout: float,<br>                                 bias: str,<br>                                 task_type: str) -&gt; AutoModelForCausalLM:<br>    &quot;&quot;&quot;<br>    Prepares the model for fine-tuning.<br><br>    Args:<br>        model (AutoModelForCausalLM): The model that will be fine-tuned.<br>        lora_r (int): Lora attention dimension.<br>        lora_alpha (int): The alpha parameter for Lora scaling.<br>        lora_dropout (float): The dropout probability for Lora layers.<br>        Bias type for Lora. Can be &#39;none&#39;, &#39;all&#39; or &#39;lora_only&#39;. If &#39;all&#39; or &#39;lora_only&#39;, the<br>            corresponding biases will be updated during training. Be aware that this means that, even when disabling<br>            the adapters, the model will not produce the same output as the base model would have without adaptation.<br>        task_type (str): The task type for the model.<br><br>    Returns:<br>        AutoModelForCausalLM: The model prepared for fine-tuning.<br>    &quot;&quot;&quot;<br>    # Enable gradient checkpointing to reduce memory usage during fine-tuning<br>    model.gradient_checkpointing_enable()<br><br>    # Prepare the model for training<br>    model = prepare_model_for_kbit_training(model)<br><br>    # Get LoRA module names<br>    target_modules = find_all_linear_names(model)<br><br>    # Create PEFT configuration for these modules and wrap the model to PEFT<br>    peft_config = create_peft_config(lora_r, lora_alpha, target_modules, lora_dropout, bias, task_type)<br>    model = get_peft_model(model, peft_config)<br><br>    model.config.use_cache = False<br><br>    return model</pre><p>In the code above we start by calling the <em>gradient_checkpointing_enable </em>function to significantly reduce GPU memory usage. This feature helps free up a substantial amount of memory, although it comes with a slight trade-off: a modest decrease in training speed due to recomputing parts of the graph during back-propagation. For more read the paper <a href="https://arxiv.org/abs/1604.06174">Training Deep Nets with Sublinear Memory Cost</a>. After that we use the best practice of PEFT lib so we prepare the model for quantization using <em>prepare_model_for_kbit_training</em>. Finally we apply the LoRA, get the PEFT model, and since we want to fine-tune the model we have to set the use_cache to False.</p><p>Step 2. Configure the trainer parameters</p><pre>print_trainable_parameters(model)<br><br># Training parameters<br>trainer = Trainer(<br>    model = model,<br>    train_dataset = dataset,<br>    args = TrainingArguments(<br>        per_device_train_batch_size = per_device_train_batch_size,<br>        gradient_accumulation_steps = gradient_accumulation_steps,<br>        warmup_steps = warmup_steps,<br>        learning_rate = learning_rate,<br>        fp16 = fp16,<br>        logging_steps = logging_steps,<br>        output_dir = output_dir,<br>        optim = optim,<br>        num_train_epochs=num_train_epochs<br>    ),<br>    data_collator = DataCollatorForLanguageModeling(tokenizer, mlm = False)<br>)</pre><p>Here we set the parameters that we need to use to fine tune the model. To get more information about them you can access its <a href="https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments">documentation</a>.</p><p>Step 3. Fine tune the model, save the metrics, save the model and free the gpu memory for not giving Out Of Memory errors.</p><pre>def fine_tune(model: AutoModelForCausalLM, trainer: Trainer, output_dir: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Fine-tune the model.<br><br>    Args:<br>        model (AutoModelForCausalLM): The model to fine-tune.<br>        trainer (Trainer): The trainer with the training configuration.<br>        output_dir (str): The output directory to save the model.<br>    &quot;&quot;&quot;<br><br>    print(&quot;Training...&quot;)<br><br>    train_result = trainer.train()<br><br>    save_metrics(train_result, trainer)<br>    save_model(model, output_dir)<br>    free_memory(model, trainer)</pre><h3>Pushing the model</h3><p>Now that we have our fine-tuned model, we need to push to the huggingFace hub in order to use it.</p><pre>model = AutoPeftModelForCausalLM.from_pretrained(output_dir, device_map = &quot;auto&quot;, torch_dtype = torch.bfloat16)<br><br>model = model.merge_and_unload()<br><br># Save fine-tuned model at a new location<br>output_merged_dir = &quot;results/sql_classification_llama2_7b/final_merged_checkpoint&quot;<br>os.makedirs(output_merged_dir, exist_ok = True)<br>model.save_pretrained(output_merged_dir, safe_serialization = True)<br><br># Save tokenizer for easy inference<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>tokenizer.save_pretrained(output_merged_dir)<br><br># Push fine-tuned model and tokenizer to Hugging Face Hub<br>model.push_to_hub(new_model, use_auth_token = True)<br>tokenizer.push_to_hub(new_model, use_auth_token = True)</pre><ol><li>Load the Fine-Tuned model.</li><li>Merge the LoRA matrix weights into the base model.</li><li>Save the merged model.</li><li>Save the tokenizer.</li><li>Push the model and tokenizer to Hugging Face Hub.</li></ol><h3>Inference</h3><p>Now to use your brand new fine-tuned model you just need to load the model, that it&#39;s now in Hugging Face Hub. Replace the “&lt;fine_tuned_model_name&gt;” and “&lt;tokenizer_name&gt;” for the ones that you uploaded to the Hub.</p><pre>torch.set_default_device(&#39;cuda&#39;)<br>model = AutoModelForCausalLM.from_pretrained(&quot;&lt;fine_tuned_model_name&gt;&quot;, trust_remote_code=True, torch_dtype=&quot;auto&quot;)<br>tokenizer = AutoTokenizer.from_pretrained(&quot;&lt;tokenizer_name&gt;&quot;, trust_remote_code=True, torch_dtype=&quot;auto&quot;)</pre><p>After you load the model, you need to create a function in order to use it for returning the SQL query.</p><p>In the function, we format the prompt and use a regex to extract only the SQL query.</p><pre>def print_inference(model: AutoModelForCausalLM, tokenizer: AutoTokenizer, question: str, context: str, answer: str) -&gt; None:<br>    &quot;&quot;&quot;<br>    Print the inference from the model.<br><br>    Args:<br>        model (AutoModelForCausalLM): Fine-tuned model.<br>        tokenizer (AutoTokenizer): Tokenizer.<br>        question (str): The natural language question.<br>        context (str): The database schema.<br>        answer (str): The query answer.<br>    &quot;&quot;&quot;<br><br>    message = f&#39;&#39;&#39;<br>    ### Instructions:<br>    Your task is to convert a question into a SQL query, given a Postgres database schema.<br>    Adhere to these rules:<br>    - **Deliberately go through the question and database schema word by word** to appropriately answer the question<br>    - **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`.<br>    - When creating a ratio, always cast the numerator as float<br><br>    ### Input:<br>    Generate a SQL query that answers the question `{question}`.<br>    This query will run on a database whose schema is represented in this string:<br>    {context}<br><br>    ### Response:<br>    &#39;&#39;&#39;<br>    inputs = tokenizer(message, return_tensors=&quot;pt&quot;, return_attention_mask=False)<br><br>    outputs = model.generate(**inputs, max_length=400)<br><br>    print_extracted_answer(tokenizer.batch_decode(outputs)[0])</pre><p>Now you are ready to go and use the model to generate SQL queries.</p><p>Below you have some example generated by the fine tuned model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqkMwIbQXXxojlrX-RwCoA.png" /></figure><p>You can run the code used in this post in this <a href="https://colab.research.google.com/drive/1aC0S9V31eHX87RY6cjCeBo397DM9NUWd?usp=sharing">Colab</a>.</p><h3>Next Steps</h3><ul><li>Compare the results from the fine-tuned model with the original model.</li><li>If the results are not satisfactory, fine-tune the model with more data or select observations with higher quality.</li><li>Build a UI and deploy the model so anyone can use it and add in the UI feedback in order to improve the model.</li></ul><h3>Greetings</h3><p>This post was inspired by the posts of <a href="https://medium.com/@kshitiz.sahay26">Kshitiz Sahay </a>.</p><h3>P.S.</h3><p>Now that you know the theory and the code behind fine-tuning a model, you can use some library to fine-tune a model easily and even locally (If you have the needed hardware).</p><p>One option is to use <a href="https://huggingface.co/docs/autotrain/index/">Auto train</a> from Hugging Face.</p><p>Another option is using services like <a href="https://www.lamini.ai/">https://www.lamini.ai/</a>.</p><p>Feel free to reach me with any comments on my <a href="https://www.linkedin.com/in/jair-guedes-ferreira-neto/">Linkedin</a> account and thank you for reading this post.</p><p>If you like what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts.</p><h3>References</h3><p><a href="https://colab.research.google.com/drive/1aC0S9V31eHX87RY6cjCeBo397DM9NUWd#scrollTo=tCbnhnxtnhvh">https://colab.research.google.com/drive/1aC0S9V31eHX87RY6cjCeBo397DM9NUWd#scrollTo=tCbnhnxtnhvh</a></p><p><a href="https://huggingface.co/docs/transformers/v4.18.0/en/performance">Performance and Scalability: How To Fit a Bigger Model and Train It Faster</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71c7d0514aa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LoRA and QLoRA for fine-tuning LLMs. Part 2/3]]></title>
            <link>https://jair-neto.medium.com/lora-and-qlora-for-fine-tuning-llms-part-2-3-d4ac38ce7e26?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4ac38ce7e26</guid>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[llama-2]]></category>
            <category><![CDATA[qlora]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 21:13:59 GMT</pubDate>
            <atom:updated>2023-11-06T21:13:59.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtcReJVjLwY2LHoIABqwMQ.jpeg" /><figcaption>2Image generated by Dall-E 3</figcaption></figure><p>In our <a href="https://medium.com/@jair-neto/demystifying-large-language-models-for-everyone-fine-tuning-your-own-llm-part-1-3-12d4b0647541">previous article,</a> we delved into the fundamentals of fine-tuning a Large Language Model (LLM) on a T4 GPU, exploring concepts like gradients, optimizers, and quantization. Now, let’s take the next step in this journey.</p><p>In this post, we’ll introduce you to a powerful technique known as LoRA (Low Rank Adaptation). LoRA, as detailed in the paper “<a href="https://arxiv.org/pdf/2106.09685.pdf">LoRA: Low-Rank Adaptation of Large Language Models</a>” published in October 2021, is the key that unlocks the path to creating your very own custom LLM, fine-tuned with your unique data.</p><h3>Introduction</h3><p>Let’s begin with the main hypothesis of the paper</p><blockquote>When adapting to a specific task, Aghajanyan et al. (2020) shows that the pre-trained language models have a low “intrinsic dimension” and can still learn efficiently despite a random projection to a smaller subspace. Inspired by this, we hypothesize the updates to the weights also have a low “intrinsic rank” during adaptation.</blockquote><p>But, let’s translate these hypotheses to plain english. To start, let me remind you of the concepts that you probably have learned in Linear Algebra.</p><h3>Low Intrinsic Dimension</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*Ggs7BKyakc2LTkxt" /><figcaption>Single Dot Image</figcaption></figure><p>This idea centers on the ability to compress the weight matrix of a Large Language Model (LLM) into a smaller, more manageable subspace without causing major changes in its behavior. To grasp this concept, picture a massive black and white image, a thousand pixels by a thousand, with just a single dot. It’s easy to see that you don’t need a million pixel values to precisely represent that single dot. In such cases, the pixel matrix of the image possesses a low intrinsic dimension because you can convey its content with much less data, making it a more efficient representation. This notion is similar to how we can capture essential information using a smaller subspace in Linear Algebra.</p><h3><em>Inspired by this, we hypothesize the updates to the weights also have a low “intrinsic rank” during adaptation</em></h3><p>The rank of a matrix represents the maximum number of rows or columns that are linearly independent. It’s the largest set of columns (or rows) that cannot be expressed as a linear combination of the others.</p><p>So if we have the matrix A the rank is equal to 1, because we can represent the second column as a linear combination of the first column, just multiplying it by 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*HPE2eJ7O45htllO2ZACjxQ.gif" /></figure><p>But in the example B below the rank is 2, because no column can be expressed as a linear combination of the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/1*gmXTBHDWqhjY5TK4ncW__g.gif" /></figure><h3>LoRA</h3><p>Here’s where the magic of LoRA comes into play. Instead of fine-tuning all the individual matrix weights of a Large Language Model (LLM), LoRA takes a different approach. It introduces two low-rank matrices, and the key here is to keep these matrices as small as possible, containing the fewest elements necessary. This clever technique allows for efficient adaptation without the need to fine-tune every single matrix weight</p><p>In traditional fine tuning we usually train all the models weights as we can see in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/0*SsfatbKDFh77cyLc" /><figcaption>In this image we can see the traditional way of fine tuning a model, where we update all the model weights. Extracted from <a href="https://www.youtube.com/watch?v=dA-NhCtrrVE">https://www.youtube.com/watch?v=dA-NhCtrrVE</a></figcaption></figure><p>In LoRA we replace the huge weight update matrix, by a decomposition of two matrix A and B assuming that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*97bpr4eIcJr1oba3Gkz5DA.gif" /></figure><p>and the rank r ≪ min(d,k). Now we only train A and B. Freezing the pretrained weights. You can see an image representation of the process below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*UzcrAv_awJGBtwvD" /><figcaption>The Lora way of fine-tuning. Extracted from <a href="https://www.youtube.com/watch?v=dA-NhCtrrVE">https://www.youtube.com/watch?v=dA-NhCtrrVE</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*iJY9E-E6A_FAQUWc" /><figcaption>Image from the paper</figcaption></figure><h3>Advantages of LoRA</h3><h4>Memory and Speed</h4><p>LoRA improves training efficiency and reduces the hardware requirements by up to three times when using adaptive optimizers. This is because we no longer need to calculate gradients or maintain optimizer states for most parameters. Instead, we focus on optimizing smaller matrices that we add to the model and the number of trainable parameters W can be as small as 0.01%</p><h4>Adaptability</h4><p>Since we have to only train two small matrix. This allows us to share a pre-trained model and create multiple smaller LoRA modules for various tasks. We can ‘freeze’ the shared model and efficiently switch between tasks by making small changes, reducing the need for extensive storage and speeding up the task-switching process. Like we could have N LoRA modules trained for a specific task, and just add them to the LLM weights,</p><h4>No additional delay at inference</h4><p>To deploy in production we need just to add W0 + BA and performance inference normally. Because both W0 and BA are dXk.</p><h4>Robust to catastrophic forgetting</h4><p>Catastrophic forgetting is the phenomenon that occurs when we fine-tune a deep learning model and the model ‘forgets’ what it has learned. Since we freeze the LLM weights and train new ones, LoRA also makes the LLM learn new tasks with a low probability of losing prior knowledge.</p><h3>QLoRA</h3><p>But there were room for improvement and in May 2023 was realized the paper “<a href="https://arxiv.org/pdf/2305.14314.pdf">QLoRA: Efficient Fine Tuning of Quantized LLMs</a>”</p><p>QLora introduces 3 main improvements to LoRA.</p><h4>4-bit NormalFloat</h4><blockquote>An information theoretically optimal quantization data type for normally distributed data that yields better empirical results than 4-bit Integers and 4-bit Floats.</blockquote><h4>Double Quantization</h4><blockquote>A method that quantizes the quantization constants, saving an average of about 0.37 bits per parameter (approximately 3 GB for a 65B model).</blockquote><h4>Paged Optimizers</h4><blockquote>Using NVIDIA unified memory to avoid the gradient checkpointing memory spikes that occur when processing a mini-batch with a long sequence length.</blockquote><h3>How QLORA works?</h3><ol><li>First quantize the LLM to 4 bits (NF4).</li><li>Each element in the matrix is stored using only 4 bits.</li><li>Then we do a LoRA training in 16 bit precision BFloat16.</li><li>And the process goes like this. Only when we are training the LoRA adapters do we dequantize (convert back) the model to do the model weights to BFloat16 and then convert back to NF4.</li></ol><h3>Summarize</h3><p>To summarize, QLORA has one storage data type (usually 4-bit NormalFloat) and a computation data type (16-bit BrainFloat). We dequantize the storage data type to the computation data type to perform the forward and backward pass, but we only compute weight gradients for the LoRA parameters which use 16-bit BFloat.</p><p>The key takeaway is that QLoRA significantly cuts the average memory needs for fine-tuning a 65B parameter model from over 780GB of GPU memory to less than 48GB. Importantly, this efficiency doesn’t compromise runtime or predictive performance when compared to a 16-bit fully finetuned baseline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IQpbnQPlUDzSbv7Z" /><figcaption>Image from the QLoRA paper</figcaption></figure><h3>Paper Results</h3><p>The research findings consistently support the effectiveness of 4-bit QLoRA fine-tuning with NF4 data type, showcasing performance on par with 16-bit full fine-tuning and 16-bit LoRA fine-tuning across established academic benchmarks. Moreover, it highlights that NF4 outperforms FP4 and that double quantization has no detrimental impact. These results provide compelling evidence that 4-bit QLoRA fine-tuning reliably matches the performance of 16-bit methods. The study covers an extensive range of over 1,000 fine-tuned models, offering insights into instruction following and chatbot performance across various datasets, model types, and scales, including large parameter models. Notably, QLoRA fine-tuning on a small, high-quality dataset leads to state-of-the-art results, even with smaller models. The research also underscores the cost-effectiveness of GPT-4 evaluations as an alternative to human evaluations for assessing chatbot performance and raises questions about the reliability of current chatbot benchmarks. Additionally, it provides an analysis of where Guanaco falls short compared to ChatGPT and makes all models and code, including CUDA kernels for 4-bit training, available to the community.</p><h3>Conclusion</h3><p>You’ve learned about LoRA, with its smart approach of using low-rank matrices, opens up new possibilities for tailoring LLMs to specific tasks while reducing memory requirements and enhancing adaptability. The recent advancements in QLoRA further refine this process by introducing 4-bit NormalFloat, double quantization, and paged optimizers, which collectively optimize the efficiency of fine-tuning. These developments are not just theoretical; they have been rigorously tested and found to consistently match or outperform traditional 16-bit methods across various benchmarks.</p><p>This marks an exciting step toward democratizing the use of Large Language Models and fine-tuning for a broader audience.</p><p>With LoRA and QLoRA, we have the tools to create more efficient, adaptive, and cost-effective language models, heralding a new era of possibilities for AI and NLP applications</p><p>Now, the 7-billion parameters, loaded as 4-bit NormalFloat (4NF), occupy a mere 3.5GB of memory. We allocate 1GB for LoRA parameters, another 1GB for gradients, and 4GB for optimizer states. With an additional 4GB set aside for memory peak activations during training, we now require just 13.5GB for the fine-tuning process. You’ve grasped the complexities and their solutions for training your custom LLM with your data.</p><h3>Up Next</h3><p>In the upcoming article, we’ll roll up our sleeves and dive into the code, putting all these concepts into action. Stay tuned for the practical implementation!</p><p>Feel free to reach me with any comments on my <a href="https://www.linkedin.com/in/jair-guedes-ferreira-neto/">Linkedin</a> account and thank you for reading this post.</p><p>If you like what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts.</p><h3>References</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdA-NhCtrrVE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdA-NhCtrrVE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdA-NhCtrrVE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f219bb3bdad7b964b2897dd07fe4316/href">https://medium.com/media/2f219bb3bdad7b964b2897dd07fe4316/href</a></iframe><p><a href="https://huggingface.co/docs/diffusers/main/en/training/lora">https://huggingface.co/docs/diffusers/main/en/training/lora</a></p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//arxiv.org/pdf/2106.09685.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/52b546326bf5cf112b01b1d7341076a2/href">https://medium.com/media/52b546326bf5cf112b01b1d7341076a2/href</a></iframe><p><a href="https://medium.com/@amodwrites/a-definitive-guide-to-qlora-fine-tuning-falcon-7b-with-peft-78f500a1f337">A Definitive Guide to QLoRA: Fine-tuning Falcon-7b with PEFT</a></p><p><a href="https://medium.com/@gitlostmurali/understanding-lora-and-qlora-the-powerhouses-of-efficient-finetuning-in-large-language-models-7ac1adf6c0cf">https://medium.com/@gitlostmurali/understanding-lora-and-qlora-the-powerhouses-of-efficient-finetuning-in-large-language-models-7ac1adf6c0cf</a></p><p><a href="https://huggingface.co/blog/4bit-transformers-bitsandbytes">Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA</a></p><p><a href="https://blog.lancedb.com/optimizing-llms-a-step-by-step-guide-to-fine-tuning-with-peft-and-qlora-22eddd13d25b"><strong>https://blog.lancedb.com/optimizing-llms-a-step-by-step-guide-to-fine-tuning-with-peft-and-qlora-22eddd13d25b</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4ac38ce7e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Large Language Models for Everyone: Fine-Tuning Your Own LLM. Part 1/3]]></title>
            <link>https://jair-neto.medium.com/demystifying-large-language-models-for-everyone-fine-tuning-your-own-llm-part-1-3-12d4b0647541?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/12d4b0647541</guid>
            <category><![CDATA[llama-2]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 23:07:01 GMT</pubDate>
            <atom:updated>2023-10-16T23:07:01.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqLaePsVhiL7jv36sAwuDQ.jpeg" /><figcaption>Image generated by Dall-E 3</figcaption></figure><p>The first thing that you have to keep in mind is that LLM stands for Large Language Models,they are immense models comprising billions of parameters, and their huge size, coupled with the vast amount of data used for training lends them their almost magic capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s_bWg4wJUfpl5pzq" /><figcaption>Image showing the number of parameters of LLMs extracted from <a href="https://pureinsights.com/blog/2023/what-are-large-language-models-llms-search-and-ai-perspectives/">https://pureinsights.com/blog/2023/what-are-large-language-models-llms-search-and-ai-perspectives/</a></figcaption></figure><p>However, this presents a challenge for many of us, as these models demand substantial computational resources. <a href="https://www.wired.com/story/openai-ceo-sam-altman-the-age-of-giant-ai-models-is-already-over/">Sam Altman once mentioned that training GPT-4 came with a staggering cost of 100 million dollars.</a></p><p>In this series, we will delve into the first solution that allows us to fine-tune an LLM using a standard 16GB T4 GPU, making this powerful technology more accessible to a broader audience.</p><h3>What you will learn</h3><ul><li>Gradients</li><li>Optimizer States</li><li>Techniques to decrease the memory usage of LLMs</li><li>Quantization</li><li>Finishing</li></ul><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*b_tbjpK00Dm-cbtZ" /><figcaption><a href="https://industrywired.com/meta-teams-up-with-microsoft-for-its-open-source-ai-model-llama/">https://industrywired.com/meta-teams-up-with-microsoft-for-its-open-source-ai-model-llama/</a></figcaption></figure><p>In this example, we’ll be working with the Meta Llama 7B model, a model with 7 billion parameters. Each parameter is represented as a 32-bit floating-point number, occupying 4 bytes of memory. To simply load this model into memory, we require a staggering 28 gigabytes of memory 7 Billions (of model parameters) * 4 Bytes (32 floating point size) = 28 GBs. Using a T4 GPU, we would have an “Out of Memory” (OOM) error.</p><p>However, loading the model is just the beginning. The fine-tuning process involves two additional memory-intensive steps: managing the gradients and the optimizer’s states. These steps further add to the memory requirements, making efficient memory management an essential aspect of working with such large-scale models.</p><h3>Let’s Start By the Gradients</h3><p>Gradiantes play a pivotal role in training machine learning models.</p><p>They are the centerpiece that enables models to really learn about the data and improve their performance over the training process. During the training process, the model learns using a technique called Gradient Descent.</p><h3>Gradient Descent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*LNbvbTC1yIU1Tm-VRO8IPg.png" /><figcaption><em>Source: Clairvoyant</em></figcaption></figure><p>To learn more about Gradient Descent you can read my <a href="https://medium.com/analytics-vidhya/stop-just-using-machine-learning-and-learn-how-to-build-it-linear-regression-and-gradient-descent-3653de24c6d5">article</a> about gradient descent in the linear regression model.</p><p>But summarizing it in Gradient Descent we minimize a loss function by iteratively adjusting model parameters based on calculated gradients and a learning rate. So gradients are essentially partial derivatives that indicate the direction and magnitude of the parameters changes to minimize the model loss.</p><p>Typically, there’s one gradient for each model parameter. Therefore, in the case of a 7-billion-parameter model, we’re dealing with 7 billion gradients, each occupying 4 bytes of memory. This totals to a memory requirement of 28 gigabytes, just for storing the gradients.</p><h3>Optimizer States</h3><p>Now that you learned about gradients and gradient descent, for fine tuning large language models we could use Stochastic Gradient Descent (SGD), but we usually use an Optimizer called Adam, often we use a variant known as AdamW. (<a href="https://towardsdatascience.com/why-adamw-matters-736223f31b5d">https://towardsdatascience.com/why-adamw-matters-736223f31b5d</a>)</p><p>In this process is where we update the LLM parameters weights and for that we need to store the Vt and the St as you can see in the image below. So 7B * 4 (bytes) * 2 (Vt and St) = 56GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*it9TbgHut1-lJKY4" /><figcaption><a href="https://www.aiplusinfo.com/blog/what-is-the-adam-optimizer-and-how-is-it-used-in-machine-learning/">https://www.aiplusinfo.com/blog/what-is-the-adam-optimizer-and-how-is-it-used-in-machine-learning/</a></figcaption></figure><p>Totalizing 28 + 28 + 56 = 112 GB needed to train the model using 32 floating point variables.</p><h3>Techniques</h3><p>Among the techniques available to tackle the memory challenge, a straightforward approach involves transitioning from 32-bit floating-point precision to 16-bit precision. This adjustment effectively reduces memory consumption by half, transforming the requirement from 112 gigabytes to 56 gigabytes. However, this approach comes with a trade-off: by simply opting for 16-bit floating-point representation, we reduce memory usage but also limit the model’s ability to represent approximately ±65k distinct values. When we are using 32 bits floating points we could represent ±2 billions distinct values.</p><h3>Quantization</h3><p>Quantization it’s essentially the process of mapping continuous values to discrete values. In our case 32 bit floating point to 8 bits integers.</p><p>But this is a challenge, because now we have to convert billions of numbers to only 255 values of int8, without losing too much of model accuracy.</p><p>The quantization process usually consists of two key steps: calibration and quantization itself.</p><p>The goal of Calibration is to find the best α factor to maximize precision, after the α is calibrated we use the formula below to realize the quantization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/0*-v3UrsqeRFWuGy2p" /><figcaption>Formula to realize the quantization</figcaption></figure><p>We’re looking at a range of numbers, and anything beyond a certain range (let’s call it the “α-interval”) will be cut off or clipped. Anything within this range will be rounded to the nearest int8 number. It’s important to choose this range carefully. If the range is too big, it can include a lot of numbers, but that might lead to rough approximations and high errors, both from clipping and rounding. So, picking the right range is often about finding a balance between making mistakes by cutting off numbers and making mistakes by rounding them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oplHHSHBB_3301Md" /><figcaption>Mapping values to int8. Source: <a href="https://deci.ai/quantization-and-quantization-aware-training/">https://deci.ai/quantization-and-quantization-aware-training/</a></figcaption></figure><p>So now we would have 7 * 1 + 7 * 1 + 7 * 2 * 1 = 28GB (where 7 stands for the number of model parameters, 1 it’s one byte for the int8 and 2 stands for the 2 values in optimizer states that we need to keep). We are now close to fitting the model in the 16GB T4 GPU memory.</p><h3>Finishing</h3><p>In this article you learned about:</p><ul><li>Model Size: Large Language Models (LLMs) are massive, with billions of parameters, making them resource-intensive to work with.</li><li>Gradients: Storing gradients for a 7-billion-parameter LLM alone requires a whopping 28GB of memory.</li><li>Optimizers: Advanced optimizers like AdamW are commonly used in LLM fine-tuning, contributing to memory requirements.</li><li>Precision Change: Transitioning from 32-bit floating-point precision to 16-bit can halve memory usage, but it comes with a trade-off of reduced representational capacity.</li><li>Quantization: Quantization is a technique that maps continuous values to discrete ones, a strategy employed to reduce memory usage. However, it necessitates a careful balance between memory efficiency and model accuracy.</li></ul><p>Feel free to reach me with any comments on my <a href="https://www.linkedin.com/in/jair-guedes-ferreira-neto/">Linkedin</a> account and thank you for reading this post.</p><p>If you like what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts.</p><h3>Up Next</h3><p>In the next article I am going to talk more about a technique called low rank adaptation (LoRA) that will continue to help us in the process of fine tuning LLM models.</p><h3>References</h3><p><a href="https://huggingface.co/docs/optimum/concept_guides/quantization">https://huggingface.co/docs/optimum/concept_guides/quantization</a></p><p><a href="https://towardsdatascience.com/why-adamw-matters-736223f31b5d">https://towardsdatascience.com/why-adamw-matters-736223f31b5d</a></p><p><a href="https://medium.com/@rakeshrajpurohit/model-quantization-with-hugging-face-transformers-and-bitsandbytes-integration-b4c9983e8996">https://medium.com/@rakeshrajpurohit/model-quantization-with-hugging-face-transformers-and-bitsandbytes-integration-b4c9983e8996</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12d4b0647541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Linear Regression from Scratch using Python]]></title>
            <link>https://medium.com/analytics-vidhya/multiple-linear-regression-from-scratch-using-python-db9368859f?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/db9368859f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 10:08:15 GMT</pubDate>
            <atom:updated>2021-08-26T10:08:15.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7p5qgdsbq9pI3l0a05vKg.jpeg" /><figcaption>Image from Marvel</figcaption></figure><p>In the previous post, you learned how to implement a simple linear regression from scratch using only NumPy. In today’s post, I will show how to implement a multiple linear regression from scratch also using only NumPy.</p><h3>Multiple Linear Regression</h3><p>In the simple linear regression, we want to predict the dependent variable ‘y’ using only one explanatory variable ‘x’ like the equation below.</p><p>y= ax + b</p><p>‘y’ is the dependent variable, ‘x’ is the explanatory variable, ‘a’ is the slope of the line, and ‘b’ is the intercept variable in other words the value of ‘y’ when ‘x’ is zero. On a linear regression, we want to find the values of ‘a’ and ‘b’ that minimizes the prediction errors.</p><p>Multiple Linear Regression is an extension of linear regression used when you have more than one explanatory variable to predict the dependent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*jxT4G7TV9Po1d5Ad-u1jKg.png" /><figcaption>Fig1. Multiple linear regression formula</figcaption></figure><p>Where for i=n observations:</p><ul><li>Y = Is the dependent Variable.</li><li>Xs = Are the explanatory variables.</li><li><em>ß</em>0 = Is the y-intercept (constant term).</li><li>The others<em> ß a</em>re the slope coefficients for each explanatory variable.</li><li>The <em>ß are also called weights.</em></li></ul><p>If you pay attention, the linear regression is a simple version of the multiple regression where all the <em>ß</em> terms from <em>ß2</em> to <em>ßp</em> are zero.</p><p>As an example, let’s assume that you want to sell your car and want to estimate how much your car is worth it. You know that factors such as model year, horsepower, and mileage influence the car price. In that case, you could create a multiple linear regression like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9zP46joqSnn_8GDyDi--w.png" /><figcaption>Fig2. A Multiple Linear Regression example.</figcaption></figure><h4>But how can I know what are the best values of the Betas?</h4><p>This part it’s similar to the simple linear regression. We want to minimize the cost function using the Gradient Descent Technique. If you don’t know what those terms are you can learn them in <a href="https://medium.com/analytics-vidhya/stop-just-using-machine-learning-and-learn-how-to-build-it-linear-regression-and-gradient-descent-3653de24c6d5">my medium post</a>.</p><p>From my previous post, you know that the cost function is the function below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*VGVT_2igYyERDagUyFlCPw.png" /><figcaption>Fig3. The simple linear regression error function. Where n is the number of observations in the data, ȳ are the predicted values and y are the actual values</figcaption></figure><p>And our goal was to find the values of ‘a’ and ‘b’ that minimizes the value of the cost function. The derivatives from the simple linear regression where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*iKGKqQ7Zr0W1UHZjH0PIrA.png" /><figcaption>Fig4. Partial derivatives of a simple linear regression</figcaption></figure><p>For the multiple linear regression, the process is the same, but now we add an <em>X</em>0 = 1 to the equation so we could generalize the derivate of the cost function. So the multiple linear regression formula became:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ENx9UNeiOn0FmAGClstzjQ.png" /><figcaption>Fig5. Complete multiple linear regression formula</figcaption></figure><p>The derivative of this function is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*xtS30d80qVvpBMVcWc2_Kw.png" /><figcaption>Fig6. The partial derivative of linear multiple regression.</figcaption></figure><p>To update the weights, we just need to multiply the derivative by a learning rate and subtract from the previous weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*c86toKXYWqxlSH-CnckI6A.png" /><figcaption>Fig7. Formula to update the <em>ßs, where </em>α is the learning rate<em>.</em></figcaption></figure><p>It’s important that we simultaneously update all <em>ß</em>.</p><p>This is an iterative process, could we make it more efficient by using matrices?</p><h3>Vectorized Multiple Linear Regression</h3><p>In Python, we can use vectorization to implement the multiple linear regression and the gradient descent. We can transform the ys, ßs, and Xs into matrices like the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*tZlMxLQmvAhTvI30GN6Geg.png" /><figcaption>Fig8. Vectorized multiple linear regression</figcaption></figure><p>With that image we can have the predicted y using the formula below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*5XwFA-Zp3y2UTX82BIb7rQ.png" /><figcaption>Fig9. Vectorized formula to get the predicted values</figcaption></figure><p>The derivative with the formula below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*PfLVgmkGRLNzcRrxITNCTQ.png" /><figcaption>Fig10. Vectorized partial derivative.</figcaption></figure><p>Finally, to get the updated weights we have the equation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*5Tzg1bL0E9V1c5c4aX6WLA.png" /><figcaption>Fig11. Vectorized formula to update the weights</figcaption></figure><h3>Let’s write the code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTZYZGosMoE_oziuIKLv9g.png" /><figcaption>Fig12. Multiple linear regression function declaration</figcaption></figure><p>The first piece of advice for the people that are learning Data Science but do not have a software engineering background. Always document your code.</p><p>So we start with a function called fit_linear_regression that will receive the Xs, Ys, learning rate and, epsilon. Epsilon works as a threshold, we will stop when the error is less than epsilon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjzkdQcNTTJsOp0iNW9HPA.png" /><figcaption>Fig13. Multiple Linear Regression in Python</figcaption></figure><ul><li>In Step 1 we insert a column containing 1 to be the y-intercept into the x NumPy array.</li><li>In Step 2 we initialize the ßs, here I am calling weights. The weights will be a NumPy array containing the number of variables in X.</li><li>In Step 3 we will update the weights until the norma of the partial derivative is less than the epsilon.</li><li>In Step 3.1 we get the predicted values like in figure 9 and the partial derivative like in figure 10.</li><li>In Step 3.2 we get the norma.</li><li>In step 3.3 we update the weights like in figure 11.</li><li>The if in lines 41 and 42 is to warn us when we put a high learning rate and the functions diverged.</li><li>The return of the function is the adjusted weights.</li></ul><p>Now that we have the correct weights, how do we predict values?</p><h3>Making predictions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*LV7aEr5WaaHCR-7-dlOZcQ.png" /><figcaption>Fig14. Function to make predictions</figcaption></figure><p>To make predictions we just need to take the dot product between the weights array excluding the last value that is the y-intercept and the transposed Xs values after that get this result and sum it with the y-intercept.</p><p>Now we implemented our multiple linear regression from scratch, but how its compare with the sklearn?</p><h3>Comparing with sklearn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*ec0th7ZUB3rV2WOYXGiaTQ.png" /><figcaption>Fig 15. MSE from sklearn function and from our function</figcaption></figure><p>The first is the <a href="https://en.wikipedia.org/wiki/Mean_squared_error">Mean Squared Error</a> from the sklearn model and the second is the MSE from our function.</p><p>As we could see, they are similar. Our function MSE is just 0.004 greater than the sklearn.</p><h3>Conclusions</h3><p>In this post, you have learned</p><ol><li>What is multiple linear regression.</li><li>How we can fit a multiple linear regression model.</li><li>A vectorized multiple linear regression formula.</li><li>How to implement your own multiple linear regression using only Python and NumPy.</li></ol><p>You can see the code used to write this post in this <a href="https://colab.research.google.com/drive/1uO-f2GLgBqSXiBmI46MaHHDJccJMdy11?usp=sharing">Colab</a> notebook.</p><p>If you like what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db9368859f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/multiple-linear-regression-from-scratch-using-python-db9368859f">Multiple Linear Regression from Scratch using Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[There isn’t such thing as a problem without a solution. How to deal with problems in life.]]></title>
            <link>https://jair-neto.medium.com/there-isnt-such-thing-as-a-problem-without-a-solution-how-to-deal-with-problems-in-life-53c9b264d42e?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/53c9b264d42e</guid>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[jewish]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 10:25:00 GMT</pubDate>
            <atom:updated>2021-08-18T10:25:00.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vFHu9F2z35Wr1nQV" /><figcaption>Photo by <a href="https://unsplash.com/@simmerdownjpg?utm_source=medium&amp;utm_medium=referral">Jackson Simmer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, I will do a summary of the book “Yiddishe Kop: Creative Problem-Solving in Jewish Learning, Lore and Humor” from Rabbi Nilton Bonder, writing about the most important chapters of the book.</p><p>In his book, Bonder shows the mindset of a people that in history has gone through several tribulations, but in all of them managed to win, come out stronger, and thrives. He shows a lot of examples throughout the book to exemplify the Jewish concepts, making it easier for the reader to assimilate his ideas.</p><p>This Jewish mindset is called Yiddishe Kop, which has the aim of creating on us the voluntary process of questioning the impossible. <a href="http://www.jinfo.org/Nobel_Prizes.html">Just as curiosity the Jews won 22% of all Nobel prizes</a> even though <a href="https://en.wikipedia.org/wiki/Jewish_population_by_country">only 0.2% of the world population are Jewish.</a></p><h3>Never giving up</h3><p>To every single potential impossible problem that you have in your life, you must not give up. Because the impossibility is only a momentary condition, and no other gesture is more instigator of creativity and intuition as “not giving up”. The simple fact of remaining playing the game opens your eyes to multiples paths that would not exist if you threw in the towel.</p><p>To exemplify Bonder writes an interesting history about a guy that was wrongfully accused and became desperate because he knew that the king would kill him. So, he asked to talk to a rabbi that tells him “Never believe that there is no solution. Do not give up and an unbelievable path will be shown to you”.</p><p>So, on the trial day, the King to pretend that the accused had a chance told him that would write in one paper the word innocent and in the another, the word guilty. Theoretically, the accused now had a 50–50 chance to be free, but he <em>broke out in a cold sweat</em> because he knew that the king was playing with him and that he wrote guilt on both pieces of paper.</p><p>But in that time, he remembered the rabbi’s words, started to meditate, after some time his eyes glowed, and to the surprise of everyone in the trial, he ate one of the papers.</p><p>So, amazed with the situation the king asked him: “What have you done? How we will know what your charge is” and he told: “It’s easy, look at the remaining piece of paper the opposite of it was what I choose”.</p><p>The process used by the accused is also known as recontextualization. When we are facing a problem that seems to have no way out, we must try to see this problem from other perspectives.</p><h3>The apparent realm of what is apparent</h3><p>The reality is like an onion, full of layers and to have a full understanding of all the real-world aspects we must undo those layers one by one. By doing that we will have a broader perception of reality.</p><p>The apparent realm of what is apparent is what it’s in plain sight. It’s like the most external layer of the onion. It’s the layer easier to perceive with our 5 senses. But we need to be careful, because our 5 senses are at the same time a resource and a limitation, and we must recognize this to not make mistakes. Life demands of us an improvement of our perception of things, always increasing our readings and going beyond the literal world capturing what is beneath the surface.</p><p>Social networks are an example of the most external layer of an onion. In social networks, people only share the best moments of their lives and because a lot of people don’t understand the concept of the onion, they can’t see that what it’s in social networks it’s not the complete reality but just a layer. Because they don’t realize it, many compare their whole life with people’s lives on social networks and end up getting depressed because of it.</p><h3>What is an answer?</h3><p>One of the characteristics of the Jews stereotype is to answer a question with another question. They do that because a simple answer can lead the questioner to a path of darkness and make him see only the apparent realm of what is apparent. When you make more and more questions, each question deepens your knowledge and makes you improve your understanding.</p><p>This topic of the book reminders me of the Five whys technique. In this technique, we want to find the real root cause of a problem by repeating the question “Why” to each answer given. This improves your chance to eliminate once and for all the problem and not stay beating your head against the wall.</p><p>Example of 5 whys taken by the <a href="https://thebusinessanalystjobdescription.com/5-whys-technique-basics-examples-and-tips/">business analyst website</a>:</p><p><strong>Example 1:</strong> Let’s take an example from the manufacturing domain.</p><p><strong>Problem statement:</strong> The conveyor belt on the main production line has stopped</p><p>1. Why has the conveyor belt stopped?<strong><br></strong><em>The main pulley responsible for rotating the belt is not functioning</em></p><p>2. Why is the main pulley not rotating?<strong><br></strong><em>Because it’s not getting enough power from the motor</em></p><p>3. Why is it not getting enough power from the motor?<strong><br></strong><em>Because the motor has stopped working</em></p><p>4. Why has the motor stopped working?<strong><br></strong><em>The windings of the motor had burned out</em></p><p>5. Why have the windings burned out?<strong><br></strong><em>The motor was loaded beyond its power capacity</em></p><p>6. Why was the motor overloaded?<strong><br></strong><em>Although there were specifications about the permitted load frequency every hour, there were no instructions about the maximum load weight.</em></p><p><strong>Root Cause:</strong> So, you see, we needed 6 Whys to finally decipher that the weight of the load on the motor was more than its capacity and now we either need to replace the motor with a more powerful one or restrict the maximum load weight permitted on the conveyor belt at a time.</p><h3>The proud wise</h3><p>A lot of the wise people fails in two aspects</p><p>1- They try to find the most complex answers to questions made to them.</p><p>2- Think that they already know everything.</p><p>According to Ockham’s razor principle which says that all things being equal the simplest solution tends to be the best one the proud wise always will give the wrong answer because he will give the most complicated one.</p><p>When someone thinks that he is already wise and does not need to learn anything, that is the moment that he will start to fail. We need to learn how to be ignorant, always thirsty for knowledge.</p><h3>The hidden realm of what is apparent</h3><h4>Reframing</h4><p>This is an interesting method. In this method every time a situation occurs, we want to ask ourselves “To what this looks like?” so we can divide the text from the context, seeing the situation with others’ eyes. Example:</p><p>In cases of loss, it’s usual in Jewish tradition to use the reframing method. When small problems happen like when a glass or a plate broke, the Jews immediately say “mazal tov” — “good luck has occurred”. This reframing is to express the joy that it was just something insignificant that broke. Now you know you’ve been distracted and can make sure that a major accident doesn’t happen.</p><p>This technique helps us to avoid a big problem before it happens, changing our mindset whenever a minor problem happens.</p><h3>Think in the long term</h3><p>A trapezist when is walking on the tightrope keeps his eyes on the final line, he does not look to the rope or to the ground to maintain his balance. Because if he does that, he lost his balance.</p><p>In life it is the same thing, we must look to the long-term objectives to maintain us focused, avoiding giving great importance to those short-term goals that have not been accomplished. It’s like the Bill Gates quote “<strong>We</strong> always <strong>overestimate</strong> the change that <strong>will occur</strong> in the next two <strong>years </strong>and underestimate the change that <strong>will occur</strong> in the next <strong>ten</strong>”.</p><p>Keeping the focus on the long-term, help us ignore the small failures along the way improving our chances of accomplishing what really matters.</p><h3>“When you have a lot to do, go to sleep”</h3><p>This is a famous Yiddish saying. Sometimes when we have a lot to do, or the tasks are too tough the best movement is to stop what we are doing and sleep. Cleaning our mind, alleviating our anxieties, and making us see the problems with different eyes.</p><p>There are some famous examples of inventions that occurred when the inventors were doing nothing like Archimedes that was in the bath when he theorizes the law of hydrostatics and Newton that was sitting under an apple tree when he theorizes about the law of gravity. Some research confirms that idle moments are beneficial.</p><p><a href="https://bootcamp.uxdesign.cc/have-more-eureka-moments-the-power-of-doing-nothing-e77a31bf9032">“It’s really important. There is research showing that mind wandering, away from the current task and then returning to the task, those people have more creative ideas when they come back.” Scott Barry Kaufman, PhD</a></p><h3>The fear of making a mistake</h3><p>Mistakes are a fundamental part of the knowledge process. Those who suffer from a lack of mistakes cannot benefit from the knowledge and insight that come from them.</p><h3>Conclusion</h3><p>We learned from the book Yiddishe Kop: Creative Problem-Solving in Jewish Learning, Lore and Humor that to all problems there is a solution, we just need to undo the layers and meditate. That we must always be humble to learn and never accept the first answer is given to a question and that we must focus on the long-term not being afraid of making mistakes.</p><p>This book opened my eyes and showed to me some ways to solve a problem that will help me a lot in all aspects of my life. I recommend this book to everyone, there are some parts of the book that reminds me of hermeticism and are not so good. But you can take a lot of lessons from Yiddishe Kop: Creative Problem-Solving in Jewish Learning, so you should read it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53c9b264d42e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Para todos os problemas sempre há uma solução, como lidar com problemas do cotidiano.]]></title>
            <link>https://jair-neto.medium.com/para-todos-os-problemas-sempre-h%C3%A1-uma-solu%C3%A7%C3%A3o-como-lidar-com-problemas-do-cotidiano-4f5db0eda45c?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5db0eda45c</guid>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[resolução-de-problemas]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 10:15:17 GMT</pubDate>
            <atom:updated>2021-08-18T10:15:17.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y9YAujlyCtXb1P9l" /><figcaption>Photo by <a href="https://unsplash.com/@simmerdownjpg?utm_source=medium&amp;utm_medium=referral">Jackson Simmer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Este artigo apresentará uma resenha sobre o livro “O segredo judaico de resolução de problemas: Iídiche kop” do rabino Nilton Bonder. Descrevendo os principais ensinamentos do livro.</p><p>Em seu livro, Bonder mostra o mindset de um povo que na história já passou por várias tribulações, mas em todas elas, conseguiram vencer. Saindo dessas tribulações mais fortes e prósperos. Esse mindset judaico que tem como objetivo criar em nós o processo voluntário de questionar o impossível é chamado de Yiddishe Kop.</p><p>A título de curiosidade, os judeus ganharam 22% de todos os prêmios Nobel, embora apenas 0,2% da população mundial seja judia. Ele mostra muitos exemplos ao longo do livro para exemplificar os conceitos judaicos, tornando mais fácil para o leitor assimilar suas ideias.</p><h3>Nunca desista!</h3><p>Para cada problema potencialmente impossível que você tenha em sua vida, você não deve desistir. Porque a impossibilidade é apenas uma condição momentânea e nenhum outro gesto é mais instigador da criatividade e da intuição do que nunca desistir. O simples fato de permanecer jogando abre seus olhos para múltiplos caminhos que não existiriam se você jogasse a toalha.</p><p>Para exemplificar este conceito, Bonder descreve uma história interessante sobre um homem que foi acusado injustamente por um rei. Ficando desesperado, pois sabia que o rei o mataria. Então, este homem pediu para falar com um rabino que lhe disse: “Nunca acredite que não há solução. Não desista, e lhe será mostrado um caminho inimaginável.”</p><p>Assim, no dia do julgamento, o rei fingindo que o acusado tinha alguma chance lhe falou que escreveria em um papel a palavra inocente e no outro a palavra culpado. Teoricamente, o acusado agora tinha 50% de chance de ser livre, mas começou a suar frio porque sabia que o rei estava brincando com ele e que tinha escrito culpado nos dois pedaços de papel.</p><p>Porém, nessa hora ele se lembrou das palavras do rabino e começou a meditar. Depois de algum tempo seus olhos brilharam e para surpresa de todos no julgamento, ele comeu um dos papéis. Então, surpreso com a situação, o rei perguntou-lhe: “O que você fez? Como saberemos qual é a sua sentença?” e ele o respondeu: “Muito fácil, só olhar para o pedaço de papel que sobrou, o oposto a ele será a minha sentença”.</p><p>O processo usado pelo acusado também é conhecido como recontextualização. Quando estamos diante de um problema que parece não ter saída, devemos tentar ver essa dificuldade através de outras perspectivas.</p><h3>O aparente do aparente</h3><p>A realidade é como uma cebola, cheia de camadas e para ter um entendimento completo de todos os aspectos do mundo, devemos desfazer essas camadas uma por uma. Fazendo isso, teremos uma percepção mais ampla da realidade.</p><p>O aparente do aparente é o que está à vista de todos. É como a camada mais externa da cebola, aquela mais fácil de perceber com os nossos 5 sentidos. Entretanto, precisamos ter cuidado, pois nossos 5 sentidos ao mesmo tempo que são um recurso também são uma limitação e devemos reconhecer isso para que não cometamos erros. A vida nos exige um aprimoramento de nossa percepção, sempre demandando que nós aumentemos nossas leituras para que possamos ir além do mundo literal, captando o que está abaixo da superfície.</p><p>As redes sociais são um exemplo da camada mais externa de uma cebola. Nelas as pessoas só compartilham os melhores momentos de suas vidas e, como muitas pessoas não entendem o conceito da cebola. Não conseguem enxergar que a realidade mostrada nas redes sociais não é a realidade completa, mas apenas uma camada dela. Por não perceberem isso, muitos comparam toda a sua vida com as vidas apresentadas nas redes sociais e acabam ficando deprimidas por causa disso.</p><h3>O que é uma resposta?</h3><p>Uma das características do estereótipo dos judeus é sempre tentar responder uma pergunta com outra pergunta. Eles fazem isso porque uma resposta simples pode levar o questionador a um caminho de escuridão, fazendo com que ele veja apenas o aparente do aparente. Quando você faz mais e mais perguntas, cada uma delas aprofunda o seu conhecimento e faz com que você melhore o seu entendimento.</p><p>Este tópico do livro pode ser facilmente relacionado a técnica dos cinco porquês. Nesta técnica, queremos encontrar a verdadeira causa raiz de um problema, repetindo a pergunta “Por que” para cada resposta dada. Isso aumenta nossas chances de eliminar o problema de uma vez por todas e não ficar apenas enxugando gelo, atuando em suas causas e não em seus efeitos colaterais.</p><p>Exemplo da técnica dos cinco porquês no domínio da manufatura.</p><p>Problema: A esteira transportadora da principal linha de produção parou.</p><p>1- Por que a esteira transportadora parou?</p><p>a. A polia principal responsável por girar a correia não está funcionando.</p><p>2- Por que a polia principal não está funcionando?</p><p>a. Porque não está recebendo energia suficiente do motor.</p><p>3- Por que não está recebendo energia suficiente do motor?</p><p>a. Porque o motor parou de funcionar.</p><p>4- Por que o motor parou de funcionar?</p><p>a. Os enrolamentos do motor queimaram.</p><p>5- Por que os enrolamentos do motor queimaram?</p><p>a. O motor estava sobrecarregado.</p><p>6- Por que o motor estava sobrecarregado?</p><p>a. Embora houvesse especificações sobre a máxima frequência de carga permitida a cada hora, não havia instruções sobre o peso máximo de carga permitido.</p><p>Causa raiz: então, podemos ver que 6 porquês foram necessários para finalmente decifrar que o peso de carga no motor era maior que a sua capacidade e agora precisamos substituir o motor por um mais potente ou restringir o peso máximo de carga. Sem este exercício, iríamos trocar a polia principal e continuaríamos com o problema raiz.</p><h3>O sábio orgulhoso</h3><p>Muitos sábios falham em dois aspectos:</p><ul><li>Eles tentam encontrar as respostas mais complexas às perguntas que lhe são feitas.</li><li>Acham que já sabem de tudo.</li></ul><p>De acordo com o princípio da navalha de Ockham, que afirma que entre duas teorias ou soluções que resolvem igualmente os mesmos fatos, deve-se optar pela mais simples. Logo, o sábio orgulhoso sempre dará a resposta errada porque ele dará a mais complicada.</p><p>Quando alguém pensa que já é sábio e não precisa aprender mais nada, esse é o momento em que começará a falhar. Precisamos aprender a ser ignorantes, sempre buscando novos conhecimentos.</p><h3>Oculto do aparente</h3><h4>Reframing/Recontextualizando</h4><p>Este é um método interessante. Neste método, sempre que ocorre uma situação, devemos nos perguntar “Com que isso se parece?” para que possamos separar o texto do contexto, enxergando a situação com outros olhos. Exemplo: em casos de perda, é comum na tradição judaica usar o método de ressignificação. Quando pequenos problemas acontecem, como quando um copo ou prato quebram, os judeus imediatamente dizem “mazal tov” — “que sorte!”. Essa ressignificação é para expressar a alegria de que foi apenas algo insignificante que quebrou. Agora você sabe que estava distraído e pode garantir que um acidente maior não aconteça. Essa técnica nos ajuda a evitar um problema maior antes que ele aconteça, mudando nossa mentalidade sempre que um problema menor acontece.</p><h3>Foque no longo prazo</h3><p>O trapezista ao caminhar na corda bamba para se equilibrar, mantém os olhos na linha de chegada e não na corda ou no chão. Porque, ele perderá o equilíbrio se olhar para corda ou para o chão.</p><p>Na vida é do mesmo jeito, devemos olhar para os objetivos de longo prazo para nos mantermos focados, evitando dar grande importância àqueles objetivos de curto prazo que não foram alcançados. É como diz Bill Gates: “Nós sempre superestimamos a mudança que ocorrerá nos próximos dois anos e subestimamos a mudança que ocorrerá nos próximos dez”.</p><p>Ao mantermos o nosso foco no longo prazo, ignoramos as pequenas falhas que iremos ter ao longo do caminho, melhorando nossas chances de realizar aqueles objetivos que realmente importam.</p><h3>“Quando você tiver muito o que fazer, vá dormir”</h3><p>Este é um famoso ditado iídiche. Às vezes, quando temos muitas atividades para fazer ou as tarefas são muito difíceis, o melhor movimento é parar o que estamos fazendo e dormir ou descansar. Limpando nossa mente, aliviando nossas ansiedades e fazendo-nos ver os problemas com outros olhos.</p><p>Existem alguns exemplos famosos de invenções que ocorreram quando os inventores estavam no ócio como Arquimedes que estava no banho quando teorizou a lei da hidrostática e Newton que estava sentado sob uma macieira quando teorizou sobre a lei da gravidade. Algumas pesquisas confirmam que os momentos de inatividade são benéficos.</p><p>“É muito importante. Há pesquisas que mostram que quando deixamos a mente vagar e então retornamos as nossas tarefas, tendemos a ter ideias mais criativas” Scott Barry Kaufman, PhD</p><h3>O medo de cometer um erro</h3><p>Os erros são uma parte fundamental do processo de conhecimento. Aqueles que sofrem com a falta de erros não podem se beneficiar do conhecimento e da percepção que vêm deles.</p><h3>Conclusão</h3><p>Em resumo, os principais ensinamentos do livro “O segredo judaico de resolução de problemas: Iídiche kop” são:</p><ul><li>Para todos os problemas sempre existe uma solução, precisamos apenas destrinchar suas camadas e meditar.</li><li>Que devemos ser humildes, nunca deixando de aprender.</li><li>Que não devemos aceitar a primeira resposta para uma pergunta.</li><li>Devemos focar no longo prazo, sem medo de cometer erros.</li></ul><p>Este livro ajuda a abrir os olhos e nos mostra algumas maneiras de resolver problemas que podem ajudar muito em vários aspectos das nossas vidas. Portanto, recomendo a leitura deste livro, pois há muitos outros ensinamentos que podemos tirar dele.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5db0eda45c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop just using Machine Learning and learn how to build it. Linear Regression and Gradient Descent]]></title>
            <link>https://medium.com/analytics-vidhya/stop-just-using-machine-learning-and-learn-how-to-build-it-linear-regression-and-gradient-descent-3653de24c6d5?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/3653de24c6d5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 06:44:15 GMT</pubDate>
            <atom:updated>2025-06-02T09:37:22.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tfz0XR4WEbsT3nTDGLJKjg.jpeg" /><figcaption>Paramount Pictures</figcaption></figure><p>Today is really easy for us to train and use machine learning model. A lot of libraries in many programming languages implement machine learning models for us and we have to just call a function and voila we are using complex machine learning models.</p><p>But do we know how those models work? What are their goals? And if the library implementation of a specific model does not fit our needs do we know how to modify it?</p><p>Thinking about those questions, that the motivation to write those series of posts came to me.</p><p>In this post you will learn:</p><ol><li><strong>What is linear regression?</strong></li><li><strong>What is gradient descent?</strong></li><li><strong>How to implement a linear regression from scratch only using NumPy.</strong></li></ol><h3>Introduction</h3><p>From the simplest machine learning models like one variable linear regression to complex deep neural networks all machine learning models have the same goal, which is to find an equation that can answer a specific problem.</p><p>So, to start this series of posts, I will begin showing you how you can build your linear regression model from scratch using only Python Numpy.</p><h3>Linear regression</h3><p>In linear regression, we want to predict a continuous value using as input some ‘Xs’ values.</p><p>The simple linear regression formula is</p><p>Y = aX + b</p><p>‘Y’ is the dependent variable, ‘X’ is the explanatory variable, ‘a’ is the slope of the line, and ‘b’ is the intercept variable in other words the value of ‘Y’ when ‘X’ is zero. On a linear regression, we want to find the values of ‘a’ and ‘b’ that minimizes the prediction errors.</p><h3>How do I know that I can use linear regression?</h3><p>One of the easiest ways to see if a linear regression would be a good model to use is to build a scatterplot of the data. A scatterplot is a simple graph that uses cartesian coordinates to draws (X, Y) points.</p><p>If the plot shows a linear association between the dependent and explanatory variable like the image below you can try to fit a linear model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*-gQKfuDQcedyZ_QyQ6-b9g.png" /><figcaption>Scatterplot example of points that we can use linear regression, we can see a linear regression pattern with some outliers points.</figcaption></figure><p>In this image we can see a positive linear association between the dependent and explanatory variables, that is not the case of the image below. We cannot draw a simple line that would be a good fit for this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*s-o-1R0UxTagqeQfir02qQ.png" /><figcaption>Scatterplot example of points that linear regression is not the best model to use.</figcaption></figure><p>But how do we know our linear regression is getting it right? For knowing that we need to calculate the <strong>cost function</strong>.</p><h3>Cost function</h3><p>Intuitively to find the errors of a linear regression function we just need to get the sum of all differences between the predicted y value (ÿ) and the actual point (y), after that we can divide this value with the number of points (n) to get the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*X3Ng6QnbHgXK2IuP41nvlQ.png" /></figure><p>But if our ‘ÿ’ value it’s smaller than the ‘y’ value the error will decrease and it’s not that behavior that we want. So, to avoid this behavior we can get the absolute value of the equation or squared the equation.</p><p>Because we are going to take the derivative of this function, later on, and the derivate of a squared function is easier to solve, we will square the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*mBvRSPvvahh99LPgP7MNUA.png" /></figure><p>This formula is called Mean Square Error (MSE).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*S6Kizsiwku9QMH90eh9iTg.png" /><figcaption>Plot showing a linear regression model in blue, the ground truth points in purple, and the errors in red</figcaption></figure><p>But how can we improve our linear regression, reducing the value of the cost function? Using a technique called <strong>Gradient Descent</strong>.</p><h3>Gradient Descent</h3><p>Gradient Descent is a technique used to find a minimum of a function. In Linear Regression, we will use Gradient Descent to find the values of ‘a’ and ‘b’ that minimizes the cost function.</p><p>The Gradient Descent is described in the image below. We first start with random ‘a’ and ‘b’ values and the initial error is where the ball is drawn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*gCWwzetib5az8OxLTYTaZA.png" /><figcaption>Example of a Gradient Descent</figcaption></figure><p>After that, we want to make steps toward the bottom of this curve. But we don’t want to make big steps because by doing that we will take too long to achieve the bottom or even worse never achieve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*sSINprxpsNafZDrlKx5fMg.png" /><figcaption>What happens when the step is too big</figcaption></figure><p>Also, we do not want to make tiny steps that will take too long to achieve the bottom. So, we need a step of just the right size. This step size is tunned by a factor called learning rate (L). Usually, L is some small value like 0.0001.</p><p>To optimize the cost function we need to get its derivative by doing the steps below.</p><p>1- Replace ÿ for ax + b</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*k5FcbhvNgf0PFew9L_2BEQ.png" /></figure><p>2- Calculate the partial derivative with respect to ‘a’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*iuVrNUMFX-dHIHB5IPz9cA.png" /></figure><p>3- Calculate the partial derivative with respect to ‘b’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*LqC_luTnotA8UctudNfWFw.png" /></figure><p>4- Update the value of ‘a’ and ‘b’ in each iteration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*yHZDC43itht9SHvIwPQkbw.png" /></figure><p>5- Finally, repeat this process m times or until the error is less than some tolerance.</p><h3>Implementing in Python</h3><p>Importing the libraries needed.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from warnings import warn</pre><p>Function to implement the linear regression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zy_bGCHb7KdP3wqzlFh-Qw.png" /><figcaption>Implementation of the linear regression</figcaption></figure><p>To implement the linear regression, we</p><ol><li>Start by setting the ‘a’ and ‘b’ to zero and getting the number of points ‘n’.</li><li>Get the predictions</li><li>Get the derivatives with respect to ‘a’ and ‘b’</li><li>Update the ‘a’ and ‘b’ coefficients</li><li>Get the error</li><li>Repeat this process until i is less than epoch or the error is less than the tolerance</li><li>Return the updated ‘a’ and ‘b’</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*10j8IqrR18H_iY7-398_8A.png" /><figcaption>Code to check if the gradient descent diverged</figcaption></figure><p>This snippet of code checks if the gradient descent diverged.</p><p>To test if this code was working as expected, I used the <a href="https://www.kaggle.com/smid80/weatherww2/data">Weather Conditions in World War Two Kaggle dataset</a> to see if I could fit a linear regression to explain the relationship between the MinTemp and the MaxTemp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*3VUK7aKsFE-XXyClg2rL9A.png" /><figcaption>MinTemp VS MaxTemp plot with the points in blue and the result of linear regression in red</figcaption></figure><p>You can check the code used to write this post in this <a href="https://colab.research.google.com/drive/15SoZ2cqa3LwHn_qjEXDx17v_kC2oLuA1?usp=sharing">Colab notebook</a>. Feel free to reach me with any comments on my <a href="https://www.linkedin.com/in/jair-guedes-ferreira-neto/">Linkedin</a> account and thank you for reading this post.</p><p>If you like what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts.</p><h3>References</h3><p><a href="https://towardsdatascience.com/linear-regression-using-gradient-descent-97a6c8700931">https://towardsdatascience.com/linear-regression-using-gradient-descent-97a6c8700931</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3653de24c6d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/stop-just-using-machine-learning-and-learn-how-to-build-it-linear-regression-and-gradient-descent-3653de24c6d5">Stop just using Machine Learning and learn how to build it. Linear Regression and Gradient Descent</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best NLP Algorithms to get Document Similarity]]></title>
            <link>https://medium.com/analytics-vidhya/best-nlp-algorithms-to-get-document-similarity-a5559244b23b?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5559244b23b</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Thu, 27 May 2021 16:41:25 GMT</pubDate>
            <atom:updated>2021-05-27T16:41:25.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TZ9VDQI0vwcYO-41" /><figcaption>Photo by <a href="https://unsplash.com/@jaredd_craig?utm_source=medium&amp;utm_medium=referral">Jaredd Craig</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever read a book and found that this book was similar to another book that you had read before? I have already. Practically all self-help books that I read are similar to Napolean Hill’s books.</p><p>So I wondered if Natural Language Processing (<a href="https://machinelearningmastery.com/natural-language-processing/">NLP</a>) could mimic this human ability and find the similarity between documents.</p><h3>Similarity Problem</h3><p>To find the similarity between texts you first need to define two aspects:</p><ol><li>The similarity method that will be used to calculate the similarities between the embeddings.</li><li>The algorithm that will be used to transform the text into an embedding, which is a form to represent the text in a vector space.</li></ol><h3>Similarity Methods</h3><h4>Cosine Similarity</h4><p><strong>Cosine Similarity</strong> measures the cosine of the angle between two embeddings. When the embeddings are pointing in the same direction the angle between them is zero so their cosine similarity is 1 when the embeddings are orthogonal the angle between them is 90 degrees and the cosine similarity is 0 finally when the angle between them is 180 degrees the the cosine similarity is -1.</p><p>-1 to 1 is the range of values that the cosine similarity can vary, where the closer to 1 more similar the embeddings are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9LdEn9NyZ7bbABUJtZvFw.png" /><figcaption>Image from <a href="https://datascience-enthusiast.com/DL/Operations_on_word_vectors.html">https://datascience-enthusiast.com/DL/Operations_on_word_vectors.html</a> showing a situation where the cosine similarity is 1 because France and Italy are related and other where the similarity is 0 because ball is not similar to crocodile</figcaption></figure><p>Mathematically, you can calculate the cosine similarity by taking the dot product between the embeddings and dividing it by the multiplication of the embeddings norms, as you can see in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JJXxsZ1SdnaLZPXvVyxDbQ.png" /><figcaption>Cosine Similarity formula</figcaption></figure><p>In python, you can use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html">cosine_similarity</a> function from the sklearn package to calculate the similarity for you.</p><h3>Euclidean Distance</h3><p><strong>Euclidean Distance</strong> is probably one of the most known formulas for computing the distance between two points applying the Pythagorean theorem. To get it you just need to subtract the points from the vectors, raise them to squares, add them up and take the square root of them. Did it seem complex? Don’t worry, in the image below it will be easier to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*F507EfvD_1GAA42iLcCANw.png" /><figcaption>Euclidean Distance formula</figcaption></figure><p>In python, you can use the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.euclidean_distances.html">euclidean_distances</a> function also from the sklearn package to calculate it.</p><p>There are also other metrics such as <em>Jaccard, Manhattan, and </em>Minkowski <em>distance that you can use, but won’t be discussed in this post.</em></p><h3>Preprocessing</h3><p>In <strong>NLP</strong> problems it is usual to make the text pass first into a preprocessing pipeline. So to all techniques used to transform the text into embeddings, the texts were first preprocessed using the following steps:</p><ol><li>Normalization: transforming the text into lower case and removing all the special characters and punctuations.</li><li>Tokenization: getting the normalized text and splitting it into a list of tokens.</li><li>Removing stop words: stop words are the words that are most commonly used in a language and do not add much meaning to the text. Some examples are the words ‘the’, ‘a’, ‘will’,…</li><li>Stemming: it is the process to get the root of the words and sometimes this root is not equal to the morphological root of the word, but the stemming goal is to make that related word maps to the same stem. Examples: branched and branching become branch.</li><li>Lemmatization: This is the process of getting the same word for a group of inflected word forms, the simplest way to do this is with a dictionary. Examples: is, was, were become be.</li></ol><p>The output of this pipeline is a list with the formatted tokens.</p><h3>Algorithms to transform the text into embeddings</h3><h4>Term Frequency-Inverse Document Frequency (TF-IDF)</h4><p>Before talking about TF-IDF I am going to talk about the simplest form of transforming the words into embeddings, the <strong>Document-term matrix</strong>. In this technique you only need to build a matrix where each row is a phrase, each column is a token and the value of the cell is the number of times that a word appeared in the phrase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*vOFvnrPM3fSG9-1mTeEDqQ.jpeg" /><figcaption><strong>Document-term matrix example</strong></figcaption></figure><p>After that to get the similarity between two phrases you only need to choose the similarity method and apply it to the phrases rows. The major problem of this method is that all words are treated as having the same importance in the phrase.</p><p>To address this problem <strong>TF-IDF</strong> emerged as a numeric statistic that is intended to reflect how important a word is to a document.</p><p><strong>TF-IDF</strong> gets this importance score by getting the term’s frequency (TF) and multiplying it by the term inverse document frequency (IDF). The higher the <strong>TF-IDF</strong> score the rarer the term in a document and the higher its importance.</p><h4>How to calculate TF-IDF?</h4><p>The term frequency it’s how many times a term appears in the document, for example: if the word ‘stock’ appears 20 times in a 2000 words document the TF of stock is 20/2000 = 0.01.</p><p>The IDF is logarithmic of the total number of documents divided by the total number of documents that contain the term, for example: if there are 50.000 documents and the word ‘stock’ appears in 500 documents so the IDF is the log(50000/500) = 4.6. So the TF-IDF of ‘stock’ is 4.6 * 0.01 = 0.046.</p><h3>Word2Vec</h3><p>In <strong>Word2Vec</strong> we use neural networks to get the embeddings representation of the words in our corpus (set of documents). The <strong>Word2Vec</strong> is likely to capture the contextual meaning of the words very well.</p><p>To get the word embeddings, you can use two methods: Continuous Bag of Words (CBOW) or Skip Gram. Both of these methods take as input the one-hot encoding representation of the words, to get this representation you just need to build a vector with the size of the number of unique words in your corpus, then each word will be represented as one in a specific position and zeros in all others positions of the vector.</p><p>For example, suppose our corpus has only 3 words airplane, bee, and cat. So we can represent them as:</p><ul><li>airplane: [1, 0, 0]</li><li>bee: [0, 1, 0]</li><li>cat: [0, 0, 1]</li></ul><p>In <strong>Word2Vec</strong> we are not interested in the output of the model, but we are interested in the weights of the hidden layer. Those weights will be the embeddings of the words.</p><h4>CBOW</h4><p>The CBOW model goal is to receive a set of one hot encoding word, predict a word learning the context. So let’s assume that we have the phrase ‘In the morning I drink coffee’, the input and outputs of the CBOW model would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*g9BcJAzjBKbDBIrLkbh3bA.png" /><figcaption>Example of CBOW input and expected output</figcaption></figure><p>So it’s a supervised learning model and the neural network learns the weights of the hidden layer using a process called backpropagation.</p><h4>Skip-Gram</h4><p>Skip-Gram is like the opposite of CBOW, here a target word is passed as input and the model tries to predict the neighboring words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*0rcIYtvk8873umH79ybzbA.png" /><figcaption>Example of Skip-Gram input and expected output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*bPoBFhWO7qKvlYZWdGByQQ.png" /><figcaption>CBOW Architecture in the left and Skip-Gram Architecture in the right</figcaption></figure><h3>Doc2Vect</h3><p>In <strong>Word2Vec</strong> we get one embedding for each one of the words. <strong>Word2Vect</strong> is useful to do a comparison between words, but what if you want to compare documents?</p><p>You could do some vector average of the words in a document to get a vector representation of the document using Word2Vec or you could use a technique built for documents like <strong>Doc2Vect</strong>.</p><p>The <strong>Doc2Vect</strong> in <a href="https://pypi.org/project/gensim/">Gensim</a> is an implementation of the article <strong>Distributed Representations of Sentences and Documents</strong> by Le and Mikolov. In this <a href="https://arxiv.org/pdf/1405.4053.pdf">article</a>, the authors presented two algorithms to get the embeddings for the documents. The <strong>Distributed Memory Model of Paragraph Vectors</strong> (PV-DM) and the <strong>Distributed Bag of Words version of Paragraph Vector</strong> (PV-DBOW)</p><h4>Distributed Memory Model of Paragraph Vectors (PV-DM)</h4><p>This model looks like the <strong>CBOW</strong>, but now the author created a new input to the model called paragraph id.</p><blockquote>“The paragraph token can be thought of as another word. It acts as a memory that remembers what is missing from the current context — or the topic of the paragraph.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lijgWiYs5yO44uVs" /><figcaption>PV-DM Architecture</figcaption></figure><h4>Distributed Bag of Words version of Paragraph Vector (PV-DBOW)</h4><p>The <strong>PV-DBOW</strong> method it is similar to the <strong>Skip-Gram</strong>, here the input is a paragraph id and the model tries to predict words randomly sampled from the document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*4m3H2LucrPQXXt5F" /><figcaption>PV-DBOW Architecture</figcaption></figure><p>To get a more robust document representation, the author combined the embeddings generated by the <strong>PV-DM</strong> with the embeddings generated by the <strong>PV-DBOW</strong>.</p><h3>Transformers</h3><p>The <strong>Transformers</strong> technique is revolutionizing the <strong>NLP</strong> problems and setting the state-of-art performance with the models <strong>BERT</strong> and <strong>RoBERTa</strong>. So in <a href="https://arxiv.org/pdf/1908.10084.pdf">Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks</a>, Reimers and Gurevych modified the model architecture of <strong>BERT</strong> and <strong>RoBERTa</strong> to make them output a fixed size sentence embedding.</p><p>To achieve that, they added a pooling operation to the output of the transformers, experimenting with some strategies such as computing the mean of all output vectors and computing a max-over-time of the output vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*PDkwmfuh03IeJAnwUa6e9Q.png" /><figcaption>Sentence Embedding BERT to get cosine similarity</figcaption></figure><p>To use a pre-trained transformer in python is easy, you just need to use the sentece_transformes package from <a href="https://www.sbert.net/">SBERT</a>. In SBERT is also available multiples architectures trained in different data.</p><h3>Comparing techniques</h3><p>The machine used was a MacBook Pro with a 2.6 GHz Dual-Core Intel Core i5 and an 8 GB 1600 MHz DDR3 memory. The data used were the texts from the letters written by Warren Buffet every year to the shareholders of Berkshire Hathaway the company that he is CEO.<br>The goal was to get the letters that were close to the 2008 letter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1DpjBmfSgUxQGNCbkTKhA.png" /><figcaption>Table with the Method, Similarity Metric, Target Year, Execution time in seconds, and the Most Similar Years ordered by the most similar to the least similar</figcaption></figure><p>TF-IDF was the slowest method taking 295 seconds to run since its computational complexity is O(nL log nL), where n is the number of sentences in the corpus and L is the average length of the sentences in a dataset.</p><p>One odd aspect was that all the techniques gave different results in the most similar years. Since the data is unlabelled we can not affirm what was the best method. In the next analysis, I will use a labeled dataset to get the answer so stay tuned.</p><h3>Finishing</h3><p>I implemented all the techniques above and you can find the code in this <a href="https://github.com/jairNeto/warren_buffet_letters">GitHub</a> repository. There you can choose the algorithm to transform the documents into embeddings and you can choose between cosine similarity and Euclidean distances.</p><p>The set of texts that I used was the letters that Warren Buffets writes annually to the shareholders from Berkshire Hathaway, the company that he is CEO.</p><p>In this article, we have explored the NLP document similarity task. Showing 4 algorithms to transform the text into embeddings: TF-IDF, Word2Vec, Doc2Vect, and Transformers and two methods to get the similarity: cosine similarity and Euclidean distance.</p><p>Feel free to reach me with any comments on my <a href="https://www.linkedin.com/in/jair-guedes-ferreira-neto/">Linkedin</a> account and thank you for reading this post.</p><p>If you <strong>like</strong> what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5559244b23b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/best-nlp-algorithms-to-get-document-similarity-a5559244b23b">Best NLP Algorithms to get Document Similarity</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using NLP to get inside Warren Buffet mind part 2]]></title>
            <link>https://medium.com/analytics-vidhya/using-nlp-to-get-inside-warren-buffet-mind-part-2-8e3557810a39?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e3557810a39</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[warren-buffett]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Tue, 04 May 2021 16:49:02 GMT</pubDate>
            <atom:updated>2021-05-04T16:49:02.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF225R8ZbA_bfP4nDo9ocw.png" /></figure><p>Frequency and Sentiment Analysis.</p><p>In part 1, I used transformers trained in the task of Questions and Answering to answer the question: “ Can a machine learning model answer questions about Finance and Economy?”. If you haven’t read this article yet, don’t waste any more time and <a href="https://medium.com/analytics-vidhya/using-nlp-to-get-inside-warren-buffet-mind-part-i-666d717d0c2e">click here</a> to read it.</p><p>In this article I will use NLP techniques to answer the questions:</p><p><strong>1. What are the most used terms of Buffet and if those terms changed along the time?</strong></p><p><strong>2. How was his feeling about the Economy and Stocks Market over the years?</strong></p><h3>What are the most used terms of Buffet and if those terms changed along the time?</h3><p>A curiosity that I had was if the speech of Buffet changed over time or always remained the same. So I analyzed how the words that he wrote in the shareholder letters changed over time.</p><p>First I combined the text from all the letters ranging from 1977 to 2020 and plotted a word cloud. Word cloud is a visual representation where the size of the words indicates their frequency in the text.</p><h4>Word Cloud</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vk0A83XSsssGA3SR" /><figcaption>Buffet letters word cloud</figcaption></figure><p>The words <strong>earning</strong> and <strong>stock</strong> have a highlight in the letters, as expected since their core business is to make money from stocks, but other interesting words that also have a great highlight are <strong>insurance</strong> and <strong>Geico</strong>. Showing how Buffet really likes the insurance sector and confirms this <a href="https://www.forbes.com/sites/randalllane/2017/09/20/warren-buffett-my-greatest-investing-advice-and-the-investments-everyone-should-make/?sh=11919b53593e">interview to Forbes when he said that Geico was the number 1 investment of his life</a>.</p><p>Other words that also caught my attention were <strong>CEO</strong>, showing that Warren invests not only in great companies but in great people and <strong>shareholder</strong>, showing that Buffet is always concerned with the well-being of its shareholders.</p><h4>Frequency Heatmap</h4><p>Based on the most used words in the letters, I plotted a heatmap to see if over the years there has been a change in Warren’s speech or if he has remained constant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*dvjzQqz_OVwRtU57" /><figcaption>Heatmap of Words Frequency, in the x-axis, are the letters years, in the y-axis are words, and the closer the cells to white color indicates a low frequency and the closer to green indicates a higher frequency.</figcaption></figure><p>We can notice that the words <strong>insurance</strong>, <strong>shareholder</strong>, <strong>gain</strong>, <strong>loss</strong>, and <strong>stock</strong> were very present in the letters throughout the years analyzed. The word <strong>CEO</strong> started to appear more constantly in the letters only from the mid-90s.</p><p>If we look at the row of the word <strong>loss</strong>, we see that in <strong>2001</strong> this word was used a lot. Probably, because of the attack on the World Trade Center that caused the insurance industry to suffer its worst loss in history so far.</p><p>Another point that stands out is the year <strong>1995</strong> of the <strong>stock</strong> row, where the creation of class B of Berkshire shares was discussed. Since this was an important decision in the company which was going to affect all the Berkshire investors he had to explain how this creation was going to work. That’s why there was greater use of the term <strong>stock </strong>in that year.</p><p>In the <strong>bond</strong> row, we see the highlights in the years <strong>1984 </strong>and<strong> 2008. </strong>In 1984 he wrote about his investment rationale to buy bonds. In 2008 he wrote about the tax-exempt bond insurance market.</p><p>But as we have not seen any strong pattern in the letters from this heatmap, I grouped the data into a 5 years period to analyze if any pattern emerges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*XzqjN5jGrg4yR6_5" /><figcaption>Heatmap of Words Frequency grouped by 5 years period</figcaption></figure><p>Even plotting the heatmap grouped, we could only see a trend at the <strong>CEO</strong> <strong>row</strong>, where the frequency increased over the years.</p><h4>But why Warren Buffet began to put the word CEO more frequently in the letters?</h4><p>Digging deeper at Buffet’s life, I found that he started his investment strategy by buying <strong>cigar butt </strong>companies.</p><blockquote><em>“If you buy a stock at a sufficiently low price, there will usually be some hiccup in the fortunes of the business that gives you a chance to unload at a decent profit, even though the long-term performance of the business may be terrible. I call this the “</em><strong><em>cigar butt</em></strong><em>” approach to investing. A cigar butt found on the street that has only one puff left in it may not offer much of a smoke, but the “bargain purchase” will make that puff all profit.</em>”</blockquote><p>The CEOs of cigar butt companies did not play a strong role in the investment, since Buffet’s intention to those kinds of companies was only to make a profit in the short term. But, his partner Charlie Munger convinced Buffet to change his investment strategy and focus on <a href="https://www.investopedia.com/terms/v/valueinvesting.asp">value investment</a> (a strategy that involves picking <a href="https://www.investopedia.com/terms/s/stock.asp">stocks</a> that appear to be trading for less than their <a href="https://www.investopedia.com/terms/i/intrinsicvalue.asp">intrinsic</a> or book value). For value investors, that focus on long-term performance, who are the CEOs of the company plays a big role in whether or not to invest in it.</p><p>This change in Warren investment mindset occurred in late the 80s, as he wrote in the 1989 letter:</p><blockquote><em>“But now, when buying companies or common stocks, we look for first-class businesses accompanied by first-class managements.”</em></blockquote><p>Thus, the likely reason for the increased use of the word CEO by Buffet was his investment strategy change from buying cigar butt companies to buying stocks.</p><p>After that, I tried to get Buffet’s thoughts about some topics that are hot nowadays, such as bitcoin, blockchain, crypto, forex, options, AI, ESG, Tesla, and FAANG. But those terms never appeared in his letters. Confirming his “circle of competence” concept. A circle of competence is when an investor sticks to areas they know about when deciding what companies to invest in.</p><p>As we can see, Buffet’s speeches don’t seem to change much over time, with some one-off events where he focuses on some specific area or important event for his shareholders. Changing only to talk more about CEOs when he changed his strategy from buying cigar butts to buying value companies.</p><h3>How was his feeling about the Economy and Stocks Market over the years?</h3><p>The last curiosity I had was if he shows his emotions in the letters or if he always leaves his emotions aside and has a more neutral tone.</p><p>To do this analysis, I took advantage of the power of the <strong>transformers</strong> again this time using the pre-trained ‘sentiment-analysis’ pipeline and also used the <a href="https://towardsdatascience.com/sentimental-analysis-using-vader-a3415fef7664">Sentiment Intensity Analyzer</a> using VADER (Valence Aware Dictionary for Sentiment Reasoning) technique to see if there was any difference between the two techniques.</p><h4><strong>What is Sentiment analysis?</strong></h4><p>Sentiment analysis or Opinion Mining is a sub-set of NLP that tries to extract whether a text is positive, negative, or neutral (some sentiment analysis only classify text as positive or negative).</p><h4>Sentiment analysis using Transformers</h4><p>To use a pre-trained transformer in the sentiment analysis task in Python is easy. With 3 lines of code, you can start to classify your sentences in negative and positive.</p><pre><strong>&gt;&gt;&gt; from</strong> <strong>transformers</strong> <strong>import</strong> pipeline<br><strong>&gt;&gt;&gt; </strong>classifier = pipeline(&#39;sentiment-analysis&#39;)<br><strong>&gt;&gt;&gt; </strong>classifier(&#39;We are very happy to show you the 🤗 Transformers library.&#39;)<br>[{&#39;label&#39;: &#39;POSITIVE&#39;, &#39;score&#39;: 0.9997795224189758}]</pre><p>The output of the sentiment analysis pipeline is a dictionary with a positive or a negative score that add up to 1.</p><p>Before I use the sentiment analysis pipeline I did some preprocess in the text to get better results. This process is summarised in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*7DZ8ZK4mEsZ3vwVu" /><figcaption>I used a sentence tokenized to split the text of the letters into sentences, then I did a cumulative sum of the sentiment analysis of each sentence, after that, I did a normalization of the results</figcaption></figure><p>Finally, I draw the results in a heatmap plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*UqTqhfsed9Uig-iw" /><figcaption>Heatmap from Sentiment Analysis using pre-trained Transformers</figcaption></figure><p>This heatmap surprised me, as the model rated most years as negative. The years <strong>2001</strong> and <strong>2008</strong> had a more negative feeling, probably due to the 9/11 in 2001 and the financial crisis in 2008.</p><p>Another interesting fact is that the rating of the 2020 letter was more positive than negative, despite the pandemic. After all, as we can see today Buffet’s felling was right because from the bottom in stock prices on March 20, 2020, until now the S&amp;P 500 has already risen more than 70%, so ‘<strong>Never bet against America</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fWbsjACC2sG5jpKmfvySA.png" /><figcaption>Warren Buffet in his 2020 annual meeting</figcaption></figure><h3>Ngrams Sentiment Analysis</h3><p>For realizing the Ngrams sentiment analysis, I used the <a href="https://www.nltk.org/">nltk</a> package to get the 20 most frequent unigram, bigram, trigram, and quadgram from the texts of all letters and used the transformer to classify the ngrams in positive and negative.</p><p>You can see the result in the chart below. The positives ngrams are on the left in blue and the negatives ones are on the right in red. It’s interesting to note that, excepting for the ngrams that contain the word loss, all other negative ngrams do not seem to be negative, like the unigrams <strong>geico</strong> and <strong>stock</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kjHwsYctLhU_7a3C" /><figcaption>Ngrams sentiment analysis bar charts, in the left there are the positive ngrams and in the right, there are the negative ngrams. To plot these bar charts I used a function implemented at this <a href="https://www.kaggle.com/jairneto/e-commerce-sentiment-analysis-eda-viz-nlp/edit">kaggle</a>.</figcaption></figure><h4>Sentiment analysis using Sentiment Intensity Analyzer VADER</h4><blockquote><em>VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media.</em></blockquote><p>The model using the Sentiment Intensity Analyzer (SIA) <strong>VADER </strong>technique classifies the texts into 3 categories, negative, positive, and neutral. The process to analyze the letters followed the same steps as the transformer, changing only the technique used to calculate the sentiment and the result is in the heatmap below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*OBD9BxWgAHZSJvww" /><figcaption>Heatmap from Sentiment Analysis using SIA</figcaption></figure><p>Using the SIA, we had the text for all years considered neutral differently from the transformers analysis. Potentially because the data used to train the model was from social media. Comparing social media text to Buffet’s informative tone in the letters is not a surprise that SIA using VADER classified all the letters text as being neutral.</p><p>Those conflicting results were insightful for my next sentiment analysis using pre-trained models. Because showed that the data used to train the model has an important role in its performance.</p><h3>Conclusion</h3><ol><li>In this post, we did not found any strong pattern changes over the years in the words used by Buffet to write his letters.</li><li>The letters had a sentiment negative or neutral and the two pre-trained models used had conflicting results, showing that we need to find a pre-trained model whose data used to train is similar to the data you want to classify.</li></ol><p>You can check the code used to write this post at my <a href="https://github.com/jairNeto/warren_buffet_letters">Github repository</a>. Feel free to reach me with any comments on my <a href="https://www.linkedin.com/in/jair-guedes-ferreira-neto/">Linkedin</a> account and thank you a million for reading this post.</p><p>If you like what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts.</p><h3>References</h3><ul><li><a href="https://www.berkshirehathaway.com/letters/letters.html">Shareholder Letters</a></li><li><a href="https://realpython.com/python-nltk-sentiment-analysis/#customizing-nltks-sentiment-analysis">Sentiment Analysis: First Steps With Python&#39;s NLTK Library - Real Python</a></li><li><a href="https://towardsdatascience.com/a-beginners-guide-to-sentiment-analysis-in-python-95e354ea84f6">A Beginner’s Guide to Sentiment Analysis with Python</a></li><li><a href="https://towardsdatascience.com/sentiment-analysis-in-10-minutes-with-bert-and-hugging-face-294e8a04b671">Sentiment Analysis in 10 Minutes with BERT and Hugging Face</a></li><li><a href="https://medium.com/@b.terryjack/nlp-pre-trained-sentiment-analysis-1eb52a9d742c">NLP: Pre-trained Sentiment Analysis</a></li><li><a href="https://www.kaggle.com/thiagopanini/e-commerce-sentiment-analysis-eda-viz-nlp?select=viz_utils.py">E-Commerce Sentiment Analysis: EDA + Viz + NLP ✍</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e3557810a39" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/using-nlp-to-get-inside-warren-buffet-mind-part-2-8e3557810a39">Using NLP to get inside Warren Buffet mind part 2</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using NLP to get inside Warren Buffet mind part I]]></title>
            <link>https://medium.com/analytics-vidhya/using-nlp-to-get-inside-warren-buffet-mind-part-i-666d717d0c2e?source=rss-c8821ffb2781------2</link>
            <guid isPermaLink="false">https://medium.com/p/666d717d0c2e</guid>
            <category><![CDATA[warren-buffett]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[question-answering]]></category>
            <dc:creator><![CDATA[Jair Neto]]></dc:creator>
            <pubDate>Tue, 27 Apr 2021 15:47:15 GMT</pubDate>
            <atom:updated>2021-04-27T21:50:01.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF225R8ZbA_bfP4nDo9ocw.png" /></figure><p><strong>Warren Buffet</strong> is an American investor, philanthropist, and the actual number 6 on the <a href="https://www.forbes.com/profile/warren-buffett/?sh=7cf5da146398">Forbes</a> billionaires list. He has an overall gain of <strong>2,810,526%</strong> from 1965 to 2020 while the <a href="https://www.investopedia.com/terms/s/sp500.asp">S&amp;P500</a> (index of the 500 largest U.S. publicly traded companies) rose 23,454%. He is considered the best investor of all time and an inspiration for a lot of people, I included.</p><h3>Introduction</h3><p>To combine my passion for <strong>technology</strong> and the <strong>financial market</strong>, I will write a series of posts to see if the use of Artificial Intelligence (AI) could help me understand the mind of Buffet by answering the 3 questions below.</p><ol><li>Can a machine learning model answer questions about Finance and Economy?</li></ol><p>2. What are the most used terms of Buffet and if those terms changed along the time?</p><p>3. How was his feeling about the Economy and Stocks Market over the years?</p><p>To answer those I will use Natural Language Processing (<a href="https://machinelearningmastery.com/natural-language-processing/">NLP</a>) techniques and the text from the <a href="https://www.berkshirehathaway.com/letters/letters.html">letters</a> that he writes every year to Berkshire Hathaway shareholders, the company that he is the CEO. In this post, I will answer the first question.</p><h3>Can a machine learning model answer questions about Finance and Economy?</h3><p>To respond to this question I will use the transformer architecture that is revolutionizing the AI landscape.</p><p>The paper “<a href="https://arxiv.org/pdf/1706.03762v5.pdf"><strong>Attention is all you need</strong></a>” from Google introduced the Transformer technique. They used an <strong>encoder</strong> to create an embedding for each word taking into account its importance in the sentence and a <strong>decoder </strong>to transform the embedding back to text.</p><h4>Transformer architecture</h4><p>The encoder and decoder architectures are composed of stacked modules with Multi-Head attention and Feed Forward layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hyQ5FSA0R6dtvVXu" /><figcaption>The Transformer — model architecture.</figcaption></figure><p>Differently from others NLP approaches the transformer does not use loopings but rather it uses stacked attention layers. In each attention layer, the model is looking at different parts of the sentence and trying to learn more about its words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IkiyTWp9QiZ3scy3" /><figcaption>Multi-Head Attention consists of several attention layers running in parallel.</figcaption></figure><p>Taking a closer look at the Attention mechanism, you can see that it is composed of two parts, the scaled dot-product Attention where a softmax is used to learn weights, and the Multi-head attention that calls the dot-product operation several times in parallel.</p><p>In the end, there is a Feed Forward layer that realizes a linear transformation of each element from the given sentence. Those attention layers try to look at different parts of the sentence to discover the semantic or syntactic information of the words.</p><p>If you want to know more about transformers you can check this<strong><em> </em></strong><a href="https://neptune.ai/blog/bert-and-the-transformer-architecture-reshaping-the-ai-landscape"><strong><em>post</em></strong></a> by Cathal Horan.</p><h4>Question Answering</h4><p>The QA (Question Answering) is when the model receives only a context and a question and it outputs an answer (where the answer lies within the context) and a confidence score. The QA is a task that uses the transformers architecture.</p><p>To use a pre-trained transform for the task of QA is easy like we can see in the example below from <a href="https://huggingface.co/transformers/task_summary.html#question-answering">huggingface</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7275566503cd1ed200c86af4e4098db/href">https://medium.com/media/a7275566503cd1ed200c86af4e4098db/href</a></iframe><p>So I used this trained model and the Buffet letter from 2008, just removing the special characters, as the context to see if the model could make correct predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*Sc_QMITWF2_grK5oefzOZw.jpeg" /><figcaption>Questions, answers, and snippets showing the correct answers</figcaption></figure><p>As you can see, the model was able to correctly understand all the questions and for all scenarios gave a satisfactory answer. For the first question the answer should be something like: “the credit crisis, coupled with tumbling home and stock prices”, but the model was partially correct, answering “the credit crisis”.</p><p>The second question that I made was to check if the model would give the correct answer even if I changed the word for a synonym, so I changed the word <strong>produced</strong> by the word <strong>generated</strong> and the answer was the same.</p><p>Then in the third question, I used ‘Who’ instead of ‘What’ to see the model behavior with differents questions pronouns the and the model gave the correct answer with a confidence of 0.98. In the last question, besides the low confidence score, the response was also correct.<br>Then I went to questions that the response was not in the text, to see how the model performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*PwRG4OajNY1n5ivbG9w6bg.jpeg" /><figcaption>Questions and answers given by the model</figcaption></figure><p>The model gave a nonsense answer to question 4, but this was expected since there isn’t any mentioning of Bear Market in the letter. But the model gave interesting answers to questions 5 and 6.</p><p>The model said that when the market crashes you should invest in derivatives transactions and this is indeed a good investment to have when the market crashes, as you can see at the market crash from 2020, when the Universa Tail Fund, that has derivatives in his portfolio,<a href="https://www.bloomberg.com/news/articles/2020-04-08/taleb-advised-universa-tail-risk-fund-returned-3-600-in-march"> <strong>returned 3,600% in March of 2020</strong></a>.</p><p>For question 6, although the model did not answer a specific stock to buy, the output was ‘underpriced securities’ that was a good response, since Buffet is famous for buying underpriced securities and underpriced securities are almost always a good investment.</p><h3>Conclusion</h3><p>We can see that a pre-trained transformer model was able to get the correct answers with a new context and even gave answers that made sense from questions whose answers were not explicitly in the context. Of course, the model is not an Oracle yet, but I am looking forward to seeing the evolution of NLP and where this will lead us in the future.</p><p>You can check the code used to write this post at my <a href="https://github.com/jairNeto/warren_buffet_letters">Github repository</a>. Feel free to reach me with any comments on my <a href="https://www.linkedin.com/in/jair-guedes-ferreira-neto/">Linkedin</a> account and thank you a million for reading this post.</p><p>If you like what you read be sure to 👏 it below, share it with your friends and follow me to not miss this series of posts. In the next post I will try to answer the questions:</p><ul><li>What are the most used terms of Buffet and if those terms changed along the time?</li><li>How was his feeling about the Economy and Stocks Market over the years?</li></ul><p><strong>Stay tuned!</strong></p><h3>References</h3><ul><li><a href="https://www.berkshirehathaway.com/letters/letters.html"><strong>https://www.berkshirehathaway.com/letters/letters.html</strong></a></li><li><a href="https://towardsdatascience.com/sentiment-analysis-in-10-minutes-with-bert-and-hugging-face-294e8a04b671">https://towardsdatascience.com/sentiment-analysis-in-10-minutes-with-bert-and-hugging-face-294e8a04b671</a></li><li><a href="https://www.tensorflow.org/tutorials/text/classify_text_with_bert">https://www.tensorflow.org/tutorials/text/classify_text_with_bert</a></li><li><a href="https://huggingface.co/transformers/model_doc/bert.html">https://huggingface.co/transformers/model_doc/bert.html</a></li><li><a href="https://neptune.ai/blog/bert-and-the-transformer-architecture-reshaping-the-ai-landscape">https://neptune.ai/blog/bert-and-the-transformer-architecture-reshaping-the-ai-landscape</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666d717d0c2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/using-nlp-to-get-inside-warren-buffet-mind-part-i-666d717d0c2e">Using NLP to get inside Warren Buffet mind part I</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>