<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Krishna Chaitanya on Medium]]></title>
        <description><![CDATA[Stories by Krishna Chaitanya on Medium]]></description>
        <link>https://medium.com/@krsna540?source=rss-ebb387495358------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fCERRUOW0GHESoqGjXy62g.jpeg</url>
            <title>Stories by Krishna Chaitanya on Medium</title>
            <link>https://medium.com/@krsna540?source=rss-ebb387495358------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:20:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krsna540/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Open Source LLMs: A Comprehensive Study]]></title>
            <link>https://krsna540.medium.com/open-source-llms-a-comprehensive-study-af09736e833d?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/af09736e833d</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 14:21:25 GMT</pubDate>
            <atom:updated>2023-11-17T14:21:25.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BD7x06lLR-pZLlOb" /><figcaption>Photo by <a href="https://unsplash.com/@jupp?utm_source=medium&amp;utm_medium=referral">Jonathan Kemper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Large Language Models:</h3><p>Large language models (LLMs) are recent advances in deep learning models. Large language models (LLMs) are deep learning algorithms that can recognize, summarize, translate, predict, and generate content using very large datasets. LLMs are trained on a massive collection of articles, Wikipedia entries, books, internet-based resources and other input sources (downstream users, crowd workers) to produce human-like responses to natural language queries and using unsupervised learning. With unsupervised learning, models can find previously unknown patterns in data using unlabeled datasets. This also eliminates the need for extensive data labeling. Due to the extensive training process that LLMs undergo, the models don’t need to be trained for any specific task and can instead serve multiple use cases. These types of models are known as <strong>foundation models</strong>.</p><p>There are several classes of large language models that are suited for different types of use cases:</p><ul><li><strong>Encoder only</strong>: These models are typically suited for tasks that can understand language, such as classification and sentiment analysis. Example — BERT (Bidirectional Encoder Representations from Transformers).</li><li><strong>Decoder only</strong>: This class of models is extremely good at generating language and content. Some use cases include story writing and blog generation. Example — GPT-3 (Generative Pretrained Transformer 3).</li><li><strong>Encoder-decoder:</strong> These models combine the encoder and decoder components of the transformer architecture to both understand and generate content. Some use cases where this architecture shines include translation and summarization. Example- T5 (Text-to-Text Transformer).</li></ul><h3>1. LLMs in Enterprise:</h3><p>There are 3 approaches in which any enterprise can use LLMs:</p><h3>1.1 Commercial LLM API</h3><p><strong>Pros</strong></p><ul><li>Requires the least LLM training technical skills, minimum training / exploration costs</li><li>Least data-demanding — a few or no examples are needed for models to perform inference</li><li>Reduce time-to-market of the apps and de-risk the project with a working LLM model</li></ul><p><strong>Cons</strong></p><ul><li>Commercial services can get expensive with a high volume of inference tasks</li><li>Many industries or use cases forbid the usage as sensitive or PII data for compliance</li><li>Less flexible downstream, doesn’t support edge inference, limited ability to customize the model, limited ability for ongoing model improvements</li></ul><p><strong>Usage considerations</strong></p><ul><li>For less technical teams but want to leverage LLM techniques to build apps, or for leveraging the best-in-class LLMs for performance</li><li>For very limited training datasets and want to leverage an LLM’s capabilities</li><li>Good for prototyping apps and exploring what is possible with LLMs</li></ul><h3>1.2 Open Source LLMs</h3><p><strong>Pros</strong></p><ul><li>A good way to leverage what LLMs have learned from a vast amount of internet data and build on top of it without paying for the IP at inference</li><li>Less dependent on the future direction of LLM service providers and have more control regarding roadmap &amp; backwards compatibility.</li></ul><p><strong>Cons</strong></p><ul><li>Requires lots of domain expert skills to train, fine-tune, and host an open-sourced LLM</li><li>Slower time-to-market and less agile</li><li>Open-sourced models lag in performance compared to commercial models</li></ul><p><strong>Usage considerations</strong></p><ul><li>A good pre-trained LLM has already seen a vast amount of data and thus has learned general capabilities from the data. This learning capabilities can be leveraged if training dataset is not huge or diverse</li><li>Operate in a regulatory environment or have user / sensitive data that cannot be fed to commercial LLM services.</li></ul><h3>1.3 Pre-train LLM by own</h3><p><strong>Pros</strong></p><ul><li>Gain full control of training datasets used for the pre-training, which directly impacts model quality, bias, and toxicity issues.</li><li>A lot of flexibility to innovate on techniques for performance and customization for downstream tasks.</li></ul><p><strong>Cons</strong></p><ul><li>Very expensive endeavor with high risks. Need cross-domain knowledge spanning from NLP/ML, subject matter, software and hardware expertise. If not done well, LLM will end up as a suboptimal model, even after spending millions of dollars</li><li>Starting from scratch and need lots of high-quality / diverse datasets for models to gain generalized capabilities.</li></ul><p><strong>Usage Considerations</strong></p><ul><li>Need to change model architecture or training dataset from existing pre-trained LLMs.</li><li>Have a large investment appetite to train and maintain expensive models on an ongoing basis.</li></ul><p>Based on above considerations if the business use case involves any sensitive or PII data and limited budget for LLM, using an existing open-sourced LLM is the best choice.</p><h3>2. Fine tuning Open Source LLMs</h3><p>Fine-tuning involves updating the weights of a pre-trained language model on a new task and dataset. The key distinction between training and fine-tuning is that training starts from scratch with a randomly initialized model dedicated to a particular task and dataset. On the other hand, fine-tuning adds to a pre-trained model and modifies its weights to achieve better performance. Fine-tuning empowers the model to comprehend and generate text in alignment with a specific field’s expert knowledge, thereby enhancing the quality of outputs significantly.</p><p>The entire pre-trained model is usually trained in fine-tuning, including all its layers and parameters. This process can be computationally expensive and time-consuming, especially for large models. Parameter-Efficient Fine-tuning (PEFT) approaches are meant to address the fine-tuning problems.</p><h3>2.1 Parameter-Efficient Fine-tuning (PEFT) methods</h3><p>PEFT approaches only fine-tune a small number of (extra) model parameters while freezing most parameters of the pretrained LLMs, thereby greatly decreasing the computational and storage costs. PEFT approaches have also shown to be better than fine-tuning in the low-data regimes and generalize better to out-of-domain scenarios.</p><p>It also helps in portability wherein users can tune models using PEFT methods to get tiny checkpoints worth a few MBs compared to the large checkpoints of full fine-tuning. The small, trained weights from PEFT approaches are added on top of the pretrained LLM. The same LLM can be used for multiple tasks by adding small weights without having to replace the entire model. Few PEFT methods:</p><h3>2.1.1 Prompt Tuning</h3><p>Prompt tuning is a simple yet effective mechanism for learning “soft prompts” to condition frozen language models to perform specific downstream tasks. Prompt Tuning is different from Prompt engineering, whereas in prompt engineering hard crafted prompts are fed to LLM to perform a task and generate response.</p><p>In Prompt tuning, front-end prompts will be fed to LLM to give task specific context. The prompts can be extra words introduced by a human or mostly AI generated number introduced into model’s embedding layer to guide the model towards a desired prediction. AI generated prompts are known as “Soft Prompts”. Each prompt consists of an embedding or string of numbers that distill knowledge from lager models. High-level or task specific prompts can act as a substitute towards additional training data during fine tuning. These soft prompts are incredibly effective in guiding the LLM towards desired output. These soft prompts lack interpretability.</p><h3>2.1.2 LoRA (LOW-RANK ADAPTATION)</h3><p>Low-Rank Adaptation, or LoRA, which freezes the pre-trained model weights and injects trainable rank decomposition matrices into each layer of the Transformer architecture, greatly reducing the number of trainable parameters for downstream tasks. LoRA can decompose the new weight matrix for the adapted task into lower-dimensional (smaller) matrices without losing too much important information.</p><p>In Regular finetuning, a neural network contains many dense layers which perform matrix multiplication. The weight matrices in these layers have full rank. Suppose W represents the weight matrix in a given neural network layer. Then, using regular backpropagation, we can obtain the weight update ΔW, which is typically calculated as a negative gradient of the loss times the learning rate:</p><p><strong>ΔW = α (-∇ LW)</strong></p><p>Then, when we have ΔW, we can update the original weights as follows:</p><p><strong>W ‘= W + ΔW</strong></p><p>compute the outputs</p><p><strong>h = W‘x= W x + ΔW x</strong></p><p>where x represents the inputs. when we train fully connected (i.e., “dense”) layers in a neural network, the weight matrices usually have full rank.</p><p>LoRA suggests that pretrained model will have a low intrinsic dimension when they are adapted to a new task. A low intrinsic dimension means the data can be effectively represented or approximated by a lower-dimensional space while retaining most of its essential information or structure. ΔW is the weight update for an A × B weight matrix. Then, we can decompose the weight update matrix into two smaller matrices: ΔW = WA WB, where WA is an A × r-dimensional matrix, and WB is an r × B-dimensional matrix. Here, we keep the original weight W frozen and only train the new matrices WA and WB. r is the hyperparameter.</p><p><strong>h = W0x + ∆W x = W0x + BAx</strong></p><p><strong>Example</strong>: In ∆W (A × B) if A=100 and B=100 then number of elements in ∆W is 10000.</p><p>Now consider r as 2, then WA (A × r) will have 200 elements and WB (r × B) will have 200 elements, total we have 400 elements for updating which is very less when compared to original elements which is 10000.</p><p>A full 7B Llama checkpoint requires 23 GB of storage capacity, while the LoRA weights can be as small as 8 MB if we choose a rank of <em>r=8</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Io4na5DzyIybuAAi.png" /></figure><h3>2.1.3 QLoRA (Quantized and Low -Rank Adapters)</h3><p>Even after applying LoRA, it is still difficult to train LLM on consumer hardware. LoRA is powerful but it still needs very large dataset to perform well, and it takes more samples for stable behavior. QLORA reduces the average memory requirements of finetuning a 65B parameter model from &gt;780GB of GPU memory to &lt;48GB without degrading the runtime or predictive performance compared to a 16-bit fully finetuned baseline.</p><p>QLoRA backpropagates gradients through a frozen 4-bit quantized pretrained language model into Low Rank Adapters (LoRA). 4-bit integer quantization of original 32-bit weights and apply Parameter Efficient Fine Tuning (PEFT), inject LoRA adapters into each layer, in 32-bit precision and start to fine tune the compute language model on a specific task for the quantized configuration to reduce quantization error of the system. Perform additionally a mixed precision training to balance the trade-off between accuracy and speed/memory usage.</p><p>Computation refers to mathematical operations that are performed on the weights and activations of the network during both forward pass (making predictions) and backward pass (when updating the weights during training). In a typical neural network these computations are performed using 32-bit floating point numbers. This is because 32-bit floating point numbers provide a good balance between precision and range. Using 32-bit floating point numbers for all computations can be memory intensive.</p><p>Quantization is a technique to reduce the precision of the numbers used in the model. In case of 4 bit-quantization, weights and activations of the network are compressed from 32-bit floating point numbers to 4-bit integers. 4-bit integers can range from -8 to 7.</p><p><strong>4-bit Normal Float Quantization</strong></p><ul><li>Normalization: The weights of the model are first normalized to have zero mean and unit variance. This ensures that the weights are distributed around zero and fall within a certain range.</li><li>Quantization: The normal weights are then quantized to 4 bits. This involves mapping the original high precision weights to a smaller set of low precision values. In the case of NF4, the quantization levels are chosen to be evenly spaced in the range of normalized weights.</li><li>Dequantization: During the forward pass and backpropagation, the quantized weights are dequantized back to full precision. This is done by mapping the 4-bit quantized values back to original range. The dequantized weights are used in the computations, but they are stored in memory in their 4-bit quantized form.</li></ul><blockquote><strong>Example </strong>— A weight in our Neural network is a 32-bit floating-point number and value is 0.5678</blockquote><blockquote>Assume 4-bit integer represents 16 levels evenly spaced between -1 and 1. These would be -1.0, -0.8667, -0.733, -0.6, -0.4667, -0.33, -0.2, -0.0667, 0.0667, 0.2, 0.333, 0.4667, 0.6, 0.7333, 0.8667, 1.0. Original weight value of 0.5678 is closed to 0.6, so quantize the weight to 0.6. In above 4-bit representation, 0.6 corresponds to the integer 13 (position). Store 4-bit integer 13 instead of 32-bit floating-point number 0.5678. For computations 4-bit integer must be dequantized as 0.6 (floating point number).</blockquote><blockquote>The dequantization error is 0.6–0.5678 = 0.0322</blockquote><p>In QLoRA method, the original pre-trained weights of the model are quantized to 4-bit and kept during fine tuning. Then a smaller number of trainable parameters in the form of low rank adapters are introduced during fine-tuning. These adapters are trained to adapt to pre-trained model to the specific tasks it is being fine tuned for in 32-bit floating point format. When it comes to computations, the 4-bit quantized weights are dequantized back to 32-bit floating point numbers. After the fine-tuning process, the model consists of the original weights in 4-bit form and the additional low rank adapters in their higher precision format. The additional low-rank adapters in the QLoRA method are in a higher precision format typically 32-bit floating point(bfloat16) for below reasons:</p><ul><li>Higher Precision allows the model to capture more subtle patterns in the data. This is particularly important for the low rank adapters, as they are responsible for adapting the pre-trained model to the specific task it is being fine-tuned for.</li><li>Training neural networks involves a lot of incremental updates to the weights. Weights in a higher precision format ensures that updates are accurately captured.</li><li>While quantizing all weights can save memory, the computation efficiency might not always improve. GPUs are optimized for 32-bit float operations.</li></ul><h3>3. Unresolved issues post Fine Tuning</h3><p>All the above methods aim to reduce memory footprint in fine tuning the LLMs. But fine tuning doesn’t allow for dynamic integration of new or proprietary data. The model’s knowledge remains static post-training, leading it to hallucinate when asked about data outside of its training set.</p><h3>Enhancing LLMs</h3><h3>3.1 Retrieval-Augmented Generation</h3><p>RAG is a viable option for enhancing outputs of language models in knowledge-intensive tasks. Retrieval Augmented Generation (RAG) is used to retrieve data from outside a foundation model and augment the prompts by adding the relevant retrieved data in context. RAG helps reduce hallucination by grounding the model on the retrieved context. RAG is cheaper to keep retrieval indices up to date than to continuously pre-train an LLM.</p><p>With RAG, the external data used to augment the prompts can come from multiple data sources, such as a document repositories, databases, or APIs. The first step is to convert the documents and any user queries into a compatible format to perform relevancy search. To make the formats compatible, a document collection, or knowledge library, and user-submitted queries are converted to numerical representations using embedding language models. Embedding is the process by which text is given numerical representation in a vector space. RAG model architectures compare the embeddings of user queries within the vector of the knowledge library. The original user prompt is then appended with relevant context from similar documents within the knowledge library. This augmented prompt is then sent to the foundation model.</p><p>One of the crucial steps in performing search and retrieval is performing a semantic search based on the input query to filter words and sentences with similar meanings. A word embedding model should be leverage for this purpose, which converts text into a set of vectors. When the source data and the prompt are vectorized based on the same word embedding model, we can perform a semantic search to match sentences and phrases with similar meanings. Since converting a large corpus of data into vectors based on word embedding for each query is expensive, generating them once and storing them in a database is a good idea. Vector databases are a new database category that stores vectors and performs similarity searches.</p><h3>3.2 Caching</h3><p>Caching is a technique to store data that has been previously retrieved or computed. Caching can significantly reduce latency for responses that have been served before, eliminating the need to compute a response for the same input again and again.</p><p>Online services often exhibit data locality, with users frequently accessing popular or trending content. Cache systems take advantage of this behavior by storing commonly accessed data, which in turn reduces data retrieval time, improves response times, and eases the burden on backend servers. Traditional cache systems typically utilize an exact match between a new query and a cached query to determine if the requested content is available in the cache before fetching the data. However, using an exact match approach for LLM caches is less effective due to the complexity and variability of LLM queries, resulting in a low cache hit rate.</p><p>Overall, caching provides a good balance between efficiency and reliability.</p><h3>References</h3><ul><li>LoRA — <a href="https://arxiv.org/pdf/2106.09685.pdf">https://arxiv.org/pdf/2106.09685.pdf</a></li><li>LoRA on LLMs- <a href="https://lightning.ai/pages/community/article/lora-llm/">https://lightning.ai/pages/community/article/lora-llm/</a></li><li>Prompt Tuning — <a href="https://arxiv.org/pdf/2104.08691.pdf">https://arxiv.org/pdf/2104.08691.pdf</a></li><li>QLoRA — <a href="https://www.youtube.com/watch?v=TPcXVJ1VSRI">https://www.youtube.com/watch?v=TPcXVJ1VSRI</a></li><li>QLoRA 4-bit Quantization — <a href="https://www.youtube.com/watch?v=TPcXVJ1VSRI">https://www.youtube.com/watch?v=TPcXVJ1VSRI</a></li><li>LLM Output Quality — <a href="https://www.youtube.com/watch?v=VKteuWXPMBs">https://www.youtube.com/watch?v=VKteuWXPMBs</a></li><li>Caching — <a href="https://github.com/zilliztech/GPTCache">https://github.com/zilliztech/GPTCache</a></li><li>RAG — <a href="https://www.promptingguide.ai/techniques/rag">https://www.promptingguide.ai/techniques/rag</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af09736e833d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promptverse]]></title>
            <link>https://krsna540.medium.com/promptverse-1244074b5491?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/1244074b5491</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 05:30:44 GMT</pubDate>
            <atom:updated>2023-07-23T05:32:03.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvAi26pQui7DHuGxyQVeLw.jpeg" /></figure><p>Package is installable through pip — <a href="https://pypi.org/project/prompt-verse/">https://pypi.org/project/prompt-verse/</a></p><p>Source Code available — <a href="https://github.com/krsna540/PromptVerse">https://github.com/krsna540/PromptVerse</a></p><h3>Description</h3><p>The PromptVerse package is designed to enhance the capabilities of developers in writing prompts, logging them, and providing a prompt registry. It offers a comprehensive list of prompt templates, allowing developers to provide input parameters and queries to generate prompts effortlessly. The package also includes offline storage in JSON format and provides features for logging, organizing, evaluating, and experimenting with prompts. With the ability to iterate through multiple prompt iterations, developers can compare experiments and metrics. Additionally, the package emphasizes minimal code requirements and provides a built-in UI display for all prompts created during a session.</p><h3>Features</h3><h3>Prompt Registry</h3><p>The PromptVerse package includes a prompt registry feature that acts as a centralized repository for storing and managing prompts. Developers can register prompts, assign relevant metadata, and easily access prompts from a single location. The prompt registry facilitates prompt discovery, version control, and promotes reusability among developers.</p><h3>Complete List of Prompt Templates</h3><p>The package provides a comprehensive list of prompt templates that cover a wide range of use cases. Developers only need to provide input parameters and queries to generate prompts using these templates. This feature streamlines the prompt writing process, saving developers time and effort.</p><h3>Offline Storage in JSON Format</h3><p>PromptVerse offers offline storage capabilities using JSON format. Developers can store prompts and related data locally, enabling easy retrieval and manipulation without an internet connection. The JSON format ensures a structured representation of prompt information.</p><h3>Logging</h3><p>The package includes a logging feature that enables developers to log prompts and associated actions. Logging helps track the execution flow, identify errors, and monitor the performance of prompts. The logged information can be used for debugging and analysis purposes.</p><h3>Organize and Evaluate Prompts</h3><p>Developers can efficiently organize and evaluate prompts using the PromptVerse package. It provides functionalities to categorize prompts based on different criteria such as tags, topics, or complexity levels. This organization helps in better management and retrieval of prompts. Additionally, developers can evaluate prompt effectiveness and performance by conducting experiments and comparing the results.</p><h3>Iterative Prompt Development and Comparison</h3><p>The PromptVerse package allows developers to iterate through multiple prompt iterations. Developers can experiment with different prompt formulations, configurations, or parameters. They can compare the results of these experiments, along with associated metrics, to determine the most effective prompt for a given scenario.</p><h3>Minimal Code</h3><p>The PromptVerse package emphasizes minimal code requirements. It provides a set of pre-defined functions and utilities that abstract complex operations, reducing the amount of code developers need to write. This allows developers to focus on the prompt logic and functionality rather than dealing with implementation details.</p><h3>UI Display of Prompt Session</h3><p>The package includes a built-in UI display that shows all the prompts created during a session. This feature provides a convenient way for developers to review and interact with prompts, ensuring a seamless prompt development experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9oNZe40ePiqRyQuYlF2xQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h4qTX2GXLk6bZf6vkJFG9w.png" /></figure><h3>Getting Started</h3><h3>Usage</h3><pre>import os<br>from prompt_verse import prompt_verse</pre><pre>if __name__ == &quot;__main__&quot;:<br>    os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;&quot; # provide your openai key here<br>    sp=prompt_verse.PromptVerse()<br>    sp.create_session(name=&quot;SamplePromptingUsecase&quot;,description=&quot;New Session for sample prompting Use case&quot;,offline_storage_location=&quot;storage/&quot;)<br>    prompt_id_1=sp.create_new_prompt(name=&quot;GreetUser&quot;,description=&quot;greeting user at begining of conversation&quot;)<br>    input_parameters={}<br>    input_parameters[&quot;persona&quot;]=&quot;Nurse ChatBot&quot;<br>    input_parameters[&quot;audience&quot;]=&quot;Patient&quot;<br>    input_parameters[&quot;query&quot;]=&quot;Greet the person&quot;<br>    input_parameters[&quot;max_length&quot;]=&quot;10&quot;<br>    generated_prompt=sp.generate_prompt_query(prompt_template=&quot;ZeroShotPrompt&quot;,prompt_input_parameters=input_parameters)<br>    llm_response=sp.execute_prompt()<br>    <br>    input_parameters={}<br>    input_parameters[&quot;persona&quot;]=&quot;Nurse ChatBot&quot;<br>    input_parameters[&quot;audience&quot;]=&quot;Patient&quot;<br>    input_parameters[&quot;query&quot;]=&quot;Greet John&quot;<br>    input_parameters[&quot;max_length&quot;]=&quot;10&quot;<br>    updated_prompt_id1=sp.update_exisitng_prompt()<br>    generated_prompt=sp.generate_prompt_query(prompt_template=&quot;ZeroShotPrompt&quot;,prompt_input_parameters=input_parameters)<br>    sp.update_input_prompt_query(&quot;Greet John Ryan&quot;)<br>    llm_response=sp.execute_prompt()<br>    <br>    #------------------------------------------------------------------------------------------------------------------<br>    <br>    prompt_id_2=sp.create_new_prompt(name=&quot;User Needs&quot;,description=&quot;asking user is doing today&quot;)<br>    input_parameters={}<br>    input_parameters[&quot;persona&quot;]=&quot;Nurse ChatBot&quot;<br>    input_parameters[&quot;audience&quot;]=&quot;Patient&quot;<br>    input_parameters[&quot;query&quot;]=&quot;ask user how he is doing today and what can we do to help him&quot;<br>    input_parameters[&quot;max_length&quot;]=&quot;20&quot;<br>    generated_prompt=sp.generate_prompt_query(prompt_template=&quot;ZeroShotPrompt&quot;,prompt_input_parameters=input_parameters)<br>    llm_response=sp.execute_prompt()<br>    print(sp.save_prompt())<br>    sp.view_report()</pre><p>References:</p><ul><li><a href="https://www.freecodecamp.org/news/how-to-build-and-publish-python-packages-with-poetry/#:~:text=After%20executing%20the%20poetry%20publish,available%20for%20installation%20through%20Poetry.&amp;text=Once%20the%20package%20is%20published,number%2Dvalidator%20library%20on%20PyPI">https://www.freecodecamp.org/news/how-to-build-and-publish-python-packages-with-poetry/#:~:text=After%20executing%20the%20poetry%20publish,available%20for%20installation%20through%20Poetry.&amp;text=Once%20the%20package%20is%20published,number%2Dvalidator%20library%20on%20PyPI</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1244074b5491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistics for Machine Learning — Comprehensive Guide Part-4.1 of 4]]></title>
            <link>https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-4-1-of-4-3cde68e95a90?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cde68e95a90</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pearson-correlation]]></category>
            <category><![CDATA[t-test]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 10:14:10 GMT</pubDate>
            <atom:updated>2023-03-18T10:14:10.689Z</atom:updated>
            <content:encoded><![CDATA[<h3>Statistics for Machine Learning — Comprehensive Guide Part-4.1 of 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D2laNn0t8y1qSWM4.jpeg" /></figure><p>In continuation to earlier <a href="https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-1-of-4-f17883273496">Part-1</a>, <a href="https://medium.com/@krsna540/statistics-for-machine-learning-comprehensive-guide-part-2-of-4-349dbf5f7844">Part-2</a> and <a href="https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-3-of-4-8f13a12b953e">Part-3</a></p><p>When it’s time to test hypothesis, it’s important to leverage the correct testing method. The two most common hypothesis testing methods are one-sided or one-tailed and two-sided tests or two-tailed tests.</p><p>Leverage a one-sided test when a strong conviction about the direction of change expected to see due to hypothesis test is known. Leverage a two-sided test when less confident in the direction of change.</p><p>Hypothesis tests can be divided into two categories: Parametric and Non-Parametric</p><p><strong>Parametric tests</strong> are those that assume that the sample data comes from a population that follows a probability distribution(normal distribution) — with a fixed set of parameters. Parametric tests are more powerful than Non-Parametric and more preferred to use.</p><p>Parametric tests have assumptions that need to be met by the data:</p><ol><li>Normality — the sample data come from a population that approximately follows a normal distribution</li><li>Homogeneity of variance — the sample data come from a population with the same variance</li><li>Independence — the sample data consists of independent observations and are sampled randomly</li><li>Outliers — the sample data don’t contain any extreme outliers</li></ol><p><strong>Non-Parametric tests</strong> are those that doesn’t make any assumptions on the population or parameters for the population. These are also referred as <strong>distribution-free tests.</strong></p><blockquote>Every parametric test has a non-parametric equivalent test</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwlPQc06eYp46zb_yDcEDg.png" /><figcaption>Hypothesis Tests</figcaption></figure><p>Dependent Samples — If the values in one sample affect the values in the other sample, then the samples are dependent.</p><p>Independent Samples — If the values in one sample reveal no information about those of the other sample, then the samples are independent.</p><h3>Parametric Tests</h3><h4>1. One Sample t-test</h4><p>The One Sample <em>t-t</em>est examines <strong><em>whether the mean of a population is statistically different from a known or hypothesized value</em></strong>. The One Sample <em>t-t</em>est or<strong> Single Sample <em>t-t</em>est</strong> is a parametric test. The One Sample <em>t</em> Test can only compare a single sample mean to a specified constant. It can not compare sample means between two or more groups.</p><p>The null hypothesis (<em>H</em>0) and (two-tailed) alternative hypothesis (<em>H</em>1) of the one sample <em>T</em> test can be expressed as:</p><ul><li><em>H</em>0: µ = µ0 (“the population mean is equal to the [proposed] population mean”)</li><li><em>H</em>1: µ ≠ µ0 (“the population mean is not equal to the [proposed] population mean”)</li></ul><p>where µ is the “true” population mean and µ0 is the proposed value of the population mean.</p><blockquote>T = (X̄ — μ) / S/√n</blockquote><p>Where, X̄ is the sample mean, μ is the hypothesized population mean, S is the standard deviation of the sample and n is the number of sample observations.</p><p>z-test are commonly used when the population standard deviation is known. t-test are used when the population standard deviation is unknown.</p><p><strong>Example- </strong>In the population, average IQ is 100. A team of scientist want to test a medication to see if it has positive or negative or no impact on intelligence. A sample of 30 participants who have take the medication has a mean of 140 with a standard deviation of 20. Did the medication affect intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vu5yVLgRn2UdOrP8gZfhBg.jpeg" /></figure><p>As alpha is 0.05, we need to find middle 95% of what we are expecting mean to be if it is outside then the mean we have is different from the population. Critical t-value at 29 degrees of freedom and at alpha =0.05 is 2.0452</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6l6qI1hfFt---kaqVtYlQ.jpeg" /></figure><h4>2. Independent Samples t-Test</h4><p>Use an independent samples t test when you want to compare the means of precisely two groups. This test is performed to determine whether two <a href="https://statisticsbyjim.com/glossary/population/">p</a>opulation means are different. The independent samples t test is also known as the two sample t test.</p><p>Independent samples t-tests have the following hypotheses:</p><ul><li><strong>Null hypothesis:</strong> The means for the two populations are equal.</li><li><strong>Alternative hypothesis:</strong> The means for the two populations are not equal</li></ul><p><strong>Example </strong>— A statistics teacher wants to compare his 2 classes to see if they performed any differently on the tests he gave that semester. Class A has 25 students with an average score of 70, standard deviation 15. Class B has 20 students with an average score of 74, standard deviation 25. Using alpha=0.05 did these 2 classes perform differently on the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYS9Cbo2sBBBvuvyNsq0yA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1BnW5QhG7Pxx1RI3rF7hA.jpeg" /></figure><p><strong>3. Paired t-test</strong></p><p>Use a paired t-test when each subject has a pair of measurements, such as a before and after score. A paired t-test determines whether the mean change for these pairs is significantly different from zero. Paired t tests are also known as a paired sample t-test or a<strong> dependent samples t test</strong>. These names reflect the fact that the two samples are paired or dependent because they contain the same subjects</p><p><strong>Example </strong>— Researcher want to test a new anti-hunger weight loss pill. They have 10 people rate their hunger both before and after taking the pill. Does the pill do anything? use alpha = 0.05</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*mEaDJtHHpDxktPxkveUJCg.png" /><figcaption>Data for anti0hunger pill</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fhS6D310n63hN6n5lhISRg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsuLkbI8G4Ty8oF86KyV4w.jpeg" /></figure><p><strong>4. One-Way ANOVA</strong></p><p>One-Way ANOVA (“analysis of variance”) compares the means of two or more independent groups in order to determine whether there is statistical evidence that the associated population means are significantly different. One-Way ANOVA is a parametric test.</p><p>This test is also known as One-Factor ANOVA, One-Way Analysis of Variance, Between Subjects ANOVA</p><p>The One-Way ANOVA is commonly used to test the following:</p><ul><li>Statistical differences among the means of two or more groups</li><li>Statistical differences among the means of two or more interventions</li><li>Statistical differences among the means of two or more change scores</li></ul><p>Data must meet the following requirements:</p><ol><li>Dependent variable that is continuous (i.e., interval or ratio level)</li><li>Independent variable that is categorical (i.e., two or more groups)</li><li>Independent samples/groups (i.e., independence of observations)</li><li>Random sample of data from the population</li><li>Normal distribution (approximately) of the dependent variable for each group (i.e., for each level of the factor)</li><li>Homogeneity of variances (i.e., variances approximately equal across groups)</li><li>No outliers</li></ol><p>When the normality, homogeneity of variances, or outliers assumptions for One-Way ANOVA are not met, run the nonparametric Kruskal-Wallis test.</p><p><strong>Hypothesis</strong></p><p>The null and alternative hypotheses of one-way ANOVA can be expressed as:</p><p><em>H</em>0: µ1 = µ2 = µ3 = … = µk (“all <em>k</em> population means are equal”)<br><em>H</em>1: At least one µi different (“at least one of the <em>k</em> population means is not equal to the others”)</p><p>where</p><ul><li>µi is the population mean of the ith group (<em>i</em> = 1, 2, …, <em>k</em>)</li></ul><p><strong>Example </strong>— Researcher wants to test a new anti-anxiety medication. They split participants into 3 conditions (0mg,5 mg, 100 mg) then ask them to rate their anxiety level on a scale of 1–10. Are there any difference between the three conditions. using alpha=0.05</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*tGKLIZjOMJ5EsiR7Dz321Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQNDG7Nfg9daDb0uWePCwQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW7xGsZlT79xZ2QKC7q3mA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIQFRXT50qScFPCU-sZkMA.jpeg" /></figure><p>Three conditions significantly differ on anxiety level F(2,18)=86.56, p&lt;0.05</p><p><strong>5.Repeated Measure ANOVA</strong></p><p>Repeated measures ANOVA is the equivalent of the one-way ANOVA, but for related, not independent groups. A repeated measures ANOVA is also referred to as a within-subjects ANOVA or ANOVA for correlated samples. This particular test requires one independent variable and one dependent variable. The dependent variable needs to be continuous (interval or ratio) and the independent variable categorical (either nominal or ordinal).</p><p>In repeated measures ANOVA, the independent variable has categories called <strong>levels</strong> or <strong>related groups </strong>where measurements are repeated over time. The benefits of repeated measures designs are that they reduce the error variance. This is because for these tests the within group variability is restricted to measuring differences between an individual’s responses between time points, not differences between individuals. Thus, researchers are better able to attribute differences across conditions or time points to being related to treatments or time factors, rather than to individual differences.</p><p><strong>Example </strong>— Researchers want to test a new anti-anxiety medication. The measure of 7 participants three times, once before taking medication, once one week after taking medication and once two weeks after taking medication. Anxiety is rated on a scale of 1–10 with 10 being high anxiety and 1 being low anxiety. Are there any difference between the three conditions using alpha=0.05</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*z1kNRjX2WUfXHBEQyCJdIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sL1bg1WY66fyWbZ3-2fZlw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*rMm6bk1SqroXfMT7mC_iuA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*2W71SHgkvw_o8L-aCnkY6g.jpeg" /></figure><p>F=224.27 which is greater than 3.8853, so reject the null hypothesis.</p><p><strong>6.Pearson Correlation Test</strong></p><p>The <strong>Pearson correlation coefficient (<em>r</em>)</strong> is the most common way of measuring a linear correlation. It is a number between –1 and 1 that measures the strength and direction of the relationship between two variables.</p><p>The Pearson correlation coefficient (<em>r</em>) is the most widely used correlation coefficient and is known by many names:</p><ul><li>Pearson’s <em>r</em></li><li>Bivariate correlation</li><li>Pearson product-moment correlation coefficient (PPMCC)</li><li>The correlation coefficient</li></ul><p>The Pearson correlation coefficient summarizes the characteristics of a dataset. Specifically, it describes the strength and direction of the linear relationship between two quantitative variables. We can test whether there is a significant relationship between two variables.</p><p>The Pearson correlation coefficient is a good choice when <strong>all </strong>of the following are true:</p><ul><li>Both variables are quantitative</li><li>The variables are normally distributed</li><li>The data have no outlier</li><li>The relationship is linear</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*nnmhtBOX5fi_I7CoaJsqfg.png" /></figure><p><strong>Example </strong>— to test age and income are related, researches collected the ages and yearly income of 10 individuals shown below. using alpha=0.05, are they related?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*cgxdtQ1UtB8H7JiqkcWbkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKs4-GF7SO8FY0-so42OWQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPV7m-sRbrMxtjrHk7s7JA.jpeg" /></figure><p>In the next part will cover Non-Parametric tests.</p><p><strong>References:</strong></p><ul><li>Datatab — <a href="https://datatab.net/">https://datatab.net/</a></li><li>Kent State University online libraries — <a href="https://libguides.library.kent.edu/SPSS/OneSampletTest">https://libguides.library.kent.edu/SPSS/</a></li><li>StatsLecture youtube channel — <a href="https://www.youtube.com/@statslectures">https://www.youtube.com/@statslectures</a></li><li><a href="https://statisticsbyjim.co/">https://statisticsbyjim.co</a>m</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cde68e95a90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistics for Machine Learning — Comprehensive Guide Part-3 of 4]]></title>
            <link>https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-3-of-4-8f13a12b953e?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f13a12b953e</guid>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 05:49:36 GMT</pubDate>
            <atom:updated>2023-02-21T05:49:36.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Statistics for Machine Learning — Comprehensive Guide Part-3 of 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3npgW3yAh0mQKhw3.jpeg" /></figure><p>In continuation to earlier <a href="https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-1-of-4-f17883273496">Part-1</a> and <a href="https://medium.com/@krsna540/statistics-for-machine-learning-comprehensive-guide-part-2-of-4-349dbf5f7844">Part-2</a></p><p>Classical statistical inference process contains below steps:</p><ul><li>Hypothesis — a proposition made as a basis for reasoning, without any assumption of its truth (price A is more profitable than price B)</li><li>Designing experiment —A/B test — experiment designed to test hypothesis to deliver conclusive results</li><li>Data collection</li><li>Inferences — the data is collected, analysed and then a conclusion is drawn</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NZ1Zc5cKEtXWDYPBIMYGQ.png" /></figure><h3><a href="https://vwo.com/glossary/a-a-testing/">A/A Testing</a></h3><p>A/A testing is a statistical test performed to compare two identical experiences on a random set of users. While the traffic is distributed equally among both variations, the objective of an A/A test is to validate a statistical test that it returns no difference in conversion rates between the two experiences.</p><h3><a href="https://vwo.com/glossary/a-b-testing/">A/B Testing</a></h3><p>A/B testing is an experimentation process where two or more versions of a web page/product/app (or an element of a webpage/product/app) are tested on the audience for specific goals to measure which version creates the highest impact on business metrics.</p><p>Example :</p><ul><li>Current treatment “A” is given to patients</li><li>Typical hypothesis is that a new treatment “B” is better</li></ul><p><strong>Subjects</strong> — The items that are exposed to treatments</p><p><strong>Treatment</strong> — Something to which a subject is exposed</p><p><strong>Treatment Group</strong> — A group of subjects exposed to a specific treatment</p><p><strong>Control Group </strong>— A group of subjects exposed to no or standard treatment</p><p>A proper A/B test has subjects that can be assigned to one treatment or another. Ideally the subjects are randomised to treatments to know difference between the treatment groups is due to one of the below two things:</p><ul><li>The effect of different treatments</li><li>Luck of the draw in which subjects are assigned to which treatments.</li></ul><p>If the experiment is expected to lead to a decision between treatment “A” and treatment “B”, a single metric or test statistic, needs to be established beforehand. Selecting a test statistic after the experiment is conducted open the door to researcher bias.</p><blockquote><em>A/B testing is a great way to gain a quick understanding of a question.</em></blockquote><h3>Hypothesis Tests</h3><p>Hypothesis Testing is used to confirm conclusions about the population parameter. Through Hypothesis testing we can determine whether there is enough evidence to conclude if hypothesis about the population parameter is true or not.</p><p>Hypothesis tests helps in learning whether random chance might be responsible for an observed effect. An A/B test is constructed with a hypothesis in mind. Statistical hypothesis testing was invented as a way to protect researchers from being fooled by random chance. Hypothesis tests are also called <strong>Significance tests.</strong></p><p>Hypothesis tests uses the following logic: “<strong>Given the human nature to react to unusual but random behavior and interpret it as meaningful, Experiment should require proof of difference between groups is more significant than what chance might reasonably produce</strong>”.</p><p><strong>Null Hypothesis</strong> — The baseline assumption that always predicts no effect or no relationship between variables</p><p><strong>Alternative Hypothesis </strong>— counterpoint to the null hypothesis, it states our research prediction of an effect or relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G-3G_Eh5J3bRBhXz.png" /><figcaption><a href="https://sciencenotes.org/null-hypothesis-examples/">Reference</a></figcaption></figure><p>In A/B test, we are testing a new option(B) against an established default option(A) and the presumption is that we will stick with default option unless the new option proves itself definitively better. In such case, we want a hypothesis test to protect us from being fooled by chance in the direction favoring B. We don’t care about being fooled by chance in the other direction, because we would be sticking with A unless B proves definitively better.</p><p>In hypothesis testing we make the decision to<strong> reject null hypothesis or fail to reject the null hypothesis</strong>.</p><p>Statistical Significance is how statisticians measure whether an experiment yields a result more extreme than what chance might produce. If the result is beyond the realm of chance variation, it is said to be <strong>statistically significant.</strong></p><p>Hypothesis testing can be summarised in 4 steps:</p><p><strong>Step-1: </strong>State the hypothesis.</p><p><strong>Example</strong> — Null Hypothesis is children in the United States watch an average of 3 hours of TV per week. Alternate Hypothesis is children watch more than (&gt;) or less than (&lt;) 3 hours of TV per week. When uncertain of the direction, state that the value in the null hypothesis is not equal to (≠) 3 hours.</p><p><strong>Step-2: </strong>Set the criteria for a decision</p><p>The criterion is based on the probability of obtaining a statistic measured in a sample if the value stated in the null hypothesis were true. <strong>Level of significance</strong> or significance level, refers to a criterion of judgment upon which a decision is made regarding the value stated in a null hypothesis. The criterion or level of significance is typically set at 5%. When the probability of obtaining a sample mean is less than 5%, then we reject the value stated in the null hypothesis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFH3x1o5f6V3-eWEah5m6w.png" /></figure><p><strong>Step-3: </strong>Compute the test statistic</p><p>The test statistic<strong> </strong>is a mathematical formula that allows researchers to determine the likelihood of obtaining sample outcomes if the null hypothesis were true. The value of the test statistic is used to make a decision regarding the null hypothesis.</p><p><strong>Step-4: </strong>Make a decision</p><p>Use the value of the test statistic to make a decision regarding the null hypothesis. Make a decision. If the probability of obtaining a sample mean is less than 5% when the null is true, then reject the null hypothesis. If the probability of obtaining a sample mean is greater than 5% when the null is true, then retain the null hypothesis.</p><blockquote>A <strong><em>p </em>value </strong>is the probability of obtaining a sample outcome, given that the value stated in the null hypothesis is true. The <em>p </em>value for obtaining a sample outcome is compared to the level of significance. The decision to reject or retain the null hypothesis is called <strong>significance.</strong></blockquote><p>The decision can be to retain the null (p &gt; .05) or reject the null (p &lt; .05).</p><p>Decisions are made on sample but not on population,<strong> t</strong>he decision can be either correct (correctly reject or retain null) or wrong (incorrectly reject or retain null).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k02mH5D-Fs85rZIGRtY57w.png" /></figure><p><strong>Type I error </strong>is the probability of rejecting a null hypothesis that is actually true. Researchers directly control for the probability of committing this type of error. This error is analogous to finding an innocent person guilty. Assume the null hypothesis is true when beginning a hypothesis test to minimise making a Type I error.</p><p>An <strong>alpha level </strong>is the level of significance or criterion for a hypothesis test. It is the largest probability of committing a Type I error that we will allow and still decide to reject the null hypothesis. This criterion is usually set at .05, and we compare the alpha level to the <em>p </em>value. When the probability of a Type I error is less than 5% (<em>p </em>&lt; .05),we decide to reject the null hypothesis; otherwise, we retain the null hypothesis.</p><p><strong>Type II error</strong> is the incorrect decision of retaining a false null hypothesis</p><p>The <strong>power </strong>in hypothesis testing is the probability of rejecting a false null hypothesis. It is the probability that a randomly selected sample will show that the null hypothesis is false when the null hypothesis is false.</p><h3>Hypothesis testing Example using Z-test as test statistic</h3><p>The <strong>z test </strong>is used to test hypotheses about a population mean when the population variance is known.</p><p><strong>Nondirectional tests</strong>, or <strong>two-tailed tests</strong>, are hypothesis tests where the alternative hypothesis is stated as <em>not equal to </em>(≠). <strong>Directional tests</strong>, or <strong>one-tailed tests</strong>, are hypothesis tests where the alternative hypothesis is stated as greater than (&gt;) or less than (&lt;) a value stated in the null hypothesis. The test statistic for a one–independent sample <em>z </em>test is called the <strong><em>z </em>statistic. </strong>The <strong><em>z </em>statistic </strong>is an inferential statistic used to determine the number of standard deviations in a standard normal distribution that a sample mean deviates from the population mean stated in the null hypothesis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*YFGWjL45lXV8ox1U4OfAmQ.png" /><figcaption>z statistic formula</figcaption></figure><p><strong>Example</strong> — Templer and Tomeo (2002) reported that the population mean score on the quantitative portion of the Graduate Record Examination (GRE) General Test for students taking the exam between 1994 and 1997 was 558 ± 139. Suppose we select a sample of 100 participants. We record a sample mean equal to 585. Compute the one–independent sample <em>z </em>test for whether or not we will retain the null hypothesis at a .05 level of significance.</p><p><strong>Solution</strong></p><p><strong>Step-1</strong> : State Hypothesis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5fy9GEI-5_C8OdbaLiWXQ.png" /></figure><p><strong>Step-2 :</strong> Set criteria for decision</p><p>To locate the probability of obtaining a sample mean from a given population, we use the standard normal distribution. We will locate the <em>z </em>scores in a standard normal distribution that are the cutoffs, or <strong>critical values, </strong>for sample mean values with less than a 5% probability of occurrence if the value stated in the null (m = 558) is true.</p><p>In a nondirectional two-tailed test, we divide the alpha value in half so that an equal proportion of area is placed in the upper and lower tail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6guptUdDdRYyLwcuA4Dlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FJLIUeKKp91UNKpoPP1ew.png" /></figure><p>Z-score for .0250 is equal to 1.96</p><p><strong>Step-3 </strong>: Compute the test statistic</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOHL3OIxae-7KeP0R8lQOQ.png" /></figure><p><strong>Step-4 </strong>: Make a decision</p><p>Obtained Z-value is 1.94</p><p>Critical Z values is 1.96</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5fArTeos2_r9zHb7xuvGA.png" /></figure><blockquote>As obtained value fails to reach the cutoff region, We have to retain the null Hypothesis which is Mean test scores are equal to 550 in population at a .05 level of significance</blockquote><p>There are many other Hypothesis tests available like t-test, Chi-Square, Kolmogorov-Smirnov, Mann-Whitney etc. in One-Sample and Two- Sample tests. Will be deep diving into these tests in next part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9xYe3iTcD1FAy_HCSbmq8w.jpeg" /><figcaption>Hypothesis Testing</figcaption></figure><blockquote>To Be Continued…….</blockquote><h3>References:</h3><ul><li>Practical Statistics for Data Scientists: 50+ Essential Concepts Using R and Python by Bruce, Peter; Bruce, Andrew;</li><li>Head First Statistics — Book by Dawn Griffiths</li><li><a href="https://www.sagepub.com/sites/default/files/upm-binaries/40007_Chapter8.pdf">https://www.sagepub.com/sites/default/files/upm-binaries/40007_Chapter8.pdf</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f13a12b953e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistics for Machine Learning — Comprehensive Guide Part-2 of 4]]></title>
            <link>https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-2-of-4-349dbf5f7844?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/349dbf5f7844</guid>
            <category><![CDATA[data-scienc]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 13:14:50 GMT</pubDate>
            <atom:updated>2022-12-31T13:41:39.888Z</atom:updated>
            <content:encoded><![CDATA[<h3>Statistics for Machine Learning — Comprehensive Guide Part-2 of 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w1E_4BjyrJ0yv9pn.jpeg" /></figure><p>First part of this series available in this <a href="https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-1-of-4-f17883273496">link</a></p><p>There’s quite a close relationship between probability and statistics. A lot of statistics has its origins in probability theory. Probability theory can help you make predictions about your data and see patterns. It can help you make sense of apparent randomness.</p><p>Basics of probability theory are available — <a href="https://krsna540.medium.com/probability-theory-for-machine-learning-overview-bb676f18d0ba">here</a></p><p><strong>Statistics deal with data, but where does it come from ?</strong></p><p>A <strong>statistical population</strong> refers to the entire group of things that you’re trying to measure, study, or analyze. A <strong>census</strong> is a study or survey involving the entire population. A census can provide you with accurate information about your population, but it’s not always practical. When populations are large or infinite, it’s just not possible to include every member.</p><p>A <strong>sample </strong>is a subset of data from a larger dataset(population). <strong>Random Sampling </strong>is a process in which each available member of the population being sampled has an equal chance of being chosen for the sample at each draw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V0_er9axiFzglqvq.png" /></figure><p>Data Quality matters more than data quantity when making an estimate or a model based on a sample. Data quality in data science involves completeness, consistency of format, cleanliness and accuracy of individual data points.</p><p>The key to creating a good sample is to choose one that is as close a match to our population as possible. If our sample is representative then we can use our sample to predict what characteristics the population will have. <strong>Not every sample closely resembles its population. </strong>Using the wrong sample could lead us to draw wrong conclusions about population parameters. Unless we are very careful, some sort of bias can creep in to the sample, which can distort our results. <strong>Bias</strong> is a sort of favoritism that we can unwittingly (or maybe knowingly) introduce into our sample, meaning that our sample is no longer randomly selected from our population.</p><p><strong>Unbiased Sample</strong></p><p>An unbiased sample is representative of the target population. This means that it has similar characteristics to the population, and we can use these to make inferences about the population itself. The shape of the distribution of an unbiased sample is similar to the shape of the population it comes from. If we know the shape of the sample distribution, we can use it to predict that of the population to a reasonable level of confidence.</p><p><strong>Biased samples</strong></p><p>A biased sample is not representative of the target population. We can’t use it to make inferences about the population because the sample and population have different characteristics. If we try to predict the shape of the population distribution from that of the sample, we’d end up with the wrong result.</p><p>Population Mean <strong>µ </strong>and Sample Mean <strong>x̄</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FgkAeE-8gbCwwx6haCu3-w.png" /><figcaption>Unbiased and Biased Sample</figcaption></figure><p>Bias is an indicator that a statistical or machine learning model has been mis-specified or an important variable left out. Drawing elements into a sample at random is <strong>Random Sampling.</strong> Random sampling is the key way to achieve unbiased sample. Random sampling can reduce bias and facilitate data quality improvement.</p><p>Selection Bias refers to bias resulting from the way in which observations are selected.</p><blockquote><strong><em>Random Sampling without replacement — </em></strong><em>Sampling without replacement means that the sampling unit isn’t replaced back into the population.</em></blockquote><blockquote><strong><em>Random Sampling with replacement — </em></strong><em>Sampling with replacement means that when we have selected each unit and recorded relevant information about it, we put it back into the population.</em></blockquote><p><strong>Stratified Sampling</strong></p><p>An alternative to random sampling is stratified sampling. With this type of sampling, the population is split into similar groups that share similar characteristics. These characteristics or groups are called strata, and each individual group is called a <strong>stratum</strong>. Perform simple random sampling on each stratum to ensure that each group is represented in our overall sample.</p><p><strong>Cluster Sampling</strong></p><p>Cluster sampling is useful if the population has a number of similar groups or clusters. With cluster sampling, instead of taking a random sample of units, you draw a random sample of clusters, and then survey everything within each of these clusters. Cluster sampling works because each cluster is similar to the others. The problem with cluster sampling is that it might not be entirely random.</p><blockquote>So with stratified sampling, we make each stratum as different as possible, and with clustered sampling, we make each cluster as similar as possible.</blockquote><p><strong>Systematic Sampling</strong></p><p>list the population in some sort of order and then survey every kth item, where k is some number. Systematic sampling is relatively quick and easy, but there’s one key disadvantage — If there’s some sort of cyclic pattern in the population, our sample will be biased. This sort of sampling can only be used effectively if there are no repetitive patterns.</p><h3>Types of Statistical Distributions</h3><p>Depending on the type of data, distributions are grouped into two categories, discrete distributions for discrete data (finite outcomes) and continuous distributions for continuous data (infinite outcomes).</p><h4>Discrete Distributions</h4><h4>1. Discrete uniform distribution</h4><p>In statistics, uniform distribution refers to a statistical distribution in which all outcomes are equally likely. Consider rolling a six-sided die. You have an equal probability of obtaining all six numbers on your next roll, i.e., obtaining precisely one of 1, 2, 3, 4, 5, or 6, equaling a probability of 1/6, hence an example of a discrete uniform distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*XHuDGgG79jB1w7S_" /></figure><h4>2. Bernoulli Distribution</h4><p>Any event with a single trial and only two possible outcomes follow a Bernoulli distribution. Flipping a coin or choosing between True and False in a quiz are examples of a Bernoulli distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*jEVp9c3dgbfsS6nD.png" /></figure><p>The graph of a Bernoulli distribution is simple to read. It consists of only two bars, one rising to the associated probability p and the other growing to 1-p.</p><h4>3. Binomial Distribution</h4><p>The Binomial Distribution can be thought of as the sum of outcomes of an event following a Bernoulli distribution. Binomial Distribution is used in binary outcome events and the probability of success and failure is the same in all successive trials. An example of a binomial event would be flipping a coin multiple times to count the number of heads and tails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/0*TMaRoRG8oExRtYK9.jpg" /></figure><p>Consider we are attempting a quiz that contains 10 True/False questions. Trying a single T/F question would be considered a Bernoulli trial, whereas attempting the entire quiz of 10 T/F questions would be categorized as a Binomial trial.</p><h4>4. Poisson Distribution</h4><p>Poisson distribution deals with the frequency with which an event occurs within a specific interval. Instead of the probability of an event, Poisson distribution requires knowing how often it happens in a particular period or distance. It is used to model count-based data, like the number of emails arriving in your mailbox in one hour or the number of customers walking into a shop in one day, for instance.</p><p>The main characteristics which describe the Poisson Processes are:</p><ul><li>The events are independent of each other.</li><li>An event can occur any number of times (within the defined period).</li><li>Two events can’t take place simultaneously.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*tS2Dsc_P6HI_dlts.png" /></figure><p>The graph of Poisson distribution plots the number of instances an event occurs in the standard interval of time and the probability of each one.</p><h4>Continuous Distributions</h4><h4>1. Normal Distribution</h4><p>Normal distribution also called <strong>Gaussian distribution</strong> is the most common distribution function for independent and randomly generated variables. A normal distribution is a symmetrical, bell-shaped distribution, with increasingly fewer observations the further from the center of the distribution. The graph of the normal distribution is characterized by two parameters: the mean which is the maximum of the graph and the standard deviation, which determines the amount of dispersion away from the mean.</p><ul><li>68% of values are within 1 standard deviation of the mean ([µ-σ µ+σ])</li><li>95% of values are within 2 standard deviations of the mean ([µ-2σ µ+2σ])</li><li>99.7% of values are within 3 standard deviations of the mean ([µ-3σ µ+3σ])</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDrjrvBi_UjSyI3bciAfIQ.png" /><figcaption>Normal Distribution</figcaption></figure><h4>2. Student t-Test Distribution</h4><p>The student’s t-distribution, also known as the t distribution, is a type of statistical distribution similar to the normal distribution with its bell shape but has heavier tails. The t distribution is used instead of the normal distribution when you have small sample sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*vALvqGE8djvOytno.png" /></figure><h4>3. Exponential distribution</h4><p>Exponential distribution is one of the widely used continuous distributions. It is used to model the time taken between different events. The exponential distribution has this memoryless property because the probability of an event occurring within a specified timeframe is not conditional on how long you’ve already been waiting for the event to occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*Gv4PeLvMcSucFAgI" /></figure><p>An exponential graph is a curved line representing how the probability changes exponentially. Exponential distributions are commonly used in calculations of product reliability or the length of time a product lasts.</p><h3>Sampling Distribution</h3><p>The term sampling distribution refers to the distribution of some sample statistic over many samples or resamples drawn from the same population.<strong> Sample Statistic</strong> is a metric calculated for a sample of data drawn from a larger population. The distribution of individual data points is <strong>Data Distribution </strong>and the distribution of a sample statistic is <strong>Sampling Distribution. </strong>Sampling distribution is likely to be more regular and bell-shaped than the Data distribution.</p><h4>Central Limit Theorem</h4><p>The central limit theorem states that if we take sufficiently large samples from a population, the samples’ means will be normally distributed, even if the population isn’t normally distributed.</p><p>The central limit theorem states that the sampling distribution of the mean will always follow a normal distribution under the following conditions:</p><ul><li>The sample size is sufficiently large.</li><li>The samples are independent and identically distributed random variables. This condition is usually met if the sampling is random.</li><li>The population’s distribution has finite variance. Central limit theorem doesn’t apply to distributions with infinite variance.</li></ul><p><strong>Standard Error</strong></p><p>Standard error is a key metric that sums up the variability in sampling distribution for a statistic. The standard error can be estimated using a statistic based on the standard deviation(s) of the sample values and the sample size(n). As the sample Size increases, standard error decreases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*awT6oQOXvL1HX76ZsshItA.png" /></figure><blockquote>Standard Deviation measures the variability of individual data points and Standard Error measures the variability of sample metric.</blockquote><p><strong>Resampling</strong></p><p>Resampling is the process of taking repeated samples from observed data. Resampling includes bootstrap and permutations(shuffling) procedures.</p><p>In permutation procedure multiple samples are combined and the sampling may be done without replacement.</p><p><strong>Bootstrap — </strong>A bootstrap sample is a sample taken with replacement from an observed data set. Bootstrap is a powerful tool for assessing the variability of a sample statistic. Bootstrap can be applied without extensive study of mathematical approximations to sampling distributions.</p><p>The algorithm for a bootstrap resampling of the mean for sample of size(n):</p><ol><li>Draw a sample value, record it and then replace it</li><li>Repeat n times</li><li>Record the mean of the n resampled values</li><li>Repeat steps 1–3 R times, where R is an arbitrary number, which specifies the number of iterations of the bootstrap.</li></ol><blockquote>Bootstrap does not compensate for a small sample size. Bootstrap neither create new data nor does it fill in holes in an existing data set. It informs about how lots of additional samples would behave when drawn from a population like our original sample.</blockquote><p>Confidence Intervals, Hypothesis Testing, A/B testing will be continued in next part.</p><blockquote>To Be Continued…….</blockquote><h4>References:</h4><ul><li>Practical Statistics for Data Scientists: 50+ Essential Concepts Using R and Python by Bruce, Peter; Bruce, Andrew;</li><li>Head First Statistics — Book by Dawn Griffiths</li><li><a href="https://www.w3schools.com/statistics/statistics_normal_distribution.php">https://www.w3schools.com/statistics/statistics_normal_distribution.ph</a>p</li><li><a href="https://datasciencedojo.com/blog/types-of-statistical-distributions-in-ml/">https://datasciencedojo.com/blog/types-of-statistical-distributions-in-ml/</a></li><li><a href="https://statisticsbyjim.com/probability/exponential-distribution/">https://statisticsbyjim.com/probability/exponential-distribution/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=349dbf5f7844" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Probability Theory for Machine Learning — Overview]]></title>
            <link>https://krsna540.medium.com/probability-theory-for-machine-learning-overview-bb676f18d0ba?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb676f18d0ba</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[probability-theory]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 05:26:31 GMT</pubDate>
            <atom:updated>2022-12-23T05:26:31.184Z</atom:updated>
            <content:encoded><![CDATA[<h3>Probability Theory for Machine Learning — Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pQqeOE9VOJIZ2N9B" /><figcaption>Photo by <a href="https://unsplash.com/@aceofnet?utm_source=medium&amp;utm_medium=referral">aceofnet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometimes it can be impossible to say what will happen from one minute to the next. But certain events are more likely to occur than others, and that’s where probability theory comes into play. Probability lets you predict the future by assessing how likely outcomes are, and knowing what could happen helps you make informed decisions.</p><p>Probability is a mathematical framework for reasoning about uncertainty.</p><p><strong>Probability</strong> indicates how likely an occurrence is, or how unlikely. In stats-speak, an event is any occurrence that has a probability attached to it — in other words, an <strong>event</strong> is any outcome where you can say how likely it is to occur. Probability is measured on a scale of 0 to 1. If an event is impossible, it has a probability of 0. If it’s an absolute certainty, then the probability is 1. A lot of the time, you’ll be dealing with probabilities somewhere in between.</p><p>Probability of an event happening = Number of ways it can happenTotal number of outcomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T68ImkA2NVkv2soho-kV0w.png" /><figcaption>Probability mathematical definition</figcaption></figure><p><strong>S</strong> is known as the possibility space, or sample space. Possible events are all subsets of S. It’s a shorthand way of referring to all of the possible outcomes.</p><p><strong>Mutually Exclusive Events</strong></p><p>When two events are Mutually Exclusive it is <strong>impossible</strong> for them to happen together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*PeLgKPGWpk3P6YMnYerGAw.png" /></figure><p><strong>Example</strong> : The probability of a card in a deck being King <strong>and</strong> a Queen is zero</p><p>P(King and Queen) = 0</p><p>P(King or Queen) = (1/13) + (1/13) = 2/13</p><p><strong>Non-Mutually Exclusive Events</strong> are events that can happen at the same time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*ZpQfyF2auUXOrZTP.png" /></figure><p>In Non-Mutually Exclusive Events, if you add P(A) and P(B), you count the intersection part twice. You should never count an element twice to find out how many you have. If you have counted it twice, there is an easy way to correct for that: <strong>subtract it once.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvUyz9cotXtorCAASikSZQ.png" /></figure><p><strong>Complimentary Events:</strong> Two events are said to be complementary when one event occurs if and only if the other does not take place. Here both the events are <strong>mutually exclusive. </strong>A’ is the complementary event of A. It’s the probability that event A does not occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*BOGnr-3sT_cDvtADZFYS6Q.png" /><figcaption>Complimentary Event of A</figcaption></figure><h3>Conditional Probabilities</h3><p>Conditional probabilities measure the probability of one event occurring relative to another occurring. If we want to express the probability of one event happening given another one has already happened, we use the “|” symbol to mean “given.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*02Vemsfg80ZQuc9NSzWDIA.png" /><figcaption>The probability of A given that we know B has happened</figcaption></figure><p>P(A and B) is the probability of getting both A and B. With this probability, you can make no assumptions about whether one of the events has already occurred. You have to find the probability of both events happening without making any assumptions.</p><p>P(A | B) is the probability of event A given event B. In other words, you make the assumption that event B has occurred, and you work out the probability of getting A under this assumption.</p><h4><strong>Law of Total Probability</strong></h4><p>Law of Total Probability gives a way of finding the total probability of a particular event based on conditional probabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2pHEE2imaVRBzqbMtblIw.png" /><figcaption>Law of total Probability</figcaption></figure><h3>Bayes’ Theorem</h3><p>Bayes’ Theorem is one of the most difficult aspects of probability.It gives you a means of finding reverse conditional probabilities, which is really useful if you don’t know every probability up front.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*enMPHAW-5ZvAzMGtbe5ijQ.png" /><figcaption>Baye’s Theorem</figcaption></figure><p>Applying Law of total probability</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*j15WC0ayMzV-whhPbPRFVw.png" /></figure><p>If two events A and B are independent, then</p><p>P(A | B) = P(A)</p><p>If this holds for any two events, then the events must be independent. Also</p><p>P(A ∩ B) = P(A) x P(B)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*GAusv2MQibuIckgD.png" /></figure><p>I can understand how you are feeling right now, This much knowledge in probability is quite sufficient for Machine Learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb676f18d0ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistics for Machine Learning — Comprehensive Guide Part-1 of 4]]></title>
            <link>https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-1-of-4-f17883273496?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/f17883273496</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistical-learning]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 15:29:11 GMT</pubDate>
            <atom:updated>2022-12-31T13:49:54.062Z</atom:updated>
            <content:encoded><![CDATA[<h3>Statistics for Machine Learning — Comprehensive Guide Part-1 of 4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uw3IaV-wHnYkMUrLBVTfpg.jpeg" /></figure><p>Statistics are numbers that summarize raw facts and figures in some meaningful way.</p><h3><strong>Study of statistics:</strong></h3><blockquote><strong>Gather data</strong> — At the root of statistics is data. Data can be gathered by looking through existing sources, conducting experiments, or by conducting surveys.</blockquote><blockquote><strong>Analyze</strong> — Once you have data, you can analyze it and generate statistics. You can calculate probabilities to see how likely certain events are, test ideas, and indicate how confident you are about your results.</blockquote><blockquote><strong>Draw conclusions </strong>-When you’ve analyzed your data, you make decisions and predictions.</blockquote><blockquote>Statistics are based on facts, but even so, they can sometimes be misleading. They can be used to tell the truth — or to lie. Studying statistics is a good way of making sure you don’t get fooled by inaccurate or misleading statistics.</blockquote><h3>Data</h3><p>Data comes from many sources: measurements, events, text, images and videos. To apply the statistical concepts unstructured raw data must be processed and manipulated into a structured form (common form is a table with rows and columns). The data type is important to determine the type of visual display, data analysis or statistical model. There are 2 basic types of structured data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGzgB4qMA5fjWRvDkOmDog.png" /><figcaption>Data Types</figcaption></figure><p><strong>Numeric</strong>: Data represented on numeric scale</p><ul><li><strong>Continuous</strong>: Data that can take on any value in an interval (Speed, Money)</li><li><strong>Discrete</strong>: Data that can take only integer values, such as count (count of occurrence of an event)</li></ul><p><strong>Categorical</strong> : Data that can take on only a specific set of values representing a set of possible categories(type of cars)</p><ul><li><strong>Nominal</strong>: Categorical data that has no measure or explicit order (Types of Cars, Marital Status). Binary is a special case of categorical data with just two categories of values (True/False, 0/1, Dead/Alive)</li><li><strong>Ordinal</strong>: Categorical data that has an explicit ordering (Movie rating)</li></ul><h3><strong>Analyze the data:</strong></h3><h4><strong>1. Location analysis</strong></h4><ul><li><strong>Mean</strong> — The sum of all values divided by the number of values</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*o0fTMn70aQzTlMr-PrUNOw.png" /></figure><ul><li><strong>Weighted Mean</strong> — The sum of all values times a weight divided by the sum of the weights</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*VKxNEbS9-wLejKS_HrA4nA.png" /><figcaption>Weighted Mean</figcaption></figure><ul><li><strong>Trimmed Mean </strong>— The average of all values after dropping a fixed number of extreme values</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*fTsOVGLV6AKBZSuWvaR9vg.png" /><figcaption>Trimmed Mean</figcaption></figure><ul><li><strong>Median</strong> — The value such that one-half of the data lies above and below</li><li><strong>Weighted Median</strong> — The value such that one-half of the sum of the weights lies above and below the sorted data</li><li><strong>Mode</strong> — The mode of a set of data is the most popular value, the value with the highest frequency.</li><li><strong>Outliers</strong> — A data value that is very different from most of the data. An extreme high or low value that stands out from the rest of the data</li><li><strong>Skewed data</strong>: When outliers pull the data to left or right then the data is skewed. <strong>Skewed to the right</strong> — Data that is skewed to the right has a “tail” of high outliers that trail off to the right. If you look at a right-skewed chart, you can see this tail. <strong>Skewed to the left </strong>— the outliers are low, and they pull the mean over to the left. In this situation, the mean is lower than the majority of values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*Upbz3s0TLlEdsU4ExSqpPw.png" /></figure><blockquote><strong>Mean</strong> — When the data is fairly symmetric and show only one trend</blockquote><blockquote><strong>Median</strong> — When data is skewed because of outliers</blockquote><blockquote><strong>Mode</strong> — When data is categorical, the only type of average calculated on categorical data is Mode</blockquote><h4>2. Variability analysis</h4><ul><li><strong>Deviations</strong> (Residuals) — The difference between the observed values and the estimate of location</li><li><strong>Variance</strong> (Mean Squared Error) — The sum of squared deviations from the mean divided by n-1 where n is number of data values</li><li><strong>Standard Deviation(</strong>σ)<strong> </strong>— The Square root of the variance. The standard deviation is much easier to interpret than the variance since it is on the same scale as the original data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*8Z5WTXxICkPwy22M3Wzlmg.png" /><figcaption>Variance and Standard Deviation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*d5XmAGUMxASpyfY_QL2PUQ.png" /></figure><ul><li><strong>Mean Absolute Deviation </strong>— The mean of the absolute values of the deviations from the mean</li><li><strong>Median Absolute Deviation </strong>(<strong>MAD</strong>) — MAD is calculated as the median of the absolute value of each value, xi, minus the median of x. The median absolute deviation is used instead of the mean deviation when the deviation value needs to be less affected by extreme values in the tail.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*M6EwIQxSMDNkrWiE93sZlw.png" /><figcaption>Median Absolute Deviation</figcaption></figure><ul><li><strong>Range</strong> — The difference between the largest and smallest value in a data set</li><li><strong>Percentile</strong> (Quantile)— The value such that P percent of the values take on this value or less and (100-P) percent takes on this value or more</li><li><strong>Interquartile range</strong>(IQR) — The difference between the 75th percentile and 25th percentile. The common measurement of variability is interquartile range (IQR). Quartiles are values that split your data into quarters. The lowest quartile is called the lower quartile, and the highest quartile is called the upper quartile. The middle quartile is the median.</li></ul><p>The variance and standard deviation are the most widespread and routinely reported statistics of variability. Both are sensitive to outliers as they are based on squared deviations. More robust metrics include mean absolute deviation, median absolute deviation from the median and percentiles(quantiles).</p><p><strong>To be continued in </strong><a href="https://krsna540.medium.com/statistics-for-machine-learning-comprehensive-guide-part-2-of-4-349dbf5f7844"><strong>Part-2</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17883273496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vectors — The  Machine Learning Perspective]]></title>
            <link>https://krsna540.medium.com/vectors-the-machine-learning-perspective-2b1673ce2e0d?source=rss-ebb387495358------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b1673ce2e0d</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Krishna Chaitanya]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 13:43:39 GMT</pubDate>
            <atom:updated>2022-11-28T13:43:39.993Z</atom:updated>
            <content:encoded><![CDATA[<h4>Vectors — The Machine Learning Perspective</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oTktZtW7M9f3VRY_" /><figcaption>Photo by <a href="https://unsplash.com/@antoine1003?utm_source=medium&amp;utm_medium=referral">Antoine Dautry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vectors are commonly used in machine learning as they lend a convenient way to organise data. There’s almost no ML model where vectors aren’t used at some point in the project lifecycle. Often one of the very first steps in making a machine learning model is vectorizing the data.</p><h3>What is a Vector ?</h3><blockquote><strong><em>Physics Perspective </em></strong><em>: Vectors are arrows pointing in space. What defines a vector is lengths and the direction it is pointing. Vectors in a flat plane are 2-Dimensional and Vectors in broad-space are 3-Dimensional.</em></blockquote><blockquote><strong><em>Computer Science Perspective</em></strong><em> : Vectors are ordered list of numbers. If the length of list is 2 then the vector is 2-Dimensional.</em></blockquote><blockquote><strong><em>Mathematics Perspective </em></strong><em>: Vectors are objects which have both, magnitude and direction. Magnitude defines the size of the vector. It is represented by a line with an arrow, where the length of the line is the magnitude of the vector and the arrow shows the direction. It is also known as Euclidean vector or Geometric vector or Spatial vector or simply </em><strong><em>vector</em></strong><em>.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*jGXIckoQdsE50rJg.png" /><figcaption>Vectors</figcaption></figure><h3>Specifics of Vector Algebra</h3><blockquote><em>Precisely a </em><strong><em>Vector</em></strong><em> is a data structure with at least two components, as opposed to a scalar. </em><strong><em>Scalars</em></strong><em> are just numbers. We can think of them like any regular value we use.</em></blockquote><blockquote><em>Co-ordinates of a vector is a pair of numbers that basically gives instruction for how to get from the tail of that vector at the origin to its tip. In a vector each coordinate is a scalar.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*eoZp6TwML1A4DgNh.png" /><figcaption>Co-ordinate representation of vectors</figcaption></figure><h4>Vector Addition and Scaling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*l3fDVfjAlJvNi8O5.png" /><figcaption>Vector Addition</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*KWtUayd37OpbzodD.png" /><figcaption>Scaling — Scalar multiplication of vector</figcaption></figure><blockquote><em>Linear combination means to add vectors together. Span of vectors is s</em><strong><em>et</em></strong><em> of all the linear combination of vectors.</em></blockquote><blockquote><em>Linear combination of V, W, U is </em><strong>aV+ bW+ cU</strong></blockquote><p>Span of these vectors is the set of all possible linear combinations</p><p>Three freely changing scalars will result in access to full 3-Dimension of space.</p><p>One of the vector can be expressed as a linear combination of other then it is <strong>Linearly Dependent.</strong></p><p>u=aV+bW</p><p>If each vector does add another dimension to the span then they are <strong>Linearly Independent.</strong></p><p>W!= aV (for all values of a)</p><p>The <strong>Basis of a vector space</strong> is a set of linearly independent vectors that span the full space.</p><h4>Dot Product of Vectors</h4><p>Dot product between 2 vectors A and B is projecting w onto the line that passes through the origin and the tip of A.</p><p><strong>A · B</strong>= |<strong>A|</strong> × |B| × cos(θ)</p><p>Dot product = (Length of projected A) * (length of projected B)</p><ul><li>2 vectors are pointing in same direction, dot product is positive</li><li>2 vectors are perpendicular then dot product is zero</li><li>2 vectors are pointing in opposite directions, then the dot product is negative</li></ul><p>Dot Product gives a scalar as output. Order of vectors in dot products doesn’t matter.</p><h4>Cross Product of Vectors</h4><p>The cross product of two vectors is the third vector that is perpendicular to the two original vectors. Its magnitude is given by the area of the parallelogram between them and its direction can be determined by the right-hand thumb rule. The Cross product of two vectors is also known as a vector product as the resultant of the cross product of vectors is a vector quantity. The cross product is zero in length when vectors <strong>a</strong> and <strong>b</strong> point in the same, or opposite, direction and reaches maximum length when vectors <strong>a</strong> and <strong>b</strong> are at right angles</p><blockquote><strong>A x B= |A| |B| sin θ</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*B6GqASV0NEhM17vo.png" /><figcaption>Cross Product</figcaption></figure><p>Cross product gives a vector as output</p><h4>Cosine Similarity</h4><p>Cosine Similarity measures the cosine of the angle between 2 non-zero vectors of an inner product space. This similarity measurement is particularly concerned with orientation, rather than magnitude. 2 cosine vectors that are aligned in the same orientation will have a similarity measurement of 1, whereas two vectors aligned perpendicularly will have a similarity of 0. If two vectors are diametrically opposed, meaning they are oriented in exactly opposite directions, then the similarity measurement is -1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*g20DWR513B9l7nGe.jpg" /><figcaption>Cosine Similarity</figcaption></figure><h4><strong>Vector Normalization</strong></h4><p>Vectors have magnitudes, and different vectors can have different sizes. Sometimes we don’t care about the size of a vector, and are only interested in the direction. If we don’t care about magnitude at all, then we can just make each vector the same size. We do this by dividing each vector by its magnitude, thus making each vector have a magnitude of 1, or transforming them to a unit vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*BWMLPwcRKmWx3XTv" /><figcaption>Vector Normalization</figcaption></figure><h3>Vector Algebra in Machine Learning</h3><ol><li>Machines can’t read text or look at images like we do. They need input to be transformed or encoded into numbers. Vectors, and matrices represent inputs like text and images as numbers, so that we can train and deploy our models.</li><li>The goal of most ML projects is to create a model that performs some function. In deep learning models, this is achieved via a neural network where the neural network layers use linear algebra (like matrix and vector multiplication) to tune your parameters. This is where the mathematical definition of vectors is relevant for ML. This includes understanding vector spaces and why they’re important for ML.</li><li>The output of ML model can be a range of different entities depending on our goal and it can be a vector as well. For example, NLP models accept text and then output a vector (called an embedding) representing the sentence. You can then use this vector to perform a range of operations, or as an input into another model. Among the operations you can perform are clustering similar sentences together in a vector space, or finding similarity between different sentences using operations like cosine similarity.</li><li>Dimensionality Reduction is about converting data of high dimensionality into data of lower dimensionality while keeping most of the information in the data. This allows us to work on larger datasets and identify the data’s most relevant features.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ni0sKC4Va0fRynAH.png" /><figcaption>Dimensionality reduction algorithms</figcaption></figure><blockquote>The mathematical definition of a vector is key to what’s going on under-the-hood of our Machine learning algorithms.</blockquote><h3>References</h3><ul><li><a href="https://www.3blue1brown.com/topics/linear-algebra">3Blue1Brown</a></li><li><a href="https://neptune.ai/blog/understanding-vectors-from-a-machine-learning-perspective">Understanding Vectors From a Machine Learning Perspective - neptune.ai</a></li><li><a href="https://www.cuemath.com/algebra/vector-algebra/">Vector Algebra - Definition, Formulas, Examples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b1673ce2e0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>