<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://zhiweilin27.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://zhiweilin27.github.io/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-07-19T02:55:29+00:00</updated><id>https://zhiweilin27.github.io/feed.xml</id><title type="html">Personal Website</title><subtitle>Welcome to my website</subtitle><author><name>Zhiwei Lin</name></author><entry><title type="html">Transformer Component</title><link href="https://zhiweilin27.github.io/2024/04/30/Transformer-Component.html" rel="alternate" type="text/html" title="Transformer Component" /><published>2024-04-30T00:00:00+00:00</published><updated>2024-04-30T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2024/04/30/Transformer-Component</id><content type="html" xml:base="https://zhiweilin27.github.io/2024/04/30/Transformer-Component.html"><![CDATA[<p>Some notes for transformer architecture
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/f68f846c-f661-486f-9cfe-f6fc71a0725c" alt="image" /></p>

<h2 id="self-attention">Self-Attention</h2>
<p>The self-attention mechanism uses three matrices - query (Q), key (K), and value (V) - to help the system understand and process the relationships between words in a sentence.</p>

<p>Let’s say we have an input sequence of length N, represented as a matrix X of shape (N, d), where d is the dimension of the input embedding vector. We can calculate the query, key, and value vectors as follows:</p>

<ul>
  <li>Query: We multiply the input embedding matrix X with a learned weight matrix Wq of shape (d, h), where h is the number of attention heads. This produces a matrix Q of shape (N, h), where each row corresponds to the query vector for the corresponding token in the input sequence.Q = XWq</li>
  <li>Key: We multiply the input embedding matrix X with a learned weight matrix Wk of shape (d, h). This produces a matrix K of shape (N, h), where each row corresponds to the key vector for the corresponding token in the input sequence.K = XWk</li>
  <li>Value: We multiply the input embedding matrix X with a learned weight matrix Wv of shape (d, h). This produces a matrix V of shape (N, h), where each row corresponds to the value vector for the corresponding
token in the input sequence.V = XWv
Once we have calculated the query, key, and value vectors, we can use them to compute the attention scores between all pairs of tokens in the input sequence.
The attention scores are then used to weight the corresponding value vectors, which are summed to produce the final output of the self-attention mechanism.
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/8b1af8b3-57a7-4823-9b28-88a6d265811d" alt="image" /></li>
</ul>

<h2 id="word-and-positional-embeddings">Word and Positional Embeddings</h2>
<p>A typical word embedding is a dense vector that represents the meaning and semantic information of a word in a continuous space. The dimension of the embeddings depends on the specific model and configuration. Let’s assume we have a 3-dimensional embedding space for simplicity. An example of embeddings for the tokens in the input sentence “The cat sat on the mat” could look like this:</p>
<ul>
  <li>The: [0.21, -0.15, 0.32]</li>
  <li>cat: [0.85, 0.29, -0.61]</li>
  <li>sat: [-0.37, 0.72, 0.45]</li>
  <li>on: [0.12, -0.64, 0.27]</li>
  <li>the: [0.21, -0.15, 0.32] (Note: Same as ‘The’ embedding, as word embeddings are usually case-insensitive)</li>
  <li>mat: [-0.53, 0.31, 0.81]
These are just example values and not real embeddings. In practice, the embeddings are learned by the model during training, and the dimensionality is usually much larger, such as 128, 256, 512, or even larger.
In addition to the word embeddings, we also need to add positional encoding to these vectors to preserve the order of the words in the input sentence.
Positional encodings is sinusoidal functions</li>
  <li>the output of sine and cosine is in [-1, 1], which is normalized. It won’t grow to an unmanageable size like integers would.</li>
  <li>no additional training has to be done since unique representations are generated for each position.
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/3c446378-f354-4d49-a8ad-9af6cce197b4" alt="image" /> where k is position, i is dimensional index</li>
</ul>

<p>Assuming we have a simple learned positional encoding, the final input embeddings might look like this:</p>
<ul>
  <li>The (word + position): [0.21, -0.15, 0.32] + [0.01, 0.02, 0.03] = [0.22, -0.13, 0.35]</li>
  <li>cat (word + position): [0.85, 0.29, -0.61] + [0.04, 0.05, 0.06] = [0.89, 0.34, -0.55]</li>
  <li>sat (word + position): [-0.37, 0.72, 0.45] + [0.07, 0.08, 0.09] = [-0.30, 0.80, 0.54]</li>
  <li>on (word + position): [0.12, -0.64, 0.27] + [0.10, 0.11, 0.12] = [0.22, -0.53, 0.39]</li>
  <li>the (word + position): [0.21, -0.15, 0.32] + [0.13, 0.14, 0.15] = [0.34, -0.01, 0.47]</li>
  <li>mat (word + position): [-0.53, 0.31, 0.81] + [0.16, 0.17, 0.18] = [-0.37, 0.48, 0.99]</li>
</ul>

<h2 id="multi-headed-attention">Multi-headed attention</h2>
<p>In the multi-head attention layer, the self-attention mechanism is applied multiple times in parallel, each with different sets of learned weights. This allows the model to capture various aspects of the context and focus on different relationships among words simultaneously.
Here’s a step-by-step explanation of the multi-head attention layer:</p>

<ul>
  <li>Determine the number of attention heads. Let’s say we have H heads.</li>
  <li>For each attention head h (where h = 1, 2, …, H), initialize separate sets of weight matrices WQ_h, WK_h, and WV_h.</li>
  <li>Perform self-attention H times in parallel, using the different sets of weight matrices for each head. This involves calculating the Q, K, and V matrices, computing the attention scores and weights, and obtaining the context-aware representations.</li>
  <li>Multiply the concatenated matrix by another learned weight matrix, WO (output matrix), to produce the final output of the multi-head attention layer.
The multi-head attention layer allows the model to capture different contextual aspects and relationships among words simultaneously. For example, one attention head might focus on syntactic relationships, while another could focus on semantic relationships. Combining the results from multiple attention heads enables the transformer to build a richer understanding of the input text.
The output of the multi-head attention layer is then passed through the remaining layers of the transformer, such as position-wise feedforward layers, layer normalization, and residual connections, before producing the final output.</li>
</ul>

<h2 id="ffns">FFNS</h2>
<p>In a transformer architecture, after the multi-head attention layer, the output goes through a position-wise feedforward layer. This layer applies a feedforward neural network (FFNN) independently to each position in the input sequence. The purpose of this layer is to process and combine the features learned by the multi-head attention layer for each token while maintaining their positions.
Here’s an overview of what happens in the position-wise feedforward layer:</p>

<ul>
  <li>For each position (i.e., each token) in the input sequence, apply a feedforward neural network. This FFNN has the same architecture and weights across all positions, but it operates independently on each token.</li>
  <li>The FFNN typically consists of two linear layers (i.e., fully connected layers) with a non-linear activation function, such as ReLU (Rectified Linear Unit), applied in between. This structure allows the model to learn more complex relationships and features within the input data.</li>
  <li>The first linear layer expands the dimension of the input, which helps the model capture more complex patterns. The dimension is then reduced back to the original size by the second linear layer.</li>
  <li>The output of the position-wise feedforward layer for each token is then combined with its corresponding input through a <strong>residual connection (addition)</strong> and passed through a layer normalization step.</li>
</ul>

<p>In summary, the position-wise feedforward layer applies a feedforward neural network independently to each token in the input sequence. This helps process and combine the features learned by the multi-head attention layer while maintaining the positional information of the tokens.
The layer enhances the expressive power of the transformer model, allowing it to capture more complex patterns and relationships within the input data.</p>

<h2 id="layer-normalization">Layer Normalization</h2>
<p>Normalization is a process that standardizes the input layer by adjusting and scaling the activations. Specifically, Transformers use Layer Normalization (LN). Unlike other normalization methods that operate over the batch dimension, LN operates over the feature dimension (across all channels).
The mathematical representation of Layer Normalization is:</p>

\[LN(x) = gamma * (x — mean(x)) / sqrt(var(x) + epsilon) + beta\]

<p>Reference：
https://towardsdatascience.com/into-the-transformer-5ad892e0cee 
https://www.linkedin.com/pulse/gpt-4-explaining-self-attention-mechanism-fatos-ismali/
https://www.linkedin.com/pulse/clear-explanation-transformer-neural-networks-ebin-babu-thomas/</p>

<h2 id="bert-implementation">Bert Implementation</h2>
<p>https://readmedium.com/en/https:/towardsdatascience.com/masked-language-modelling-with-bert-7d49793e5d2c</p>

<h2 id="generative-language-modeling-greedy-beam-search-random-walk">Generative Language Modeling (Greedy, Beam Search, Random Walk)</h2>
<h3 id="greedy-decoding">Greedy Decoding</h3>
<ul>
  <li>It is one of the simplest and fastest methods for generating text and involves selecting the most likely next word at each step in the sequence.
    <h3 id="beam-search">Beam Search</h3>
  </li>
  <li>The fundamental idea of beam search is exploring multiple paths instead of just single one.: Unlike greedy decoding, which only keeps the single best path (the most probable next word) at each step, beam search keeps track of the k most probable paths at each step. This means at every step in the sequence,</li>
  <li>it doesn’t just consider the single most likely next word, but the k most likely next words.
    <h3 id="random-walk">Random Walk</h3>
    <p>method where the selection of each next word in a sequence is based on some level of randomness rather than deterministic rules or purely greedy choices.</p>
  </li>
  <li>Stochastic Sampling: In language generation, a random walk can be analogous to sampling methods where each word is chosen based on a probability distribution over the vocabulary. The model computes probabilities for the next word based on the context provided by previous words, and then a word is randomly selected based on this distribution.</li>
  <li>Temperature Adjusted Sampling: This is a refinement where the “temperature” parameter is used to control the randomness of the word selection:
    <ul>
      <li>A high temperature results in more uniform distributions (higher randomness), making the generation process more exploratory and diverse, akin to a random walk with many possible paths.</li>
      <li>A low temperature results in sharper distributions (less randomness), making the generation more conservative, focusing on more likely words.</li>
    </ul>
  </li>
  <li>Top-k and Top-p Sampling: These are methods to constrain the randomness to the most likely next words:
    <ul>
      <li>Top-k Sampling: Top-k sampling refines the selection process by limiting the pool of potential next tokens to the top-k most likely candidates. Among these top-k tokens, the next token is chosen based on its probability, maintaining a degree of randomness while focusing on more likely options.</li>
      <li>Top-p (Nucleus) Sampling: In top-p sampling or nucleus sampling, the selection pool for the next token is determined by the cumulative probability of the most probable tokens. When you set a threshold p, the model includes just enough of the most probable tokens so that their combined probability reaches or exceeds this threshold</li>
    </ul>
  </li>
</ul>

<p>https://medium.com/@pashashaik/natural-language-generation-from-scratch-in-large-language-models-with-pytorch-4d9379635316</p>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/bc9ad6f1-514f-4222-9a00-a05b74d4eb36" alt="image" />
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/4480c6aa-ba6e-426b-b08d-a696340ffd22" alt="image" /></p>

<h2 id="pre-training">Pre-training</h2>
<p>Pre-training is a foundational step in the LLM training process, where the model gains a general understanding of language by exposure to vast amounts of text data.</p>

<p>Think of it as the model’s introduction to the world of words, phrases, and ideas. During this phase, the LLM learns grammar rules, linguistic patterns, factual information, and reasoning abilities.</p>

<p>To achieve this, the model is fed an extensive dataset containing diverse texts from books, articles, websites, and more. Take the example of GPT-3, with its immense parameter count. It ingested around 570 GB of text data during pre-training. This is like reading hundreds of thousands of books in multiple languages, giving the model a rich tapestry of language to draw from.</p>

<h2 id="fine-tuning">fine-tuning</h2>
<p>After the initial pre-training phase, like primary and secondary education where the LLM gets its general language skills, fine-tuning is like giving it on-the-job training. It’s honing its abilities for particular tasks or domains, transforming it from a language learner into a task-specific expert.</p>

<p>For instance, scientists might fine-tune a model with a dataset of medical texts, making it exceptional at understanding medical jargon and answering health-related questions.</p>

<p>Similarly, you can train a model on legal documents, turning it into a whizz at summarizing contracts and legal discussions.</p>

<p>During fine-tuning, the parameters of the pre-trained model are updated (fine-tuned) using task-specific data, typically with a smaller learning rate than during pre-training.</p>

<h3 id="task-fine-tuning">task fine-tuning</h3>
<p>This method allows the model to adapt its parameters to the nuances and requirements of the targeted task, thereby enhancing its performance and relevance to that particular domain. Task-specific fine-tuning is particularly valuable when you want to optimize the model’s performance for a single, well-defined task, ensuring that the model excels in generating task-specific content with precision and accuracy.</p>

<p>Task-specific fine-tuning is closely related to transfer learning, but transfer learning is more about leveraging the general features learned by the model, whereas task-specific fine-tuning is about 
adapting the model to the specific requirements of the new task.</p>

<h3 id="instruction-fine-tuning">Instruction fine-tuning</h3>
<p>Whereas supervised fine-tuning consists in training models on example inputs and the results derived from them (output), instruction tuning fleshes out input-output examples with another component: instructions.</p>

<p>This is precisely what enables instruction-tuned models to generalize more easily to new tasks. As a result, LLMs tuned in this way become much more versatile and useful.</p>

<p>input examples and their corresponding outputs, instruction tuning augments input-output examples with instructions, which enables instruction-tuned models to generalize more easily to new tasks.</p>

<h3 id="contextual-embeddings">Contextual Embeddings</h3>
<p>Both embedding techniques, traditional word embedding (e.g. word2vec, Glove) and contextual embedding (e.g. ELMo, BERT), aim to learn a continuous (vector) representation for each word in the documents. Continuous representations can be used in downstream machine learning tasks.</p>

<p>Traditional word embedding techniques learn a global word embedding. They first build a global vocabulary using unique words in the documents by ignoring the meaning of words in different context. Then, similar representations are learnt for the words appeared more frequently close each other in the documents. The problem is that in such word representations the words’ contextual meaning (the meaning derived from the words’ surroundings), is ignored. For example, only one representation is learnt for “left” in sentence “I left my phone on the left side of the table.” However, “left” has two different meanings in the sentence, and needs to have two different representations in the embedding space.</p>

<p>On the other hand, contextual embedding methods are used to learn sequence-level semantics by considering the sequence of all words in the documents. Thus, such techniques learn different representations for polysemous words, e.g. “left” in example above, based on their context.</p>

<h3 id="rag">RAG</h3>
<p>Retrieval-augmented generation is a technique used in natural language processing that combines the power of both retrieval-based models and generative models to enhance the quality and relevance of generated text.
https://webcache.googleusercontent.com/search?q=cache:https://colabdoge.medium.com/what-is-rag-retrieval-augmented-generation-b0afc5dd5e79&amp;strip=0&amp;vwsrc=1&amp;referer=medium-parser</p>

<h2 id="few-short-zero-shot">Few short, Zero-shot</h2>
<ul>
  <li>Zero-shot learning — a technique whereby we prompt an LLM without any examples, attempting to take advantage of the reasoning patterns it has gleaned (i.e. a generalist LLM)</li>
  <li>Few-shot learning — a technique whereby we prompt an LLM with several concrete examples of task performance
    <ul>
      <li>Fine tuning - When you already have a model trained to perform the task you want but on a different dataset, you initialise using the pre-trained weights and train it on target (usually smaller) dataset (usually with a smaller learning rate).</li>
      <li>Few shot learning - When you want to train a model on any task using very few samples. e.g., you have a model trained on different but related task and you (optionally) modify it and train for target task using small number of examples.
  For example: Fine tuning - Training a model for intent classification and then fine tuning it on a different dataset. Few shot learning - Training a language model on large text dataset and modifying it (usually last (few) layer) to classify intents by training on small labelled dataset.</li>
    </ul>
  </li>
</ul>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Some notes for transformer architecture]]></summary></entry><entry><title type="html">Sql Notes</title><link href="https://zhiweilin27.github.io/2024/04/25/SQL-Notes.html" rel="alternate" type="text/html" title="Sql Notes" /><published>2024-04-25T00:00:00+00:00</published><updated>2024-04-25T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2024/04/25/SQL-Notes</id><content type="html" xml:base="https://zhiweilin27.github.io/2024/04/25/SQL-Notes.html"><![CDATA[<p>This note is designed for my personal use; it’s not a comprehensive SQL cheat sheet, as I only record the functions/codes that I think are worthy</p>

<h2 id="date">Date</h2>
<h3 id="current-date-and-time">Current Date and Time</h3>
<p>To get the current date and time, most SQL databases provide functions like <code class="language-plaintext highlighter-rouge">NOW()</code>, <code class="language-plaintext highlighter-rouge">CURRENT_DATE</code>, and <code class="language-plaintext highlighter-rouge">CURRENT_TIMESTAMP</code>.</p>

<ul>
  <li>SELECT <code class="language-plaintext highlighter-rouge">CURRENT_DATE</code>
    <ul>
      <li>Returns the current date</li>
    </ul>
  </li>
  <li>SELECT <code class="language-plaintext highlighter-rouge">CURRENT_TIMESTAMP</code>
    <ul>
      <li>Returns the current date and time</li>
    </ul>
  </li>
</ul>

<h3 id="extracting-date-parts">Extracting Date Parts</h3>
<p>You can extract specific parts of a date (like year, month, day, hour, etc.) using the <code class="language-plaintext highlighter-rouge">EXTRACT()</code> function or specific functions like <code class="language-plaintext highlighter-rouge">YEAR()</code>, <code class="language-plaintext highlighter-rouge">MONTH()</code>, and <code class="language-plaintext highlighter-rouge">DAY()</code>.</p>

<ul>
  <li>SELECT EXTRACT(YEAR FROM CURRENT_DATE) AS Year</li>
  <li>SELECT <code class="language-plaintext highlighter-rouge">MONTH(CURRENT_DATE)</code> AS Month</li>
  <li>SELECT <code class="language-plaintext highlighter-rouge">DAY(CURRENT_DATE)</code> AS Day</li>
</ul>

<h3 id="date-arithmeticdatediff">Date Arithmetic/DATEDIFF</h3>
<p>You can add or subtract days, weeks, months, or years to a date using functions like <code class="language-plaintext highlighter-rouge">DATE_ADD</code> or <code class="language-plaintext highlighter-rouge">DATE_SUB</code>, or by using interval arithmetic.</p>

<ul>
  <li>SELECT CURRENT_DATE + <code class="language-plaintext highlighter-rouge">INTERVAL 1 DAY</code>
    <ul>
      <li>Adds 1 day to the current date</li>
    </ul>
  </li>
  <li>SELECT CURRENT_DATE - <code class="language-plaintext highlighter-rouge">INTERVAL 7 DAY</code>
    <ul>
      <li>Subtracts 7 days from the current date</li>
    </ul>
  </li>
  <li>MySQL
    <ul>
      <li>SELECT <code class="language-plaintext highlighter-rouge">DATEDIFF('2023-04-01', '2023-01-01')</code> AS DaysBetween
        <ul>
          <li>Calculate the number of days between two dates</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>PostgreSQL
    <ul>
      <li>SELECT ‘2023-04-01’::date - ‘2023-01-01’::date AS DaysBetween
        <ul>
          <li>Calculate the number of days between two dates</li>
        </ul>
      </li>
      <li>SELECT AGE(‘2023-04-01’::date, ‘2023-01-01’::date) AS DateDifference
        <ul>
          <li>Calculate the precise age between two dates</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>SQL Server
    <ul>
      <li>SELECT DATEDIFF(day, ‘2023-01-01’, ‘2023-04-01’) AS DaysBetween
        <ul>
          <li>Calculate the number of days between two dates</li>
        </ul>
      </li>
      <li>SELECT DATEDIFF(month, ‘2023-01-01’, ‘2023-04-01’) AS MonthsBetween
        <ul>
          <li>Calculate the number of months between two dates</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Oracle
    <ul>
      <li>SELECT (TO_DATE(‘2023-04-01’, ‘YYYY-MM-DD’) - TO_DATE(‘2023-01-01’, ‘YYYY-MM-DD’)) AS DaysBetween
        <ul>
          <li>Calculate the number of days between two dates</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

<h3 id="formatting-dates">Formatting Dates</h3>
<p>To format dates into a specific string format, you might use the <code class="language-plaintext highlighter-rouge">DATE_FORMAT()</code> function in MySQL or <code class="language-plaintext highlighter-rouge">TO_CHAR()</code> in PostgreSQL and Oracle.</p>

<ul>
  <li>MySQL
    <ul>
      <li>SELECT <code class="language-plaintext highlighter-rouge">DATE_FORMAT(CURRENT_DATE, '%Y-%m-%d')</code></li>
    </ul>
  </li>
  <li>PostgreSQL or Oracle
    <ul>
      <li>SELECT <code class="language-plaintext highlighter-rouge">TO_CHAR(CURRENT_DATE, 'YYYY-MM-DD')</code></li>
    </ul>
  </li>
</ul>

<h3 id="comparing-dates">Comparing Dates</h3>
<p>You can compare dates to filter records in a <code class="language-plaintext highlighter-rouge">WHERE</code> clause.</p>

<ul>
  <li>
    <p>SELECT * FROM orders WHERE order_date &gt; ‘2023-01-01’</p>
  </li>
  <li>
    <p>SELECT * FROM orders WHERE order_date <code class="language-plaintext highlighter-rouge">BETWEEN '2023-01-01' AND '2023-03-31'</code></p>
  </li>
</ul>

<h3 id="date-conversion">Date Conversion</h3>
<p>Sometimes you might need to convert strings to dates or vice versa. Functions like <code class="language-plaintext highlighter-rouge">STR_TO_DATE()</code> in MySQL or <code class="language-plaintext highlighter-rouge">TO_DATE()</code> in PostgreSQL and Oracle can be used.</p>

<ul>
  <li>MySQL
    <ul>
      <li>SELECT <code class="language-plaintext highlighter-rouge">STR_TO_DATE('2023-01-01', '%Y-%m-%d')</code></li>
    </ul>
  </li>
  <li>PostgreSQL or Oracle
    <ul>
      <li>SELECT <code class="language-plaintext highlighter-rouge">TO_DATE('2023-01-01', 'YYYY-MM-DD')</code></li>
    </ul>
  </li>
</ul>

<h3 id="time-zone-conversions">Time Zone Conversions</h3>
<p>Handling time zones can be crucial for applications spanning multiple regions.</p>

<ul>
  <li>PostgreSQL
    <ul>
      <li>SELECT CURRENT_TIMESTAMP AT TIME ZONE ‘UTC’</li>
      <li>SELECT CURRENT_TIMESTAMP AT TIME ZONE ‘America/New_York’</li>
    </ul>
  </li>
</ul>

<h2 id="groupby">GroupBy</h2>
<p>In SQL, several standard aggregation functions are typically used with the <code class="language-plaintext highlighter-rouge">GROUP BY</code> clause to summarize data across different groups. These functions perform calculations on a set of values and return a single value. Here’s a list of the most commonly used aggregation functions that you can use with <code class="language-plaintext highlighter-rouge">GROUP BY</code>:</p>
<h3 id="count-sum-avgmax-minstddevstddev_popvariancevar_pop">COUNT(), SUM(), AVG(),MAX(), MIN(),STDDEV(),STDDEV_POP(),VARIANCE(),VAR_POP()</h3>
<ul>
  <li>SELECT category, <code class="language-plaintext highlighter-rouge">COUNT(*)</code> FROM products GROUP BY category</li>
  <li>SELECT department, <code class="language-plaintext highlighter-rouge">SUM(salary)</code> FROM employees GROUP BY department</li>
  <li>SELECT department, <code class="language-plaintext highlighter-rouge">AVG(salary)</code> FROM employees GROUP BY department</li>
  <li>SELECT department, <code class="language-plaintext highlighter-rouge">MAX(salary)</code> FROM employees GROUP BY department</li>
  <li>SELECT department, <code class="language-plaintext highlighter-rouge">MIN(salary)</code> FROM employees GROUP BY department</li>
  <li>SELECT department, <code class="language-plaintext highlighter-rouge">STDDEV(salary)</code> FROM employees GROUP BY department</li>
  <li>SELECT department, <code class="language-plaintext highlighter-rouge">VARIANCE(salary)</code> FROM employees GROUP BY department</li>
</ul>

<h3 id="group_concat-mysqlsqlite">GROUP_CONCAT() (MySQL/SQLite)</h3>
<p>Concatenates values from a group into a single string with values separated by a delimiter. Not standard SQL but available in several SQL databases.</p>

<ul>
  <li>SELECT department, <code class="language-plaintext highlighter-rouge">GROUP_CONCAT(employee_name SEPARATOR ', ')</code> FROM employees GROUP BY department;</li>
</ul>

<h3 id="additional-aggregation-considerationsdistinct-over-paritions">Additional Aggregation Considerations(Distinct, Over Paritions)</h3>
<ul>
  <li><strong>Distinct</strong>: Many aggregation functions allow you to specify <code class="language-plaintext highlighter-rouge">DISTINCT</code> to consider only distinct values within each group.
    <ul>
      <li>SELECT category, COUNT(<code class="language-plaintext highlighter-rouge">DISTINCT</code> product_name) FROM products GROUP BY category;</li>
    </ul>
  </li>
  <li><strong>Over Partitions</strong>: While not used directly with <code class="language-plaintext highlighter-rouge">GROUP BY</code>, many aggregation functions can also be used with the <code class="language-plaintext highlighter-rouge">OVER()</code> clause to perform calculations across different partitions of data without collapsing the rows into a single output row per group.
    <ul>
      <li>SELECT department, salary, AVG(salary) OVER (PARTITION BY department) FROM employees;</li>
    </ul>
  </li>
</ul>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[This note is designed for my personal use; it’s not a comprehensive SQL cheat sheet, as I only record the functions/codes that I think are worthy]]></summary></entry><entry><title type="html">Basic Ratemaking</title><link href="https://zhiweilin27.github.io/2024/04/19/Basic-Ratemaking.html" rel="alternate" type="text/html" title="Basic Ratemaking" /><published>2024-04-19T00:00:00+00:00</published><updated>2024-04-19T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2024/04/19/Basic-Ratemaking</id><content type="html" xml:base="https://zhiweilin27.github.io/2024/04/19/Basic-Ratemaking.html"><![CDATA[<p>My notes refer to the study manual <a href="https://www.casact.org/sites/default/files/2021-03/5_Werner_Modlin.pdf">BASIC RATEMAKING Fifth Edition, May 2016</a>.</p>

<h2 id="chapter-1-introduction">Chapter 1 Introduction</h2>
<p><strong>FUNDAMENTAL INSURANCE EQUATION</strong></p>
<ul>
  <li><strong>Price = Cost + Profit</strong></li>
  <li><strong>Premium= Losses + LAE + UW Expenses + UW Profit</strong>
    <h3 id="exposure">Exposure</h3>
    <p>The basic unit of risk underlying the insurance premium includes written, earned, unearned, and in-force exposures</p>
  </li>
  <li><strong>Written exposures</strong> are the total exposures arising from policies issued (i.e., underwritten or
written) during a specified period of time, such as a calendar year or quarter.</li>
  <li><strong>Earned exposures</strong> represent the portion of the written exposures for which coverage has already
been provided as of a certain point in time.</li>
  <li><strong>Unearned exposures</strong> represent the portion of the written exposures for which coverage has not
yet been provided as of that point in time.</li>
  <li><strong>In-force exposures</strong> are the number of insured units that are exposed to loss at a given point in
time.</li>
</ul>

<h3 id="premium">Premium</h3>
<p>The amount the insured pays for insurance coverage includes written, earned, unearned, and in-force premium</p>
<ul>
  <li><strong>Written premium</strong> is the total premium associated with policies that were issued during a
specified period.</li>
  <li><strong>Earned premium</strong> represents the portion of the written premium for which coverage has already
been provided as of a certain point in time.</li>
  <li><strong>Unearned premium</strong> is the portion of the written premium for which coverage has yet to be
provided as of a certain point in time.</li>
  <li><strong>In-force premium</strong> is the full-term premium for policies that are in effect at a given point in time.</li>
</ul>

<h3 id="claim">Claim</h3>
<ul>
  <li>An <strong>insurance policy</strong> entails the insured paying a premium to the insurer for coverage against specific events.</li>
  <li>When such an event occurs, the insured (now the <strong>claimant</strong>) files a claim. The event’s date is known as the <strong>date of loss</strong> or <strong>accident date</strong>.</li>
  <li>Claims unknown to the insurer at a given time are termed <strong>unreported claims</strong> or <strong>incurred but not reported (IBNR) claims</strong></li>
  <li>After the report date, a claim becomes known to the company and is classified as a <strong>reported claim</strong>. It remains an <strong>open claim</strong> until settled, after which it is considered closed. However, claims can be reopened if further activity occurs post-closure.</li>
</ul>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/249f8ff9-9921-4794-9492-bb98e9e7b394" alt="Claim Date" /></p>

<h3 id="losses">Losses</h3>
<p>Loss under an insurance policy is the compensation amount payable to the claimant. Loss terminology includes paid loss, case reserve, reported or case incurred loss, IBNR/IBNER reserves, and ultimate loss.</p>
<ul>
  <li><strong>Paid loss</strong> is amounts already disbursed to the claimant.</li>
  <li><strong>Case reserve</strong> is an estimate of the amount of money required to ultimately settle the claim, it excludes any payments already made.</li>
  <li><strong>Reported loss</strong> is equal to Paid loss + Case reserve</li>
  <li><strong>Ultimate loss</strong> is the total required to settle the claim. Estimated Ultimate Loss equal to Reported Loss + IBNR Reserve + IBNER Reserve.</li>
</ul>

<h3 id="loss-adjustment-expense-lae">Loss Adjustment Expense (LAE)</h3>
<p>In addition to the money paid to the claimant for compensation, <strong>loss adjustment expenses (LAE)</strong> are costs insurers incur while settling claims, divided into <strong>allocated loss adjustment expenses (ALAE)</strong> and <strong>unallocated
loss adjustment expenses (ULAE)</strong>:</p>

<p>LAE =  ALAE + ULAE.</p>

<ul>
  <li>ALAE are claim-related expenses that are directly attributable to a specific claim; for example, fees
associated with outside legal counsel hired to defend a claim can be directly assigned to a specific claim.</li>
  <li>ULAE are claim-related expenses that cannot be directly assigned to a specific claim. For example,
salaries of claims department personnel are not readily assignable to a specific claim and are categorized
as ULAE.</li>
</ul>

<h3 id="underwriting-expenses-uw-expenses">Underwriting Expenses (UW Expenses)</h3>
<p>In addition to loss adjustment expenses, underwriting expenses are costs insurers incur for various expenses in acquiring and servicing policies.</p>
<ul>
  <li><strong>Commissions and brokerage</strong>: are payments made to insurance agents or brokers for generating business.</li>
  <li><strong>Other acquisition costs</strong>: are expenses beyond commissions and brokerage, such as those for media advertising and mailings to potential customers.</li>
  <li><strong>General expenses</strong>: are the operational and any other miscellaneous costs. For example, upkeep for the home office.</li>
  <li><strong>Taxes, licenses, and fees</strong>: are all taxes and miscellaneous fees paid by the insurer excluding federal income taxes. Premium taxes and licensing fees are examples of items included in this category.</li>
</ul>

<h3 id="underwriting-profit-uw-profit">Underwriting Profit (UW Profit)</h3>
<p>The two primary profit sources for insurance companies are underwriting profit and investment income.</p>
<ul>
  <li><strong>Underwriting profit</strong>, also known as operating income, is the profit from individual policies calculated as income minus expenses, similar to profit definitions in other industries.</li>
  <li><strong>Investment income</strong>  is the profit from investing the funds that the insurance company holds.</li>
</ul>

<h3 id="basic-insurance-ratios">Basic Insurance Ratios</h3>
<p>A set of basic ratios to monitor and evaluate the appropriateness of an insurance company’s rates.</p>

<ul>
  <li><strong>Frequency</strong>: \(\text{Frequency} = \frac{ \text{# of Claims}}{\text{# of Exposures}}\).
    <ul>
      <li>Help measure the effectiveness of specific underwriting actions.</li>
      <li>For example, if the number of claims is 100,000 and the number of earned exposures is 2,000,000, then the frequency is 5% (= 100,000 / 2,000,000).</li>
    </ul>
  </li>
  <li><strong>Severity</strong>: \(\text{average cost of claims} =\text{Severity} = \frac{\text{Losses}}{\text{# of Claims}}\).
    <ul>
      <li>
\[\text{Paid Severity} = \frac{\text{Paid Losses}}{\text{# of Claims Closed}}\]
      </li>
      <li>
\[\text{Reported Severity} = \frac{\text{Reported Losses}}{\text{# of Claims Reported}}\]
      </li>
      <li>Additionally, ALAE may be included or excluded from the numerator.</li>
      <li>Help measure the loss trends.</li>
      <li>For example, if the total loss dollars are $300,000,000 and the number of claims is 100,000, then the severity is
$3,000 (= $300,000,000 / 100,000).</li>
    </ul>
  </li>
  <li><strong>Pure Premium (or Loss Cost)</strong>: \(\text{average loss per exposure } =\text{Pure Premium} = \frac{\text{Losses}}{\text{# of Exposures}} = \text{Frequency} X \text{times Severity}\)
    <ul>
      <li>Typically, reported losses (or ultimate losses) and earned exposures are used.</li>
      <li>The reported losses may or may not include ALAE and/or ULAE.</li>
      <li>Help measure the overall loss cost trends.</li>
      <li>For example, if total loss dollars are $300,000,000 and the number of exposures is 2,000,000, then the pure premium is $150 (= $300,000,000 / 2,000,000 = 5.0% x $3,000).</li>
    </ul>
  </li>
  <li><strong>Average Premium</strong>: \(\text{Average Premium} = \frac{\text{Premuim}}{\text{# Of Expesures}}\)
    <ul>
      <li>It is important that the premium and the exposures be on the same basis (e.g., written, earned, or in-force).</li>
      <li>Changes in average premium may indicate
        <ul>
          <li>Rate change</li>
          <li>Change in the mix of business, e.g. deductible shift, insured limit shift, risk shifts, and etc.</li>
        </ul>
      </li>
      <li>For example, if the total premium is $400,000,000 and the total exposures are 2,000,000, then the average</li>
    </ul>
  </li>
  <li><strong>Loss Ratio</strong>: \(\text{Loss Ratio} = \frac{\text{Losses}}{\text{Premium}} = \frac{\text{Pure premium}}{\text{Average Premium}}\).
    <ul>
      <li>Typically, the ratio uses total reported losses and total earned premiums; however, other variations are common. Companies may include LAE in the calculation of loss ratios (commonly referred to as loss and LAE ratios).</li>
      <li>Help measure the adequacy of the rates</li>
      <li>For example, if the total loss dollars are $300,000,000 and the total premium is $400,000,000, then the loss ratio is 75% (= $300,000,000 / $400,000,000).</li>
    </ul>
  </li>
  <li><strong>Loss Adjustment Expense Ratio (LAE Ratio)</strong>: \({\text{LAERatio}} = \frac{\text{Loss Adjustment Expenses}}{\text{Losses}}\)
    <ul>
      <li>The loss adjustment expenses include both allocated and unallocated loss adjustment expenses. Companies may differ as to whether paid or reported (incurred) figures are used.</li>
      <li>Companies monitor this ratio over time to determine if costs associated with claim settlement procedures are stable or not. A company may compare its ratio to those of other companies as a benchmark for its claims settlement procedures.</li>
    </ul>
  </li>
  <li>
    <p><strong>Underwriting Expense Ratio</strong>: \(\text{UW Expense Ratio} = \frac {\text{UW Expense}}{\text{Premium}}\)</p>
  </li>
  <li><strong>Operating Expense Ratio</strong>: \(\text{OER} = \text{UW Expense Ratio} + \frac {\text{LAE}} {\text{Earned Premium}}\)
    <ul>
      <li>The OER is used to monitor operational expenditures and is key to determining overall profitability.</li>
    </ul>
  </li>
  <li><strong>Combined Ratio</strong>: \(\text{Combined Ratio} = \text{Loss ratio} + \frac{\text{LAE}}{\text{Earned Premium}} + \frac{\text{Underwriting Expenses}}{\text{Written Premium}}\)
    <ul>
      <li>In calculating the combined ratio, the loss ratio should not include LAE or it will be double counted.</li>
      <li>some companies may compare underwriting expenses incurred throughout the policy to earned premiums rather than to written premiums. In this case,
the companies may choose to define combined ratio as \(\text{Combined Ratio} = \text{Loss Ratio} + \text{OER}\)</li>
    </ul>
  </li>
  <li><strong>Retention Ratio</strong>: \(\text{Retention Ratio} = \frac{\text{# of Policies Renewed}}{\text{# of potential Renewal Policies}}\).
    <ul>
      <li>Retention ratios and changes in the retention ratios are monitored closely by product management and
marketing departments</li>
      <li>Retention ratios are used to gauge the competitiveness of rates and are very closely examined following rate changes or major changes in service</li>
      <li>If 100,000 policies are invited to renew in a particular month and 85,000 of the insureds choose to renew,
then the retention ratio is 85% (= 85,000 / 100,000).</li>
    </ul>
  </li>
  <li><strong>Close Ratio</strong>: \(\text{Closs ratio} = \frac{\text{# of Accepted Quotes}}{\text{# of Quotes}}\).
    <ul>
      <li>a prospective insured may receive multiple quotes and companies may count that as one quote or may consider each quote
separately.</li>
      <li>Close ratios and changes in the close ratios are monitored closely by product management and marketing
departments.</li>
      <li>Closed ratios are used to determine the competitiveness of rates for new business.</li>
      <li>If the company provides 300,000 quotes in a particular month and generates 60,000 new
policies from those quotes, then the close ratio is 20% (= 60,000 / 300,000).</li>
    </ul>
  </li>
</ul>

<h2 id="chapter-2-rating-manuals">CHAPTER	2 RATING	MANUALS</h2>
<p>For most lines of business, the following information is necessary to calculate the premium for a given risk:</p>
<ul>
  <li>Rules</li>
  <li>Rate pages (i.e., base rates, rating tables, and fees)</li>
  <li>Rating algorithm</li>
  <li>Underwriting guidelines
Generally speaking, the first three items are found in a company’s rating manual, and the underwriting guidelines are maintained in a separate proprietary underwriting manual.
    <h3 id="rules">Rules</h3>
  </li>
  <li>Typically contains qualitative information that is needed to understand and apply the quantitative rating algorithms</li>
  <li>To be an aid in calculating premium
    <h3 id="ratepages">RATEPAGES</h3>
  </li>
  <li>The rate pages generally contain the numerical inputs (e.g., base rates, rating tables, and fees) needed to calculate the premium</li>
  <li>Base Risk
    <ul>
      <li>A specific risk pre A specific risk pre–defined by the insurer
– Represents a set of risk characteristics that are most common or target market.</li>
    </ul>
  </li>
  <li>Base Rate
    <ul>
      <li>The rate applied to the base risk</li>
      <li>Not the average rate</li>
      <li>The rate for risks other than base risk is determined by modifying the base rate by a series of multipliers or addends or some unique mathematical expression.</li>
      <li>
        <h3 id="rating-algorithms">Rating Algorithms</h3>
      </li>
    </ul>
  </li>
  <li>describes in detail how to combine the various components in the rules and rate pages to calculate the overall premium charged for any risk that is not specifically pre-printed in a rate table.</li>
  <li>May include:
    <ul>
      <li>The order in which rating variables should be considered</li>
      <li>Multiplicative or additive</li>
      <li>Maximum and minimum premium</li>
    </ul>
  </li>
</ul>

<h3 id="underwriting-guidelines">Underwriting Guidelines</h3>
<ul>
  <li>Underwriting guidelines may be used to specify
– Decisions to accept, decline, or refer (to senior underwriter) risks 
– Company Placement
    <ul>
      <li>Tier placement
– Schedule rating credits/debits</li>
    </ul>
  </li>
</ul>

<p><a href="https://www.casact.org/sites/default/files/2021-03/5_Werner_Modlin.pdf">HOMEOWNERS RATING MANUAL EXAMPLE</a> Check page 17 for homeowners rating manual example.</p>

<h2 id="chapter-3-ratemaking-data">CHAPTER	3 RATEMAKING	DATA</h2>
<p>Data is used by actuaries for many purposes including ratemaking.</p>

<h3 id="internal-data">Internal Data</h3>
<ul>
  <li>Risk information including exposures, premiums, claim counts, and losses</li>
  <li>Accounting Information including Underwriting expense, ULAE</li>
</ul>

<h3 id="risk-data">Risk Data</h3>
<ul>
  <li>Policy Database
    <ul>
      <li>Policy Identifier</li>
      <li>Risk Identifier (one policy may have multiple risks, e.g. two cars, two locations of insured)</li>
      <li>Relevant Dates (original effective date, original expiration date, date of amendment)</li>
      <li>Premium</li>
      <li>Exposure</li>
      <li>Characteristic</li>
    </ul>
  </li>
  <li>Claim Database
    <ul>
      <li>Policy Identifier</li>
      <li>Risk Identifier</li>
      <li>Claim Identifier</li>
      <li>Claimant Identifier</li>
      <li>Event Identifier</li>
      <li>Relevant Loss Dates (Report data, data of loss payment, date of reserve change, data of claim status change)</li>
      <li>Claim Status (open, closed, reopen, reclosed)</li>
      <li>Paid Loss</li>
      <li>Case Reserve</li>
      <li>ALAE (ULAE is handled elsewhere)</li>
      <li>Salvage &amp; Subrogation</li>
      <li>Type of Injury</li>
      <li>Cause of Loss</li>
    </ul>
  </li>
</ul>

<h3 id="accounting-information">Accounting Information</h3>
<ul>
  <li>Underwriting Expenses
    <ul>
      <li>Expenses incurred in the acquisition and servicing of the policies, including general expenses, other acquisition expenses, commissions and brokerage, taxes, licenses, and fees</li>
    </ul>
  </li>
  <li>ULAE</li>
</ul>

<h3 id="data-aggregation">Data Aggregation</h3>
<ul>
  <li>Calendar year
    <ul>
      <li>Consider all premium and loss transactions that occur during the 12-month calendar year</li>
      <li>All premiums and exposures are fixed at the end of the CY</li>
      <li>CY data is available quickly once the CY ends</li>
      <li>Main disadvantage of CY is the mismatch in timing between premiums and losses. For example, premium earned during CY come from policies in force during that year, and losses may include payments and reserve changes on claims from policies issued years ago.</li>
    </ul>
  </li>
  <li>Accident year
    <ul>
      <li>Considers losses for accidents that have occurred during a 12-month period, regardless of the policy-issued date</li>
      <li>Premium and exposure are defined as the same as CY aggregation</li>
      <li>Reported losses consist of loss payments made plus case reserves only for those claims that occurred during that year</li>
      <li>Reported losses can and often do change at the end of AY
        <ul>
          <li>Additional Claims are reported and paid</li>
          <li>Reserves are changed</li>
        </ul>
      </li>
      <li>Future development on those known losses needs to be estimated</li>
      <li>Better match of premium and losses than CY
        <ul>
          <li>Losses on accidents occurring during the year are compared to premiums earned on policies during the same year</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Policy Year
    <ul>
      <li>Considers all premium and loss transactions on policies that were effective during a 12-month period</li>
      <li>Premiums and exposures are not fixed until after the expiration date</li>
      <li>Reported losses for PY consist of payments made plus case reserves only for those claims covered by policies effective during the year</li>
      <li>Reported losses can and often do change at the end of AY
        <ul>
          <li>Additional claims are reported and paid</li>
          <li>Reserves are changed</li>
        </ul>
      </li>
      <li>Best Match between losses and premium
        <ul>
          <li>Losses on policies effective during the year are compared with premiums earned on those same policies</li>
        </ul>
      </li>
      <li>Data takes longer to develop than both CY and AY
        <ul>
          <li>For a product with an annual policy term, premiums are not fully earned until 24 months after the start of the policy year.</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Report year
    <ul>
      <li>Considers losses for accidents that are reported during a 12-month period, regardless of when the claim occurred</li>
      <li>Premium and exposures are defined as the same as CY aggregation</li>
      <li>Reported losses consist of loss payments made plus case reserves only for those claims that are reported during that year</li>
      <li>Reported losses can and often do change at the end of AY
        <ul>
          <li>Additional claims are reported and paid</li>
          <li>Reserves are changed</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[My notes refer to the study manual BASIC RATEMAKING Fifth Edition, May 2016.]]></summary></entry><entry><title type="html">Nlp Tokenization And Word Sense Disambiguation</title><link href="https://zhiweilin27.github.io/2024/02/10/NLP-Tokenization-and-Word-Sense-Disambiguation.html" rel="alternate" type="text/html" title="Nlp Tokenization And Word Sense Disambiguation" /><published>2024-02-10T00:00:00+00:00</published><updated>2024-02-10T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2024/02/10/NLP-Tokenization-and-Word-Sense-Disambiguation</id><content type="html" xml:base="https://zhiweilin27.github.io/2024/02/10/NLP-Tokenization-and-Word-Sense-Disambiguation.html"><![CDATA[<p>Tokenization in natural language processing (NLP)involves breaking down text into smaller units called tokens. These tokens can be words, characters, or subwords. This process is for preparing text for further processing.</p>

<h2 id="word-tokenization">Word Tokenization</h2>
<p>Word tokenization is the process of splitting text into individual words.</p>

<p>Example: Input: “I like doing NLP”</p>

<p>Tokens: [“I”, “like”, “doing”, “NLP”]</p>

<h2 id="byte-pair-encoding-tokenization">Byte-Pair Encoding Tokenization</h2>
<p>It’s used by a lot of Transformer models, including GPT, GPT-2, RoBERTa, BART, and DeBERTa. BPE training starts by computing the unique set of words used in the corpus, then iteratively merging the most frequently occurring character or byte pairs in a given dataset until a desired vocabulary size is reached.</p>

<p>Example: word “low” appear 5 times, “lowest” appear 2 times, “newer” appear 6 times, “wider” appear 3 times, “new” appear 2 time in the corpus.</p>

<p>Step 1: Initial Vocabulary</p>

<p>corpus                                              vocabulary</p>

<p>5   l o w _                                           _, d, e, i, l, n, o, r, s, t, w</p>

<p>2    l o w e s t _</p>

<p>6    n e w e r _</p>

<p>3    w i d e r _</p>

<p>2    n e w _</p>

<p>Step 2: Count and Merge Frequent Pairs (er appear 9 times)</p>

<p>corpus                                              vocabulary</p>

<p>5   l o w _                                          _, d, e, i, l, n, o, r, s, t, w, er</p>

<p>2    l o w e s t _</p>

<p>6    n e w er _</p>

<p>3    w i d er _</p>

<p>2    n e w _</p>

<p>step 3: continues to count and merge Frequent Pairs (er_ appear 9 times)</p>

<p>corpus                                              vocabulary</p>

<p>5   l o w _                                         _ , d, e, i, l, n, o, r, s, t, w, er, er_</p>

<p>2    l o w e s t _</p>

<p>6    n e w er_</p>

<p>3    w i d er_</p>

<p>2    n e w _</p>

<p>step n: continues until the max vocabulary set is reached.</p>

<p>Algorithm:</p>

<p><img width="747" alt="Screenshot 2024-02-28 at 12 27 59 AM" src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/3dc6166e-d4fb-4cf7-bce4-0929b904b315" /></p>

<p>The articles I found which are very helpful for understanding Byte-Pair Encoding Tokenization:</p>
<ul>
  <li><a href="https://towardsdatascience.com/byte-pair-encoding-subword-based-tokenization-algorithm-77828a70bee0">Byte-Pair Encoding: Subword-based tokenization algorithm</a> written by Chetna Khanna</li>
  <li><a href="https://martinlwx.github.io/en/the-bpe-tokenizer/">BPE Tokenization Demystified: Implementation and Examples</a> written by MartinLwx</li>
  <li><a href="https://vinija.ai/nlp/tokenizer/">Vinija’s notes</a> written by Jain, Vinija, and Chadha, Aman.</li>
</ul>

<h3 id="advantage">Advantage</h3>
<ul>
  <li>Handling Rare Words: By tokenizing words into subwords, BPE mitigates the issue of out-of-vocabulary(OOV) by allowing the model to understand and generate words that it might not have seen during training.</li>
  <li>Reduced Model Size: By tokenizing words into subwords, BPE allows the model to work with a more manageable vocabulary size. This can reduce the model’s complexity and the amount of memory required.</li>
</ul>

<h3 id="implementation">Implementation</h3>
<p>I’ve implemented both word tokenizer and BPE tokenizer in Python from scratch:</p>

<p><i class="far fa-hand-pointer fa-rotate-90"></i>
<a href="https://github.com/zhiweilin27/NLP/blob/main/a1_tweets.txt">dataset</a></p>

<p><i class="far fa-hand-pointer fa-rotate-90"></i>
<a href="https://github.com/zhiweilin27/NLP/blob/main/a1_p1_lin_112845768.py">python code</a></p>

<p><i class="far fa-hand-pointer fa-rotate-90"></i>
<a href="https://github.com/zhiweilin27/NLP/blob/main/a1_p1_lin_112845768_OUTPUT.txt">output</a></p>

<h2 id="wordpiece-tokenization">WordPiece Tokenization</h2>
<p>Word Piece is also a subword tokenization algorithm, it’s similar to BPE but differs slightly in its approach to creating new tokens. Instead of just merging the most frequent pairs, WordPiece looks at the likelihood of the entire vocabulary and adds the token that increases the likelihood of the data the most. It’s first proposed in the paper “<a href="https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf">Japanese and Korean Voice Search</a>”. The core idea of Word Piece method:</p>
<ul>
  <li>does putting “a” and “b” together increase the ability to model the corpus? can be quantified by: p(‘a’,’b’) / (p(‘a’)p(‘b’))</li>
</ul>

<p>The articles I found which are very helpful for understanding WordPiece:</p>
<ul>
  <li><a href="https://towardsdatascience.com/wordpiece-subword-based-tokenization-algorithm-1fbd14394ed7">WordPiece: Subword-based tokenization algorithm</a> written by Chetna Khanna</li>
  <li><a href="https://vinija.ai/nlp/tokenizer/">Vinija’s notes</a> written by Jain, Vinija, and Chadha, Aman.</li>
</ul>

<h2 id="logistic-regression-for-word-sense-disambiguation-wsd">Logistic Regression for Word Sense Disambiguation (WSD)</h2>
<p>WSD is the process of identifying which sense of a word (i.e., its meaning) is used in a sentence when the word has multiple meanings.
For example, the word “return” has different meanings such as:</p>
<ol>
  <li>come back to a place or situation.</li>
  <li>To yield a profit or result.</li>
</ol>

<p>This task is crucial for many natural language processing (NLP) applications, such as machine translation, information retrieval, and text understanding. Logistic Regression is a simple (easy to interpret) and useful model to identify the sense of a word in a sentence, but the pitfall of logistic regression is it might not come with the most accurate result.</p>

<p>More details about logistic regression or generalized linear regression can be seen in this <a href="https://zhiweilin27.github.io/2023/10/22/Generalized-Linear-Regression.html#logistic-regression">post</a></p>

<h3 id="implementation-1">Implementation</h3>
<p>I’ve implemented logistic regression using PyTorch for Word Sense Disambiguation (WSD) from scratch:
(One also can use CNN, RNN, or transformer to do this task, as those may yield better accuracy)</p>

<p><i class="far fa-hand-pointer fa-rotate-90"></i>
<a href="https://github.com/zhiweilin27/NLP/blob/main/a1_wsd_24_2_10.txt">dataset</a></p>

<p><i class="far fa-hand-pointer fa-rotate-90"></i>
<a href="https://github.com/zhiweilin27/NLP/blob/main/a1_p2_lin_112845768.py">python code</a></p>

<p><i class="far fa-hand-pointer fa-rotate-90"></i>
<a href="https://github.com/zhiweilin27/NLP/blob/main/a1_p2_lin_112845768_OUTPUT.txt">output</a></p>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Tokenization in natural language processing (NLP)involves breaking down text into smaller units called tokens. These tokens can be words, characters, or subwords. This process is for preparing text for further processing.]]></summary></entry><entry><title type="html">Principle Component Analysis (pca)</title><link href="https://zhiweilin27.github.io/2023/12/02/Principle-Component-Analysis-(PCA).html" rel="alternate" type="text/html" title="Principle Component Analysis (pca)" /><published>2023-12-02T00:00:00+00:00</published><updated>2023-12-02T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2023/12/02/Principle-Component-Analysis-(PCA)</id><content type="html" xml:base="https://zhiweilin27.github.io/2023/12/02/Principle-Component-Analysis-(PCA).html"><![CDATA[<h2 id="principal-components-overview">Principal Components Overview</h2>

<p>Suppose we have \(X\) as a vector of \(p\) random variables, then the covariance matrix \(V\) is \(p \times p\). 
We want to find a vector \(\alpha_1 = (\alpha_{11}, \alpha_{12}, ..., \alpha_{1p})\) such that \(\alpha_{1}^{T} X\) gives maximum variance.</p>

<p>In mathematical terms, it is expressed as:</p>

\[\begin{align*}
\max(\text{cov}(\alpha_{1}^{T} X)) &amp;= \max(\alpha_{1}^{T} X \alpha_{1}) \text{        such that } ||\alpha_{1}||^2 = 1 \\
&amp;\Rightarrow L(\alpha_1, \lambda) = \alpha_{1}^{T} X \alpha_1 - \lambda(||\alpha_{1}||^2 - 1)
\end{align*}\]

<p>Taking derivatives with respect to \(\lambda\) and \(\alpha_1\):</p>

\[\frac{\delta L}{\delta \lambda} = ||\alpha_{1}||^2 - 1 = 0\]

\[\frac{\delta L}{\delta \alpha_1} = 2(V\alpha_{1}- \lambda \alpha_{1}) = 0\]

\[\Rightarrow V\alpha_{1} = \lambda \alpha_{1}\]

<p>Therefore, the maximum value for \(||\alpha_1||^2 = 1\) is \(\lambda_1\). 
Thus, a vector \(\alpha_1\) that gives maximum variance corresponds to the eigenvector for \(\lambda_1\).</p>

<p>For the second vector \(\alpha_2\), it is also required to be uncorrelated with \(\alpha_1\):</p>

\[\max(\text{cov}(\alpha_{2}^{T} X)) = \max(\alpha_{2}^{T} X \alpha_2) \text{        such that } ||\alpha_2||^2 = 1 \text{ and } \alpha_{1}^{T} \alpha_2 = 0\]

\[\Rightarrow L(\alpha_2, \lambda, \lambda_2) = \alpha_{2}^{T} X \alpha_2 - \lambda(||\alpha_{2}||^2 - 1) - \lambda_2(\alpha_{1}^{T} \alpha_2)\]

<p>Continues this procedure will find all \(\lambda_k\), \(\alpha_k\) for kth P.C.</p>

<p>Given \(X\) is a vector of \(P\) and the covariance matrix is \(p \times p\):</p>

<p>Total variance = \(\lambda_1 + \lambda_2 + \ldots + \lambda_p\)</p>

<p>The \(k\)th principal component explains: \(\frac{\lambda_k}{\lambda_1 + \lambda_2 + \ldots + \lambda_p}\)</p>

<p>The first \(k\) principal components explain: \(\frac{\lambda_1 + \lambda_2 + \ldots + \lambda_k}{\lambda_1 + \lambda_2 + \ldots + \lambda_p}\)</p>

<h2 id="eigendecomposition">Eigendecomposition</h2>

<p>Principal Component Analysis (PCA) aims to reduce the dimensionality of high-dimensional data points by linearly projecting them onto a lower-dimensional space while preserving as much variance as possible or minimizing the reconstruction error made by this projection. This is achieved by performing eigendecomposition on the covariance matrix V of the dataset \(X\), such that \(V=PDP^T\). Since the covariance matrix is symmetric, eigenvalues in matrix D are always positive. An eigenvector that preserves maximum variance corresponds to the largest eigenvalue.</p>

<h2 id="singular-value-decomposition">Singular Value Decomposition</h2>

<p>Singular Value Decomposition (SVD) is more stable than eigendecomposition, especially when the dataset has fewer data points than dimensions. Directly performing PCA can be inefficient, so singular value decomposition (SVD) is preferred.</p>

<p><a href="https://graphics.stanford.edu/courses/cs233-20-spring/ReferencedPapers/LectureNotes-PCA.pdf">some good lecture notes found</a></p>

<p><a href="https://people.tamu.edu/~sji/classes/PCA.pdf">lecture notes</a></p>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Principal Components Overview]]></summary></entry><entry><title type="html">CNN and ResNet</title><link href="https://zhiweilin27.github.io/2023/12/01/CNN-ResNet.html" rel="alternate" type="text/html" title="CNN and ResNet" /><published>2023-12-01T00:00:00+00:00</published><updated>2023-12-01T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2023/12/01/CNN-ResNet</id><content type="html" xml:base="https://zhiweilin27.github.io/2023/12/01/CNN-ResNet.html"><![CDATA[<h2 id="neural-network-overview">Neural Network Overview</h2>
<p>Neural Network is inspired by biological phenomena in the human brain - how information is transferred as signals in the human brain. There are many types of Neural Networks that exist. The basic neural network architecture can be classified as Feed-forward Neural Network, CNN, RNN, and etc.</p>

<h3 id="gradient-descent">Gradient Descent:</h3>
<p>Gradient Descent is a first-order iterative algorithm for finding a local minimum. It plays a crucial role in a neural network architecture. There are three types of gradient descent:
\(\theta_{i+1} = \theta_i - \alpha \nabla J(\theta_i)\)
where \(\alpha\) is the learning rate.</p>
<ul>
  <li>Batch GD: Uses all data points for parameter updates.</li>
  <li>Stochastic GD: Uses one random data point for updates.</li>
  <li><strong>Mini Batch GD</strong>: Uses a few random data points for updates.</li>
</ul>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/62ad48a5-0303-4895-9909-91fb08bb6412" alt="gradient-descent-learning-rate" /></p>

<p>The learning rate \(\alpha\) cannot be too large; otherwise, it will diverge. We generally adjust the learning rate after several epochs.</p>

<h3 id="activation-function">Activation Function</h3>
<p>There are several commonly used activation functions such as ReLU, tanH, and the Sigmoid functions. Each of these functions has a specific usage.</p>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/81de4de6-6986-4d64-b07a-5713d4265b7a" alt="Activation functions" /></p>

<p>As in linear regression notes, we know optimization requires the loss function to be convex. However, in deep learning, the loss function is generally non-convex due to non-linear activation functions. Because of this, we only guarantee finding a local minimum.</p>

<h3 id="forward-propagation">Forward Propagation</h3>
<p>Propagating the input signal through layers to get the output.</p>

\[\begin{align*}
    f_0 &amp;= x \\
    f_r &amp;= \sigma_r(\theta_{r-1} f_{r-1} + C_{r-1}), \quad r = 1, \ldots, L \\
    f_{L+1} &amp;= \theta_{L} f_L + C_L
\end{align*}\]

<h3 id="backward-propagation">Backward Propagation</h3>
<p><strong>Backpropagation</strong>: Adjusting the parameters based on the gradient of the error with respect to the network’s parameters. Chain Rule is involved.</p>

\[\frac{\partial \text{error}}{\partial \theta_i}\]

<h2 id="cnn-architecture">CNN Architecture</h2>
<p>Convolutional Neural Network consists of multiple layers like the input layer, Convolutional layer, Pooling layer, and fully connected layers.</p>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/6eea6464-6f42-49d5-9587-2092bbab40ab" alt="CNN Architecture" /></p>

<p>It’s particularly useful for finding patterns in images to recognize objects.</p>

<h3 id="kernel-stride-and-padding">Kernel, Stride, and Padding</h3>
<ul>
  <li>Kernel is used to extract features from images; it can be viewed as a parameter in the model.</li>
  <li>Stride controls the movement of the Kernel across the input image. If strides = 2, it will skip the next 2 pixels.</li>
  <li>Padding controls the addition of extra pixels around the borders of the input images or feature map. If padding = 2, it will add two column/row pixels around the borders.</li>
</ul>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/5539aec8-7fe1-4b70-a2c7-25c5fa6e6775" alt="Kernel, Stride, and Padding" /></p>

<h2 id="resnet">ResNet</h2>
<p>ResNet is the neural network architecture proposed by Kaiming He in the paper <a href="https://arxiv.org/abs/1512.03385">Deep Residual Learning for Image Recognition</a>. It is widely known for its outstanding performance in image recognition. One of the problems ResNets solves is the famous known vanishing gradient. This is because when the network is too deep, the gradients from where the loss function is calculated easily shrink to zero after several applications of the chain rule. This results in the weights never updating their values, and therefore, no learning is being performed.</p>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/c654b38f-fa26-4316-b11f-658c598c82fe" alt="ResNet Architecture" /></p>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Neural Network Overview Neural Network is inspired by biological phenomena in the human brain - how information is transferred as signals in the human brain. There are many types of Neural Networks that exist. The basic neural network architecture can be classified as Feed-forward Neural Network, CNN, RNN, and etc.]]></summary></entry><entry><title type="html">Decision Tree</title><link href="https://zhiweilin27.github.io/2023/10/23/Decision-Tree.html" rel="alternate" type="text/html" title="Decision Tree" /><published>2023-10-23T00:00:00+00:00</published><updated>2023-10-23T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2023/10/23/Decision-Tree</id><content type="html" xml:base="https://zhiweilin27.github.io/2023/10/23/Decision-Tree.html"><![CDATA[<h2 id="decision-tree-overview">Decision Tree Overview</h2>
<p>Decision trees are a type of supervised machine learning algorithm used for classification and regression tasks with a tree-like model. The basic structure of a tree
consists of the root node, decision node, and leaf node. The general procedure is that it starts at the root, splits based on the best attribute, and repeats until 
meeting stopping criteria (e.g., all instances in a leaf node belong to the same class).
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/b0cbb83a-e5e7-4296-95b8-49ade8546f0c" alt="Capture" /></p>

<p>There are various splitting criteria used by the regression tree and the classification tree</p>
<ul>
  <li>Gini impurity: a measure of variance across the K classes of the qualitative response. It is widely used in classification trees.<br />
\(Gini\ Index = \sum_{i} p_{i}(1-p_{i})\)<br />
For a two-class problem, the Gini impurity for a given node can be written as:<br />
\(Gini\ Impurity = p_{1}(1-p_{1}) + p_{2}(1-p_{2})\)</li>
  <li>Entropy: a measure similar to the Gini index.<br />
\(Entropy = -\sum_{i} p_{i} \ln(p_{i})\)<br />
For a two-class problem, the entropy for a given node can be written as:<br />
\(Entropy = -p \ln(p) - (1 - p) \ln(1 - p)\)</li>
  <li>Sum of Squared Error (SSE): Unlike the previous two metrics, SEE is widely used in a regression task.<br />
\(SSE = \sum_{i \in S_{1}} (y_{i} - \bar{y}_{1})^{2} + \sum_{i \in S_{2}} (y_{i} - \bar{y}_{2})^{2}\)</li>
</ul>

<p><strong>Procedure</strong></p>
<ol>
  <li>Encode categorical variables, and handle missing values.</li>
  <li>Build the Tree
    <ul>
      <li>use an appropriate metric to find the best splits, and split based on the attribute that results in the most significant reduction in heterogeneity.</li>
    </ul>
  </li>
  <li>Limit the tree depth to prevent overfitting.</li>
  <li>Use cross-validation to assess the model’s performance (optional).</li>
  <li>Use the trained model on test data</li>
</ol>

<h2 id="emsemble-models">Emsemble Models</h2>
<p>Ensemble models combine the results of multiple models to achieve a better result. The core idea is that the aggregation of multiple models can often outperform a single model. There are 
some advantages over individual trees such as improved accuracy, reduced overfitting, increased robustness, insights into feature importance, and flexibility. Random Forest and Gradient Boosting are popular examples of ensemble decision trees that are highly effective in various domains.</p>

<h3 id="bootstrap">Bootstrap</h3>
<ul>
  <li>Bootstrapping is a fundamental technique in ensemble modeling. It involves generating additional samples by repeatedly sampling from the existing observations with <strong>replacement</strong>, as new samples are available, the accuracy of statistical estimates (bias and variance) can be assessed.</li>
  <li>More specifically, each subset has the same size as the original dataset, and random sampling aids in estimating the mean and standard deviation by resampling from the dataset.</li>
</ul>

<h3 id="bagging">Bagging</h3>
<ul>
  <li>Bagging is based on the bootstrap. It combines the results of multiple models to obtain a more generalized and robust prediction. It creates subsets (bags) from the original dataset using random sampling with replacement, and each subset is used to train a base model or weak model independently. These models run in parallel and are independent of each other.</li>
  <li><strong>Random Forest</strong> is a variant of bagging that seeks to further improve the prediction accuracy of a tree-based model. While bagging involves averaging identically distributed and possibly correlated trees, random forests seek to make the bagged trees less correlated via an additional degree of randomization - every split is allowed to use only m predictors instead of the full set of p predictors.</li>
</ul>

<h3 id="boosting">Boosting</h3>
<ul>
  <li>Boosting uses a different approach to ensemble learning than bagging and random forest. Instead of making independent bootstrapped samples, fitting a decision tree to each bootstrapped sample separately, and averaging the predictions of these trees to reduce variance, boosting builds a sequence of inter-dependent tress, each fitted to the residuals of the preceding tree and a scaled-down version of the current tree’s prediction is subtracted from the preceding tree’s residual to from the new residual.</li>
  <li>Through this iterative process, boosting aims to convert a collection of weak learners into a stronger and more accurate model. The final model is a weighted combination of all the models.</li>
</ul>

<p>well-known boosting models:</p>

<ol>
  <li>
    <p><strong>Gradient Boosting Machines (GBM):</strong> A powerful boosting technique that builds trees sequentially, with each tree learning and correcting errors made by the previous one. GBM minimizes a loss function (e.g., sum squared error for regression, cross-entropy for classification) by using gradients.</p>
  </li>
  <li>
    <p><strong>XGBoost (Extreme Gradient Boosting):</strong> A highly efficient and scalable implementation of gradient boosting. It introduces several regularization techniques to prevent overfitting and improve performance.</p>
  </li>
  <li>
    <p><strong>LightGBM:</strong> Another high-performance gradient boosting framework developed by Microsoft. It’s known for its speed and memory efficiency, making it suitable for large datasets. LightGBM uses a novel technique called Gradient-based One-Side Sampling (GOSS) to handle large datasets more effectively.</p>
  </li>
  <li>
    <p><strong>CatBoost:</strong> Developed by Yandex, CatBoost is a gradient-boosting library that works well with categorical features without the need for one-hot encoding or preprocessing. It employs techniques like ordered boosting and oblivious trees to improve performance.</p>
  </li>
</ol>

<p><a href="https://arxiv.org/pdf/1603.02754.pdf">XGBoost</a>, <a href="https://proceedings.neurips.cc/paper_files/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf">LightGBM</a>, and <a href="https://arxiv.org/pdf/1706.09516.pdf">CatBoost</a> are very popular models, providing high accuracy.</p>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Decision Tree Overview Decision trees are a type of supervised machine learning algorithm used for classification and regression tasks with a tree-like model. The basic structure of a tree consists of the root node, decision node, and leaf node. The general procedure is that it starts at the root, splits based on the best attribute, and repeats until meeting stopping criteria (e.g., all instances in a leaf node belong to the same class).]]></summary></entry><entry><title type="html">Generalized Linear Regression And Svm</title><link href="https://zhiweilin27.github.io/2023/10/22/Generalized-Linear-Regression-and-SVM.html" rel="alternate" type="text/html" title="Generalized Linear Regression And Svm" /><published>2023-10-22T00:00:00+00:00</published><updated>2023-10-22T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2023/10/22/Generalized-Linear-Regression-and-SVM</id><content type="html" xml:base="https://zhiweilin27.github.io/2023/10/22/Generalized-Linear-Regression-and-SVM.html"><![CDATA[<h2 id="generalized-linear-regression">Generalized Linear Regression</h2>

<p>Generalized linear regression is an extension of ordinary linear regression. The response variable can be categorical, and the distribution of residuals can be non-normal. Here’s a summary:</p>

<ul>
  <li>Response variable in GLR is no longer confined to the class of normal distribution; it only needs to be a member of the linear exponential family of distributions.</li>
  <li>GLR uses a link function where the response mean is linearly related to the predictors.</li>
</ul>

<h3 id="linear-exponential-family-of-distribution">Linear Exponential Family of Distribution</h3>

<p>Mathematically, a distribution is a member of the linear exponential family of distributions if its probability function can be expressed as:</p>

\[f(y;\theta,\phi) = \exp\left(\frac{y\theta - b(\theta)}{\phi} + S(y,\phi)\right)\]

<p>where:</p>
<ul>
  <li>\(y\) is the argument of the probability function.</li>
  <li>\(\theta\) is the parameter of interest.</li>
  <li>\(\phi\) is the scale parameter.</li>
  <li>\(b(\theta)\) and \(S(y,\phi)\) are functions of \(\theta\) and \(\phi\), respectively.</li>
</ul>

<p>For further details, check this <a href="https://en.wikipedia.org/wiki/Exponential_family">website</a>.</p>

<h3 id="link-functions">Link Functions</h3>

<p>Link functions connect the response distribution’s mean to the predictors. It’s a monotonic function that links the mean of the response to a linear combination of predictors:</p>

\[g(\mu) = X\beta\]

<p>where \(g(\cdot)\) is the link function, \(\mu\) is the response mean, \(X\) is the matrix of predictors, and \(w\) is the coefficients.</p>

<p>The monotonicity property allows us to invert the link function and estimate the response mean \(\mu\) as soon as the parameter vector \(\beta\) has been estimated from the data:</p>

\[\mu = g^{-1}(\eta) = g^{-1}(\beta_0 + \beta_1 x_1 + \cdots + \beta_p x_p)\]

<h3 id="canonical-link-function">Canonical Link Function</h3>

<p>There are many possible link functions connecting response distribution’s mean to the linear predictor. One comman choice of the link function is the canonical link, which sets the sysmatic component \(\eta\) of the model equal to the paramter \(\theta\).</p>

<p>\(g(\mu) = \eta = \theta\)
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/13046288-8f30-4c03-90e3-3a7ff9626ab6" alt="IMG_2306" /></p>

<h2 id="logistic-regression">Logistic Regression</h2>

<p>Logistic regression is one of the most famous generalized linear regression techniques.</p>

<ul>
  <li>For the classification of two classes (e.g., \(t=1\) or \(t=0\)), the link function used is the logistic function (sigmoid curve) defined as \(f(z) = \frac{1}{1+e^{-z}}\).</li>
  <li>For multiclass classification, there’s an extension called the softmax function defined as:</li>
</ul>

\[f(z)_i = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}} \quad \text{for } i = 1, \ldots, K\]

<p>Let’s derive the optimal weights that minimize least squares errors.</p>

<p>First, the logistic regression model is represented as:</p>

\[P(y|x) =
  \begin{cases} 
    h(x) &amp; \text{for } y = +1 \\
    1 - h(x) &amp; \text{for } y = -1
  \end{cases}\]

<p>where \(h(x) = \Theta(w^Tx)\) and \(\Theta\) is the logistic function defined as \(\Theta(s) = \frac{e^{s}}{1+e^{s}}\).</p>

<p>Thus,</p>

\[P(y|x) = \Theta(yw^Tx)\]

<p>One reason for choosing the mathematical form \(\Theta(s) = \frac{e^s}{1+e^s}\) 
is that it leads to this simple expression for \(P(y|x)\)</p>

<p>The likelihood for a sample of size \(N\) is given by:</p>

\[L(\beta;\textbf{y},\textbf{X}) = \prod_{n=1}^{N} P(y_n|x_n)\]

<p>Maximizing the likelihood:</p>

\[\begin{align*}
&amp;\text{Maximize } \prod_{n=1}^{N} P(y_n | x_n) \\
&amp;\Leftrightarrow \ln\left(\prod_{n=1}^{N} P(y_n | x_n)\right) \quad \text{(This is log-likelihood)} \\
&amp;\equiv \max \sum_{n=1}^{N} \ln P(y_n | x_n) \\
&amp;\Leftrightarrow \min -\frac{1}{N} \sum_{n=1}^{N} \ln P(y_n | x_n) \\
&amp;\equiv \frac{1}{N} \sum_{n=1}^{N} \ln\left(\frac{1}{P(y_n | x_n)}\right) \\
&amp;\equiv \frac{1}{N} \sum_{n=1}^{N} \ln\left(\frac{1}{\Theta(y_n w^T x_n)}\right) \\
&amp;\equiv \frac{1}{N} \sum_{n=1}^{N} \ln(1 + e^{-y_n w^T x_n})
\end{align*}\]

\[E(w) = \frac{1}{N} \sum_{n=1}^{N} \ln(1 + e^{-y_n w^T x_n})\]

<p>The first-order derivative of the logistic regression objective function \(E(w)\) with respect to the weight vector \(w\) is derived as follows:</p>

\[\begin{align*}
\nabla E(w) &amp;= \nabla\left(\frac{1}{N}\sum_{n=1}^{N}\ln(1+e^{-y_nw^Tx_n})\right) \\
&amp;= \frac{1}{N}\sum_{n=1}^{N}\frac{-y_nx_ne^{-y_nw^Tx_n}}{1+e^{-y_nw^Tx_n}} \\
&amp;= \frac{1}{N}\sum_{n=1}^{N}\frac{-y_nx_ne^{-y_nw^Tx_n}}{1+e^{-y_nw^Tx_n}}\cdot\frac{1+e^{y_nw^Tx_n}}{1+e^{y_nw^Tx_n}} \\
&amp;= \frac{-1}{N}\sum_{n=1}^{N}\frac{y_nx_n(e^{-y_nw^Tx_n}+1)}{(1+e^{-y_nw^Tx_n})(1+e^{y_nw^Tx_n})} \\
&amp;= \frac{-1}{N}\sum_{n=1}^{N}\frac{y_nx_n}{1+e^{y_nw^Tx_n}}
\end{align*}\]

<p>This concludes the derivation.</p>

<h3 id="decision-boundary">Decision Boundary</h3>
<p>The logistic function is used to map the output of a linear combination of features (i.e., the weighted sum of input features plus a bias term) to a probability value between 0 and 1. And since the logistic function(sigmoid function) is a monotonically increasing function - when x increases, y increases, the decision boundary remains linear as in linear regression.</p>

<p>Proof of Decision Boundary for one-variable when p(y=1|x) = p(y=0|x):<br />
\(\frac{1}{1 + e^{-(\beta_0 + \beta_1 x)}} = \frac{1}{2}\)<br />
\(2 = 1 + e^{-(\beta_0 + \beta_1 x)}\)<br />
\(1 = e^{-(\beta_0 + \beta_1 x)}\)<br />
\(\ln(1) = -(\beta_0 + \beta_1 x)\)<br />
\(0 = -(\beta_0 + \beta_1 x)\)<br />
\(0 = \beta_0 + \beta_1 x\)<br />
\(x = -\frac{\beta_0}{\beta_1}\)</p>

<p>This can be extended to multi-variables.</p>

<p>The plot below is an example of a decision boundary for logistic regression:<br />
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/ec282923-e57a-47ab-b4e2-b2419c421a51" alt="decision-boundary" /></p>

<h2 id="support-vector-machine">Support Vector Machine</h2>
<p>Different from Generalized Linear regression, SVM is to find a plane that has the maximum margin, i.e. the maximum distance between data points of both classes. This might yield better accuracy as we also maximize the margin distance, which provides some reinforcement. Hence, future data points can be classified with more confidence(higher accuracy).</p>

<p><img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/261f95b1-3d93-426f-8908-81c7152e94c0" alt="Capture" /></p>

<p><strong>Hinge Loss:</strong> is the loss function used in Support Vector Machines (SVM). The objective is to find the values of \(w\) and \(b\) that minimize:<br />
\(\min_{w, b} \frac{1}{2}||w||^2 + C \sum_{i=1}^{n} \xi_i\)<br />
Subject to the constraints:<br />
\(y_i(w \cdot x_i + b) \geq 1 - \xi_i, \quad \forall i = 1, \ldots, n\)<br />
\(\xi_i \geq 0, \quad \forall i = 1, \ldots, n\)</p>

<p>Kernel Tricks: The kernel function computes the inner product between two vectors</p>
<ul>
  <li>
    <p><strong>Linear Kernel:</strong> The simplest form, where the kernel is just the dot product of two vectors. It is used when the data is linearly separable.<br />
\(K(x, x') = x \cdot x'\)</p>
  </li>
  <li>
    <p><strong>Polynomial Kernel:</strong> Allows learning of non-linear models by mapping inputs into polynomial feature space.<br />
\(K(x, x') = (\gamma x \cdot x' + r)^d\)</p>
  </li>
  <li>
    <p><strong>Radial Basis Function (RBF) or Gaussian Kernel:</strong> One of the most common kernels. It can map the inputs into an infinite-dimensional space, providing great flexibility in fitting the data.<br />
\(K(x, x') = \exp(-\gamma \|x - x'\|^2)\)</p>
  </li>
</ul>

<h3 id="decision-boundary-1">Decision Boundary</h3>
<p>The decision boundary of an SVM is determined by the choice of the kernel:</p>
<ul>
  <li>Linear Kernel: The decision boundary is linear.</li>
  <li>Non-linear Kernels (Polynomial and RBF): The decision boundary is non-linear</li>
</ul>

<p>An example of an RBF decision boundary is:
<img src="https://github.com/zhiweilin27/zhiweilin27.github.io/assets/111717798/99f9e3bf-ab9a-4cc4-bd23-3b5b2aa8a88f" alt="Capture" /></p>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Generalized Linear Regression]]></summary></entry><entry><title type="html">Multicollinearity Step Wise Regression Shrinkage Methods Notes</title><link href="https://zhiweilin27.github.io/2023/10/21/Multicollinearity-Step-wise-Regression-Shrinkage-Methods-Notes.html" rel="alternate" type="text/html" title="Multicollinearity Step Wise Regression Shrinkage Methods Notes" /><published>2023-10-21T00:00:00+00:00</published><updated>2023-10-21T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2023/10/21/Multicollinearity-Step-wise-Regression-Shrinkage-Methods-Notes</id><content type="html" xml:base="https://zhiweilin27.github.io/2023/10/21/Multicollinearity-Step-wise-Regression-Shrinkage-Methods-Notes.html"><![CDATA[<h2 id="multicollinearity">Multicollinearity</h2>

<p>Multicollinearity occurs when two or more predictors in a regression model are moderately or highly correlated with each other. In the least squares estimation,</p>

\[w = (X^TX)^{-1}X^T y\]

<p>Thus, when collinearity is present, coefficient estimates (\(w\)) for the correlated variables become unstable (X is not invertible).</p>

<p>Several methods address the multicollinearity problem:</p>

<ul>
  <li>Step-wise regression (variable selection using adjusted \(R^2\), AIC, BIC, or Mallow’s \(C_p\)).</li>
  <li>Shrinkage methods (Ridge, Lasso, or Elastic Net).</li>
</ul>

<h2 id="step-wise-regression-variable-selection">Step-Wise Regression (Variable Selection)</h2>

<p>Stepwise regression selects a subset of predictor variables based on statistical criteria such as adjusted \(R^2\), AIC, BIC, or Mallow’s \(C_p\).</p>

<h3 id="adjusted-r2">Adjusted \(R^2\)</h3>

<p>The coefficient of determination \(R^2\) is defined as \(R^2 = 1- \frac{RSS}{TSS}\). However, as more predictors are added, \(R^2\) always increases. To address this, statisticians developed adjusted \(R^2\), which rescales \(R^2\) to account for the number of predictors.<br />
Adjusted \(R^2\) formula:  \(R^2_{\alpha} = 1- \frac{\frac{RSS}{n-p-1}}{\frac{TSS}{n-1}}\) <br />
As can be seen, adjusted \(R^2\) rescales the ordinary \(R^2\) by dividing RSS and TSS by their respective degrees of freedom in the ANOVA table. The goal of it is that the value would not always increase as more predictor variables are added in. It’s sort of acting like a penalty for adding more variables.</p>

<h3 id="aic-bic-and-mallows-c_p">AIC, BIC, and Mallow’s \(C_p\)</h3>

<p>These model comparison statistics penalize complex models to favor simplicity, following the parsimony principle.</p>

\[\begin{align*}
\text{Mallow's } C_p &amp; : \frac{RSS+2ps_{\text{full}}^2}{n} \\
\text{AIC} &amp; : 2p-2ln(L) \\
\text{BIC} &amp; : ln(n)p-2ln(L)
\end{align*}\]

<p>Here, \(p\) is the number of predictors, \(s_{\text{full}}^2\) is the mean squared error of the full model, \(L\) maximum value of the likelihood function for the model.</p>

<h2 id="shrinkage-methods">Shrinkage Methods</h2>

<p>Shrinkage methods regulate or shrink coefficient estimates towards zero.</p>

<h3 id="ridge-regression">Ridge Regression</h3>

<p>In Ridge regression, the objective function is:</p>

\[E(w) = \sum(y_i - (w_0 + w_1x_{i1} + \ldots + w_p x_{ip}))^2 + \lambda \sum (w_j^2),\]

<p>where \(\lambda \geq 0\) is called the tuning parameter. The \(\lambda\) value is a hyperparameter that needs to be tuned (using cross-validation) to obtain the value of \(\lambda\) such that the error (RSS) is minimized.</p>

<p>Derive optimal w using matrix annotation: 
\(E(w) = ||xw-y||^2+\lambda ||w||^2\)</p>

\[\nabla E(w) = 2x^Txw - 2x^Ty+ 2 \lambda w =0\]

\[\Rightarrow 2x^Txw + 2\lambda w = 2x^T y\]

\[w = \frac{x^Ty}{x^Tx+\lambda I}\]

\[\Rightarrow w = (x^Tx + \lambda I)^{-1}(x^Ty)\]

<h3 id="lasso-regression">Lasso Regression</h3>

<p>In Lasso regression, the objective function is similar to Ridge, but the penalty term involves the absolute value of the coefficients:</p>

\[E(w) = \sum(y_i - (w_0 + w_1x_{i1} + \ldots + w_p x_{ip}))^2 + \lambda \sum (|w_j|).\]

<p>In contrast to Ridge regression, the Lasso has the remarkable effect of shrinking the coefficient estimates to be exactly zeros. Therefore, Lasso can also be used for variable selection.</p>

<h3 id="elastic-net">Elastic Net</h3>
<p>Elastic Net combines the penalties of both Lasso and Ridge regression techniques:</p>

\[E(w) = \sum(y_i - (w_0 + w_1x_{i1} + \ldots + w_p x_{ip}))^2 + \lambda_1 \sum (w_j^2) + \lambda_2 \sum (|w_j|).\]

<p>Overall, these methods provide effective ways to handle multicollinearity in regression models.</p>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Multicollinearity]]></summary></entry><entry><title type="html">Linear Regression Notes</title><link href="https://zhiweilin27.github.io/2023/10/20/Linear-Regression-Notes.html" rel="alternate" type="text/html" title="Linear Regression Notes" /><published>2023-10-20T00:00:00+00:00</published><updated>2023-10-20T00:00:00+00:00</updated><id>https://zhiweilin27.github.io/2023/10/20/Linear-Regression-Notes</id><content type="html" xml:base="https://zhiweilin27.github.io/2023/10/20/Linear-Regression-Notes.html"><![CDATA[<h1 id="linear-regression-overview">Linear Regression Overview</h1>
<p>Linear regression is a statistical method used to model the linear relationship between a dependent variable y and one or more independent variables \(x_{1}, x_{2}, \ldots, x_{p}\). It is simple, yet it remains one of the most useful analytical tools. While it may not always yield the highest accuracy, the model simplicity and interpibility are very good.</p>

<p>The linear regression model takes the form:</p>

\[y = \beta_{0} + \beta_{1} x_{1} + \beta_{2} x_{2} + \cdots + \beta_{p} x_{p} + \varepsilon\]

<p>where:</p>

<ul>
  <li>y is the dependent variable</li>
  <li>\(x_1, x_2, \ldots, x_p\) are the independent variables</li>
  <li>\(\beta_0, \beta_1, \ldots, \beta_p\) are the coefficients (parameters) of the model</li>
  <li>\(\varepsilon\) is the error term, which represents the difference between the observed and predicted values of y.</li>
</ul>

<p>Often these \(n\) equations are stacked together and written in matrix notation as:</p>

\[\mathbf{y} = \mathbf{X} \mathbf{\beta} + \mathbf{\varepsilon}\]

<p>where:</p>

\[\mathbf{y} = \begin{pmatrix} y_1 \\ y_2 \\ \vdots \\ y_n \end{pmatrix}, \quad 
\mathbf{X} = \begin{pmatrix} 
    \mathbf{x}_1^\mathsf{T} \\ 
    \mathbf{x}_2^\mathsf{T} \\ 
    \vdots \\ 
    \mathbf{x}_n^\mathsf{T} 
\end{pmatrix} = \begin{pmatrix} 
    1 &amp; x_{11} &amp; \cdots &amp; x_{1p} \\ 
    1 &amp; x_{21} &amp; \cdots &amp; x_{2p} \\ 
    \vdots &amp; \vdots &amp; \ddots &amp; \vdots \\ 
    1 &amp; x_{n1} &amp; \cdots &amp; x_{np} 
\end{pmatrix}\]

\[\mathbf{\beta} = \begin{pmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \vdots \\ \beta_p \end{pmatrix}, \quad 
\mathbf{\varepsilon} = \begin{pmatrix} \varepsilon_1 \\ \varepsilon_2 \\ \vdots \\ \varepsilon_n \end{pmatrix}\]

<h2 id="least-square-estimation">Least Square Estimation</h2>

<p>Least square error tries to minimize the sum of square residuals: \(\varepsilon = \sum(y-\hat{y})^2\).</p>

<p>To minimize this \(\varepsilon\):</p>

\[\begin{align*}
E &amp;= \sum(\hat{y} - y)^2 \\
&amp;= \lVert \hat{y} - y \rVert_2^2 \\
&amp;= \lVert Xw - y \rVert_2^2 \\
&amp;= (Xw-y)^T(Xw-y) \\
&amp;= ((Xw)^T - y^T)(Xw - y) \\
&amp;= (w^TX^TXw^T - 2w^TX^Ty + y^Ty)
\end{align*}\]

\[\nabla E = 2(X^TXw - X^T y) = 0\]

\[\Rightarrow X^TXw = X^Ty\]

\[\Rightarrow w_{optimal} = (X^TX)^{-1}X^T y\]

<p>where \(X^TX\) is invertible.</p>

<p>It’s known that \(x_{1}, x_{2}, \ldots, x_{p}\) need to be independent of each other for the matrix \(X\) to be invertible. In practice, we often assume that variables are independent from each other, even if they exhibit small correlations. However, if variables are strongly correlated (dependent), they shouldn’t be included in the linear model, as they will lead to incorrect results.</p>

<p>There are several methods to handle multiple dependent variables in regression models:</p>

<ul>
  <li>Variable selection based on criteria such as Bayesian Information Criterion (BIC) or Akaike Information Criterion (AIC).</li>
  <li>Regularization techniques such as Ridge regression, Lasso regression, and Elastic Net regression, which penalize the inclusion of multiple correlated variables in the model.</li>
</ul>

<p>These methods help address the issue of multicollinearity and improve the accuracy and reliability of the regression model.</p>

<h3 id="derivation-of-the-coefficients">Derivation of the Coefficients</h3>

<p>Let’s simplify the derivation for a regression with only one predictor:</p>

\[\hat{y} = a + bx\]

<p>Then, the error function E  can be expressed as:</p>

\[E = \sum_{i=1}^{n}(y_i - \hat{y_i})^2 = \sum_{i=1}^{n}(y_i - a - bx_i)^2\]

<p>To minimize the value of E:</p>

<p>take derivative respect to a</p>

\[\begin{align*}
0 &amp;= \frac{\partial E}{\partial a} \\
0 &amp;= -2 \sum_{i=1}^{n}(y_i - a - bx_i) \\
0 &amp;= \sum_{i=1}^{n}(y_i - a - bx_i) \\
0 &amp;= \sum_{i=1}^{n} y_i - \sum_{i=1}^{n} a - b \sum_{i=1}^{n} x_i \\
n(a) &amp;= \sum_{i=1}^{n} y_i - b \sum_{i=1}^{n} x_i \\
a &amp;= \bar{y} - b\bar{x}
\end{align*}\]

<p>we find optimal \(a = \bar{y} - b\bar{x}\)</p>

<p>then take derivative respect to b</p>

\[\begin{align*}
0 &amp;= \frac{\partial E}{\partial b} \\
0 &amp;= -2 \sum_{i=1}^{n} (x_i)(y_i - a - bx_i) \\
0 &amp;= \sum_{i=1}^{n} (x_i y_i - x_i \bar{y} + b x_i \bar{x} - b x_i^2) \\
b \sum_{i=1}^{n} (x_i^2 - x_i \bar{x}) &amp;= \sum_{i=1}^{n} (x_i y_i - x_i \bar{y}) \\
b &amp;= \frac{\sum_{i=1}^{n} (x_i y_i - x_i \bar{y})}{\sum_{i=1}^{n} (x_i^2 - x_i \bar{x})}
\end{align*}\]

<p>Alternatively:</p>

\[\begin{align*}
b &amp; = \frac{\sum_{i=1}^{n} x_{i} y_{i} - n \bar{x} \bar{y}}{\sum_{i=1}^{n} x_{i}^{2} - n \bar{x}^{2}} \\
&amp; = \frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})}{\sum_{i=1}^{n}(x_i-\bar{x})^2}
\end{align*}\]

<h3 id="the-coefficient-of-determination-r2">The Coefficient of Determination R^2</h3>

<ul>
  <li>SSE (Error/Residual Sum of Squares): \(\sum_{i=1}^{n} (y_i - \hat{y_i})^2\), the value we are trying to minimize.</li>
  <li>SSR (Regression Sum of Squares): \(\sum_{i=1}^{n} ({\hat{y_i}} - \bar{y})^2\), the value we are trying to maximize.</li>
  <li>SST (Total Sum of Squares): \(\sum_{i=1}^{n} (\hat{y_i} - \bar{y})^2\)</li>
</ul>

<p>loosely speaking, \(R^2\) is how many precentage of variance being captured by the model. Therefore, \(R^2 = \frac{SSR}{SST} or 1-\frac{SSE}{SST}\)</p>

<h2 id="maximum-likilihood-estimation">Maximum Likilihood Estimation</h2>
<p>\(\begin{align*}
f(y_i | x_i, \beta_0, \beta_1, \ldots, \beta_p) &amp;= \\
&amp;\frac{1}{\sqrt{2 \pi \sigma^2}} \exp\left(-\frac{(y_i - (\beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \cdots + \beta_p x_{ip}))^2}{2\sigma^2}\right)
\end{align*}\)</p>

<p>The likelihood function for the entire dataset \(\{(x_i, y_i)\}_{i=1}^n\) is the product of the likelihoods of individual observations:</p>

\[L(\beta_0, \beta_1, \ldots, \beta_p) = \prod_{i=1}^n f(y_i | x_i, \beta_0, \beta_1, \ldots, \beta_p)\]

\[\ell(\beta_0, \beta_1, \ldots, \beta_p) = \log L(\beta_0, \beta_1, \ldots, \beta_p)\]

\[\frac{\partial \ell}{\partial \beta_j} = 0, \quad \text{for } j = 0, 1, \ldots, p\]

<p>Solving this system of equations gives us the maximum likelihood estimates \(\hat{\beta}_0, \hat{\beta}_1, \ldots, \hat{\beta}_p\).</p>

<p>This approach provides estimates that maximize the likelihood of observing the given data under the assumed linear regression model. When \(f_θ\) is a normal distribution with zero mean and variance θ, the resulting estimate is identical to the least square estimation.</p>

<h2 id="other-estimation-technique-quantile-regression">Other Estimation Technique (Quantile Regression)</h2>
<p>Other estimation techniques like quantile regression are also very useful. It focuses on the conditional quantiles of y given X rather than the conditional mean of y given X. Least square estimation is highly affected by outliers, but quantile regression is more robust to outliers. Quantile regression is very useful in some real-world data with outliers.</p>

<p><a href="https://pubs.aeaweb.org/doi/pdfplus/10.1257/jep.15.4.143" target="_blank">Roger Koenker Quantile Regression paper</a></p>

<h2 id="convexity">Convexity</h2>
<p>A good error function is required to be convex, which has only one minimum point. This property simplifies the optimization process, as there is no risk of getting stuck in a suboptimal solution. Mathematicians/Statisticians put much effort into designing a convex error function. 
In addition, the least square error is the quadratic objective function, while the quantile error function is the linear objective function. In terms of efficiency, linear objective function like quantile regression runs much faster than least-squared regression in large datasets.</p>]]></content><author><name>Zhiwei Lin</name></author><summary type="html"><![CDATA[Linear Regression Overview Linear regression is a statistical method used to model the linear relationship between a dependent variable y and one or more independent variables \(x_{1}, x_{2}, \ldots, x_{p}\). It is simple, yet it remains one of the most useful analytical tools. While it may not always yield the highest accuracy, the model simplicity and interpibility are very good.]]></summary></entry></feed>