<?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 TAUIL Hafsa on Medium]]></title>
        <description><![CDATA[Stories by TAUIL Hafsa on Medium]]></description>
        <link>https://medium.com/@hasfatauil12?source=rss-151fc28d0829------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6mHmZMFr3rloIQo35lZHYw.png</url>
            <title>Stories by TAUIL Hafsa on Medium</title>
            <link>https://medium.com/@hasfatauil12?source=rss-151fc28d0829------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:22:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasfatauil12/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[You Only Look Once:
Unified, Real-Time Object Detection]]></title>
            <link>https://medium.com/@hasfatauil12/you-only-look-once-unified-real-time-object-detection-287b59fdd43e?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/287b59fdd43e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[yolo]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 17:51:07 GMT</pubDate>
            <atom:updated>2024-09-03T17:51:07.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uepULEQopn4pM5UbLtZi0Q.png" /></figure><p><strong>YOLO (You Only Look Once)</strong> is a groundbreaking object detection system that has significantly influenced the field of computer vision since its introduced by Joseph Redmon in 2015. Unlike traditional methods that repurpose classifiers or localizers to perform detection, YOLO reframes object detection as a single regression problem, predicting both class probabilities and bounding boxes directly from full images in one evaluation. This innovation allows YOLO to achieve high-speed performance while maintaining strong accuracy, making it a foundational model that has been further developed and refined in subsequent versions.</p><h3>So what is YOLO ?</h3><p>YOLO is an object detection system designed to detect and classify objects within an image in real-time. It treats the detection problem as a single regression task, directly mapping an image to bounding box coordinates and class probabilities. This approach differs from traditional object detection systems that typically involve a multi-stage process, such as using a region proposal network followed by a classification network.</p><h3>How YOLO Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OW3Tg4BeN7uvQ4boc166wg.png" /></figure><h4>General Overview:</h4><p>YOLO operates on the principle of dividing the input image into a grid and predicting bounding boxes and probabilities for each grid cell. Each bounding box has an associated confidence score that reflects the accuracy of the box and the likelihood of the object being in the box. YOLO predicts multiple bounding boxes per grid cell, allowing it to detect multiple objects within the same image.</p><h4>Key Steps:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*TElI_GQ-QOXJPZ0nDfAsOA.png" /></figure><p><strong>1. Image Division:</strong><br>The input image is divided into an S*S grid, where each grid cell is responsible for predicting bounding boxes and detecting objects whose center falls within the grid cell.</p><p><strong>2. Bounding Box Prediction:</strong><br>Each grid cell predicts a fixed number of bounding boxes (typically two) and their associated confidence scores. The confidence score is a combination of the probability that a bounding box contains an object and the accuracy of the predicted bounding box.</p><p><strong>3. Class Prediction:</strong><br>Each grid cell predicts the conditional class probabilities, P(Class_i|Object), for the presence of an object. These predictions are independent of the number of bounding boxes.</p><p><strong>4. Final Predictions:</strong><br>The final predictions combine the bounding box predictions and class probabilities. Non-Maximum Suppression (NMS) is typically used to remove redundant boxes with lower confidence scores, ensuring that the most likely bounding boxes are retained.</p><h3>Evolution of YOLO (You Only Look Once)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zg3xtj5HNRLV2uBjTeVstw.png" /></figure><ol><li><strong>YOLOv1 (2015)</strong><br>YOLOv1 was the first version introduced by Joseph Redmon in 2015. It framed object detection as a single regression problem, where the entire image is processed in one pass through the network, predicting bounding boxes and class probabilities simultaneously. This approach made YOLO extremely fast compared to previous methods like R-CNN.</li><li><strong>YOLOv2 (2016)</strong><br>YOLOv2, also known as YOLO9000, introduced several improvements, including the use of anchor boxes, batch normalization, and high-resolution classifiers. It also featured the ability to detect more than 9000 object categories by combining data from both object detection and classification datasets.</li><li><strong>YOLOv3 (2018)</strong><br>YOLOv3 introduced a more complex network architecture with Darknet-53 as its backbone, enabling better feature extraction. It also implemented multi-scale predictions, allowing the model to detect objects at different sizes more accurately.</li><li><strong>YOLOv4 (2020)</strong><br>YOLOv4 was designed for both speed and accuracy, introducing innovations like the CSPDarknet53 backbone, PANet for path aggregation, and the Mish activation function. This version further optimized the model for real-world applications, making it highly efficient.</li><li><strong>YOLOv5 (2020)</strong><br> YOLOv5 is known for being the first version written in PyTorch, which made it more accessible for developers. Although it wasn’t an official release from the original creators, YOLOv5 became widely adopted due to its ease of use and further improvements in speed and accuracy.</li><li><strong>YOLOv6 (2022)</strong><br> YOLOv6 focused on enhancing both efficiency and accuracy. It introduced architectural optimizations that improved the model’s performance on resource-constrained devices while maintaining high detection accuracy.</li><li><strong>YOLOv7 (2022)</strong><br>YOLOv7 built upon previous versions with further architectural advancements. It optimized model size and speed, ensuring the best possible performance in real-time applications, making it a preferred choice for scenarios requiring fast inference.</li><li><strong>YOLOv8 (2023)</strong><br> YOLOv8 was designed to maintain high accuracy while improving efficiency. It incorporated more advanced techniques and algorithms to ensure that the model remains competitive with newer object detection frameworks.</li><li><strong>YOLOv9 (2023)</strong><br> YOLOv9 introduced enhanced mechanisms for improving accuracy, especially in detecting smaller objects, while retaining the model’s speed. It also made strides in reducing computational overhead.</li><li><strong>YOLOv10 (2024)</strong><br>The latest version, YOLOv10, focused on eliminating Non-Maximum Suppression (NMS) and optimizing various model components for faster and more accurate detections. This version also aimed to reduce false positives and improve detection reliability in diverse environments.</li></ol><h4>Comparison Between YOLO Versions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtI0U2TaWUmFElwvkvzddg.png" /></figure><h3>Conclusion</h3><p><strong>YOLO (You Only Look Once)</strong> has dramatically transformed object detection by making it faster and more accurate with each new version. From its 2015 debut to the latest YOLOv10 in 2024, YOLO has consistently introduced key innovations that have kept it at the cutting edge of computer vision. Its evolution showcases the power of simple, unified models in achieving real-time object detection, making YOLO a foundational tool in the field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=287b59fdd43e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring LoRA(Low-Rank Adaptation)]]></title>
            <link>https://medium.com/@hasfatauil12/exploring-lora-low-rank-adaptation-c58b7192e5ba?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58b7192e5ba</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[lora]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 17:21:32 GMT</pubDate>
            <atom:updated>2024-08-24T17:21:32.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*Afte4pcUzkhD_tDXe4XpsQ.png" /></figure><p>With LoRA (Low-Rank Adaptation), we can somehow solve the challenges of fine-tuning large language models (LLMs). This technique makes the process more efficient by updating only a small, low-rank subset of the model’s parameters, significantly reducing computational and memory requirements.</p><p>In this blog, you will explore what LoRA is, how it works, its mechanism, and its applications.</p><h3>So what is LoRA?</h3><p>Low-Rank Adaptation (LoRA) was introduced to address the challenge of fine-tuning large pre-trained models, which can be prohibitively expensive in terms of storage and computation. The principle of LoRA is based on the idea that the changes in the model weights during adaptation to a specific task have a low “intrinsic rank.”. LoRA uses rank decomposition matrices to represent the updates, significantly reducing the number of trainable parameters.</p><h3>How LoRA Works</h3><p>LoRA freezes the pre-trained model weights and injects trainable low-rank matrices into each layer of the Transformer architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzhBBmRNG17dE0J0UmeU1w.png" /></figure><p><strong>Specifically:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwWekAXgC6Rp1FKz89pQmw.png" /></figure><p><strong>Note:</strong></p><ul><li><strong><em>r</em></strong> is the rank, which is much smaller than<strong><em> d </em></strong>and <strong><em>k</em></strong>.</li><li>During training, only <strong>A</strong> and <strong>B</strong> are updated, while <strong>W0</strong> remains unchanged.</li></ul><h3>Mathematical Formulation</h3><ol><li><strong>Pre-trained Weight Matrix:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*x_b-ihxrtGlCCkTEeozLtw.png" /></figure><p><strong>2. Rank Decomposition:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*Ra5WE9m1e7SW6CDk3hYtmA.png" /></figure><p><strong>3. Forward Pass:</strong> For an input x,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*BaeKoM8DUHBydd7l-67_NA.png" /></figure><p><strong>4. Initialization:</strong></p><ul><li><strong>B</strong> is initialized to zeros.</li><li><strong>A</strong> is initialized from a Gaussian distribution.</li></ul><h3>Advantages of LoRA</h3><ul><li><strong>Parameter Efficiency: </strong>Reduces the number of trainable parameters by orders of magnitude. For example, with GPT-3, LoRA can reduce the number of trainable parameters by 10,000 times.</li><li><strong>Memory Efficiency:</strong> Lowers the GPU memory requirement during training by up to 3 times since most of the pre-trained model weights are frozen.</li><li><strong>No Additional Inference Latency: </strong>Merges the trainable matrices with the frozen weights during inference, ensuring no additional latency compared to a fully fine-tuned model.</li><li><strong>Modularity: </strong>Allows a pre-trained model to be shared across many tasks by switching out the low-rank matrices, thereby reducing storage and task-switching overhead.</li><li><strong>Orthogonality: </strong>Can be combined with other methods like prefix-tuning for potentially better performance.</li></ul><h3>Applications of LoRA</h3><p>LoRA can be applied to various natural language processing tasks where large pre-trained models are used. These include:</p><blockquote>- Text generation<br>- Summarization<br>- Machine reading comprehension (MRC)<br>- Natural language to SQL (NL2SQL)<br>- Any task that involves adapting a large pre-trained language model to a specific downstream application.</blockquote><h3>Conclusion</h3><p>LoRA offers a highly efficient and scalable solution for adapting large pre-trained language models to various downstream tasks, making it an attractive alternative to traditional fine-tuning approaches.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58b7192e5ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAM: Segment Anything Model]]></title>
            <link>https://medium.com/@hasfatauil12/sam-segment-anything-model-d4f541165f6b?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f541165f6b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Thu, 25 Jul 2024 19:53:11 GMT</pubDate>
            <atom:updated>2024-07-25T19:53:11.130Z</atom:updated>
            <content:encoded><![CDATA[<p>“Segment Anything” introduces a revolutionary approach to image segmentation, capable of segmenting any kind of image using prompts like points, bounding boxes, or text. Unlike traditional models tailored to specific tasks, this model extends its functionality across diverse applications, making it a powerful foundation model akin to Gemini or GPT in NLP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dl-o6bJFgWsajEsKgB7Eiw.png" /></figure><p>In this blog you will discover the Segment Anything model, exploring its architecture including components such as the Image Encoder, Prompt Encoder, Mask Decoder, and the loss functions it employs.</p><h3>Why SAM?</h3><p>Unlike previous models, Segment Anything <strong>can handle any type of image</strong>. This is a significant advancement as it eliminates the need for multiple specialized models. It <strong>uses versatile prompts </strong>(points, bounding boxes, text) to guide segmentation, similar to NLP models like BERT or GPT-4. Additionally, SAM’s efficient encoder-decoder architecture enables<strong> real-time processing</strong>, making it practical for various applications.</p><p>These models simplify segmentation tasks significantly. With just a few lines of code, you can segment any image you need.</p><p><strong>For example, let’s take this image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UwERXd9Fqzg5clkaz15Dw.jpeg" /></figure><pre>#initialize a SAM model using (ViT) checkpoint, and generate segmentation masks for an input image (&quot;zibra.png&quot;).<br>from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor<br>sam = sam_model_registry[&quot;vit_h&quot;](checkpoint=&quot;sam_vit_h_4b8939.pth&quot;)<br>sam.to(device=&quot;cuda&quot;)<br>mask_generator = SamAutomaticMaskGenerator(sam)<br>image = np.array(Image.open(&quot;zibra.png&quot;)) #you can replace &quot;zibra.png&quot; by the path of the image you want to segment.<br>masks = mask_generator.generate(image)<br>#plot the image with the mask.<br>plt.figure(figsize=(20,20))<br>plt.imshow(image)<br>show_anns(masks) #&#39;show_anns&#39; is a helper functions defined in the next cell of code.<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><pre>def show_anns(anns):<br>    if len(anns) == 0:<br>        return<br>    sorted_anns = sorted(anns, key=(lambda x: x[&#39;area&#39;]), reverse=True)<br>    ax = plt.gca()<br>    ax.set_autoscale_on(False)<br><br>    img = np.ones((sorted_anns[0][&#39;segmentation&#39;].shape[0], sorted_anns[0][&#39;segmentation&#39;].shape[1], 4))<br>    img[:,:,3] = 0<br>    for ann in sorted_anns:<br>        m = ann[&#39;segmentation&#39;]<br>        color_mask = np.concatenate([np.random.random(3), [0.35]])<br>        img[m] = color_mask<br>    ax.imshow(img)</pre><p>The output of this code is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Wq5D246X2E48h-0FWAR9g.jpeg" /></figure><h3>Model Architecture:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIr1nl-lM5nfRrPENIvd0A.png" /><figcaption>The Segment Anything (SA) project introduces a new task, model, and dataset for image segmentation. — Source: <a href="https://ai.meta.com/research/publications/segment-anything/">Official Paper</a></figcaption></figure><p>The architecture of the <strong>“Segment Anything”</strong> model is based on an encoder-decoder framework with several key components. It starts with an <strong><em>image encoder</em></strong><em> </em>that creates an<strong><em> </em></strong>embedding from the input image. Next, a <strong><em>prompt encoder</em></strong> processes user-provided prompts. The model generates an initial mask based on the first prompt. To refine the segmentation, users can provide additional prompts, and the model uses the previous mask as a starting point. This iterative process enables the model to enhance the mask based on user input. Finally, the<strong><em> mask decoder</em></strong> combines the prompt, the previous mask, and the image embedding to predict the updated mask and its confidence score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrZPt9B4bkClC3OXUrOq8g.png" /><figcaption>The architecture of the segment anything model (SAM). — Source: <a href="https://ai.meta.com/research/publications/segment-anything/">Official Paper</a></figcaption></figure><h4>Image Encoder</h4><p>The image encoder in SAM is a crucial component motivated by the need for scalability and powerful pretraining methods. It employs a <strong><em>Vision Transformer (ViT)</em></strong> pre-trained with <strong><em>Masked Autoencoders (MAE)</em></strong>. This encoder processes high-resolution inputs with minimal adaptations and runs once per image. This pre-processing step ensures that the image is ready for prompting, making the model more efficient.</p><ul><li>The <strong>Vision Transformer (ViT)</strong> is a type of neural network architecture initially designed for natural language processing tasks and later adapted for computer vision. Unlike traditional convolutional neural networks (CNNs), ViTs divide an image into fixed-size patches, each treated similarly to a token in NLP tasks. These patches are then linearly embedded and processed through a standard Transformer encoder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*4JwejsNzoTLzF13DV7qxDg.png" /></figure><ul><li><strong>Masked Autoencoders (MAE) </strong>are a type of self-supervised learning approach used to pre-train the Vision Transformer. The key idea behind MAE is to randomly mask a portion of the input patches and train the model to reconstruct the missing parts. This process encourages the model to learn robust and meaningful representations of the image data, even when parts of the input are missing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gj9d3lj9vGzf09KhOUMzKA.png" /></figure><h4>Prompt Encoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*_c80vkEF342_sWruvo0zkg.png" /></figure><p>SAM’s prompt encoder is designed to handle two sets of prompts:<strong> sparse and dense.</strong></p><ul><li><strong><em>Sparse prompts</em></strong> include points, boxes, and text, which are represented using positional encodings combined with learned embeddings for each prompt type. Free-form text is encoded using an off-the-shelf text encoder from CLIP.</li><li><strong><em>Dense prompts</em></strong>, such as masks, are embedded using convolutions and summed element-wise with the image embedding.</li></ul><p>This flexible prompt encoding allows SAM to adapt to various user inputs seamlessly.</p><h4>Mask Decoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUWdzZKDPTMdI1H-rfWBwg.png" /></figure><p>The mask decoder in SAM is designed for efficiency, mapping the image embedding, prompt embeddings, and an output token to a mask. Inspired by previous Transformer models, the decoder uses a modified Transformer decoder block that includes prompt self-attention and cross-attention in both directions (prompt-to-image embedding and vice versa). This update enhances the embeddings, allowing the model to generate more accurate masks. The mask decoder runs two blocks before upsampling the image embedding, and a multi-layer perceptron (MLP) maps the output token to a dynamic linear classifier. This classifier computes the mask foreground probability at each image location.</p><p>The decoder operates through the following steps:</p><blockquote><strong>1. Combining Embeddings: </strong>Input prompt embeddings (points, boxes, text) and precomputed image embeddings are combined with positional encodings to maintain spatial context.</blockquote><blockquote><strong>2. Attention Mechanisms: </strong><br>- Self-Attention: Applied to prompt tokens to understand internal relationships.<br>- Cross-Attention: Bidirectional cross-attention integrates information from both prompt and image embeddings.</blockquote><blockquote><strong>3. Output Tokens and Prediction:</strong><br>- Special Tokens: IOU token for predicting confidence scores and multiple mask tokens for handling ambiguous prompts.<br>- Dynamic Mask Prediction: An MLP processes the output tokens, calculating mask foreground probability at each image location.</blockquote><blockquote><strong>4. Final Mask Generation: </strong>The decoder runs through two blocks before upsampling the image embedding. The upscaled embeddings are combined with the output tokens from the MLP to produce the final high-resolution mask.</blockquote><p>This streamlined process ensures that SAM can perform real-time interactive segmentation, making it suitable for applications like web browsers where fast and accurate segmentation is crucial.</p><h3>Loss function</h3><p>The loss function in SAM is a combination of <strong>Focal loss</strong> and <strong>Dice loss</strong>, used in a ratio of 20 to 1.</p><h4><strong>Focal loss</strong></h4><p>Focal loss is an adaptation of cross-entropy loss, designed to address class imbalance by giving more weight to hard-to-classify examples. This is crucial in segmentation tasks, where the object mask often occupies a small fraction of the image, leading to an imbalance between mask and non-mask pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*jEKPvXtd8DYZtOa2yNzbVQ.png" /></figure><p>Where γ (Gamma) is the focusing parameter to be tuned using cross-validation.</p><h4>Dice loss</h4><p>Dice loss, derived from the Sørensen-Dice coefficient or F1 score, measures the similarity between the predicted and ground truth masks. It is calculated as twice the area of overlap divided by the total area, with the loss being one minus the Dice score. This combination ensures robust performance in generating accurate segmentation masks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*JyGCT6uJXKOFUr_atPtGTg.png" /></figure><h3>Conclusion</h3><p>The Segment Anything Model (SAM) offers a powerful solution for object segmentation in images. With its fast processing speed and versatile inference modes, SAM enhances datasets with precise segmentation masks. Its innovative use of Vision Transformers and Masked Autoencoders allows it to handle diverse inputs in real-time, making it a valuable tool for various computer vision applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f541165f6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Large Language Models (LLM): The Power Behind Modern AI]]></title>
            <link>https://medium.com/@hasfatauil12/understanding-large-language-models-llm-the-power-behind-modern-ai-7f742de953b6?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f742de953b6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 15:24:04 GMT</pubDate>
            <atom:updated>2024-07-23T15:24:04.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKSfkS2DfiDsyx6SZ9_NVA.jpeg" /></figure><p>With large language models, science fiction has become a reality. As a subset of deep learning, LLMs have demonstrated impressive capabilities across a wide range of domains and applications. From text generation and classification to summarization and question answering, these models, trained on vast amounts of text data, have learned to mimic human language with remarkable accuracy.</p><p>In this blog, you’ll discover what LLMs are, how they work, their various applications, and the challenges and limitations they face.</p><h3>So what are LLMs?</h3><p>LLM refers to <strong>large</strong>, <strong>general-purpose</strong> language models that can be <strong>pre-trained</strong> and then <strong>fine-tuned</strong> for specific purposes.</p><blockquote><strong>“Large” </strong>has two meanings. First, it refers to the large training dataset. Second, it refers to the large number of parameters, which are the memories and knowledge the model learned during training.</blockquote><blockquote><strong>“General purpose”</strong> means these models can solve common problems. This is possible because human language has many similarities, and only a few organizations have the resources to train these massive models. They can create fundamental language models for others to use.</blockquote><blockquote>Finally, <strong>“pre-trained and fine-tuned” </strong>means training a large language model on a general-purpose dataset first, and then fine-tuning it for specific tasks with a smaller dataset.</blockquote><p><strong>The benefits of using large language models are:</strong></p><ul><li>First, a single model can handle a variety of tasks.</li><li>Second, large language models require minimal additional training data to adapt to specific problems.</li><li>Third, the performance of large language models continues to improve as more data and parameters are added.</li></ul><h3>How do LLMs work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*4CGRSJ6WyeQI_ve4eqUXsw.png" /></figure><p>LLMs began with early neural networks and NLP techniques. The 2017 “Attention Is All You Need” paper introduced the transformer architecture, which relies on self-attention mechanisms to weigh the importance of different words in a sentence. This allows the model to capture complex relationships and dependencies in the text, revolutionizing the field. This led to the development of models like GPT (Generative Pre-trained Transformer), showcasing the power and versatility of LLMs.</p><p>For a better understanding of transformers, I recommend this blog [“Transformer: Attention Is All You Need”](<a href="https://medium.com/@hasfatauil12/transformer-attention-is-all-you-need-79e34353d6a5">https://medium.com/@hasfatauil12/transformer-attention-is-all-you-need-79e34353d6a5</a>), where I explain the architecture and how it works in detail.</p><p>LLMs can be comprised of three key components: data, architecture (Transformers), and training. <br>The training process involves teaching the model to predict the next word in a sentence. Initially, the model might make random guesses, but with each iteration, it adjusts its internal parameters to improve accuracy. For example, it might start by predicting “the dog barks at the” as “the dog barks at the car” but gradually learns to predict “the dog barks at the cat.”<br>After initial training, the model can be fine-tuned on smaller, specific datasets to enhance its performance on particular tasks, transforming a general language model into an expert for specific applications.</p><h3>Application of LLMs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*9HxCJt785z1a-3Cpm6oyaQ.png" /></figure><p>Large Language Models have a wide range of applications, demonstrating their versatility and potential in various fields.</p><ul><li>In medicine, LLMs like ChatGPT support medical education, clinical decision-making, and patient care by providing insightful explanations and aiding in radiologic decision-making and clinical genetics.</li><li>In education, they enhance learning experiences by generating personalized recommendations, assisting in course design, and automating grading.</li><li>In finance, LLMs improve customer service, risk assessment, algorithmic trading, and financial reporting through advanced natural language processing capabilities.</li><li>In engineering, they assist in software development, debugging, mechanical calculations, and manufacturing processes, thereby improving efficiency and innovation across these domains.</li></ul><h3>Challenges &amp; Limitatioms</h3><p>The challenges and limitations of Large Language Models include:</p><p><strong>1. Bias:</strong> LLMs can replicate biases from training data, user interactions, algorithms, and context.<br><strong>2. Information Hallucination:</strong> They may generate incorrect or fictional information.<br><strong>3. Explainability:</strong> The complexity of LLMs makes it difficult to understand their decision-making processes.<br><strong>4. Resource Requirements: </strong>Training requires vast data and computational resources, which can be costly and environmentally taxing.<br><strong>5. Limited Generalizability: </strong>They may struggle with new tasks or domains outside their training data.<br><strong>6. Ethical Concerns: </strong>Issues include privacy, potential misuse, and perpetuation of harmful stereotypes or misinformation.<br><strong>7. Adversarial Attacks:</strong> Vulnerable to inputs designed to cause incorrect or harmful outputs.<br><strong>8. Cost and Scalability: </strong>High costs and limited scalability can be prohibitive for many organizations. Training LLMs requires expensive GPUs and substantial computational resources, which adds to the overall cost.</p><h3>Conclusion</h3><p>Briefly, Large Language Models (LLMs) analyze relationships between words in the training data to learn the patterns of human language. They have many uses but also face challenges. As this technology advances, it’s important to address these issues to use LLMs effectively and responsibly. Understanding these models not only illuminates the capabilities of modern AI but also underscores the ongoing need for thoughtful development and application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f742de953b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer “Attention Is All You Need”]]></title>
            <link>https://medium.com/@hasfatauil12/transformer-attention-is-all-you-need-79e34353d6a5?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e34353d6a5</guid>
            <category><![CDATA[tranformers]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 19:29:39 GMT</pubDate>
            <atom:updated>2024-07-22T19:29:39.365Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOh755aS70USG9JZXg4uCA.png" /></figure><p>In machine learning, <strong>sequence tasks</strong> involve inputs and outputs that are ordered sequences, such as time series, sentences, or DNA sequences. The order of elements in these sequences is significant. These tasks are crucial in many applications,<em> including speech recognition, music generation, DNA sequence analysis, and language translation.</em></p><p>Before advanced models like transformers, <strong>Recurrent Neural Networks (RNNs)</strong> were commonly used for sequence tasks. However, RNNs had difficulty with training due to the vanishing gradient problem. In RNNs, gradients carry information necessary for learning, but when they become too small or too large, the learning process is disrupted. This made it challenging to train on long data sequences.</p><p>Transformer solves these problems with recurrent neural networks.</p><p>In this blog, you will discover what Transformers are, along with a detailed exploration of their architecture.</p><h3>Introduction:</h3><p><strong>Transformers</strong> are a powerful deep learning model used in natural language processing <strong>(NLP)</strong> and computer vision <strong>(CV)</strong> tasks. They leverage a mechanism called <strong>“self-attention” </strong>to process sequential input data simultaneously, capturing context and relevance more effectively. This allows transformers to understand and generate complex patterns in data with remarkable accuracy.</p><h3>Model architecture:</h3><p>The structure of the Transformers can be divided into two macroblocks <strong>Encoder</strong> and <strong>Decoder</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gG7mdTf8Wy0vY0uaFeHgsQ.png" /></figure><h4>Input Embedding</h4><p>The encoder starts with Input Embedding but how do we get that input?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWIItfEL38lDcMI1FhZuYA.png" /></figure><p>To get the input embedding, we first turn our original sentence into tokens and then map these tokens to numbers that represent their positions in our vocabulary. These numbers called input IDs, are then mapped into a vector of size 512. Each vector consists of 512 numbers, and the same word is always mapped to the same initial embedding. However, this embedding is not fixed; it is a parameter that the model adjusts during training to represent the meaning of the word. While the input IDs remain constant due to the fixed vocabulary, the embeddings evolve throughout the training process. This adjustment ensures that the embeddings reflect the needs of the loss function. Essentially, input embeddings transform each word into a 512-dimensional vector, referred to as the 512D model.</p><h4>Positional Encoding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*vypNsMFFjlkhIOgYvNYh9g.png" /></figure><p>The second layer in the encoder is <strong>Positional Encoding</strong>. The position of words can significantly alter the meaning of a sentence, so each word needs to carry information about its position within the sentence. We want the positional encoding to form a pattern that the model can learn. To achieve this, we create fixed vectors of size 512, called positional encoding vectors, which are computed rather than learned. These vectors represent the position of each word in the sentence. We then add these positional encoding vectors to the input embeddings, resulting in an output that is a vector of size 512.</p><h4>Multi-Head Attention</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*bbpv13N5trbTf5wiCl3h7w.png" /></figure><p>An attention mechanism allows the model to focus on different parts of the input sequence when producing each element of the output sequence. It operates on three main components: Query (Q), Key (K), and Value (V).</p><ul><li><strong>Query (Q):</strong> The vector representation of the current position in the sequence.</li><li><strong>Key (K):</strong> The vector representations of all positions in the input sequence.</li><li><strong>Value (V):</strong> The vector representations of all positions in the input sequence, which contain the actual information to be attended to.</li></ul><p>Mathematically, it is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*owdhoRJBh7qfYxWaFvoUrA.png" /></figure><p>Here we apply​ the softmax function across the scaled dot product of the Query and Key matrices divided by the sqrt of dk (dimension of the key vectors). The result is then multiplied by the Value matrix to produce the final output.</p><p>For more details, we can summarize the process by the following steps:</p><ol><li><strong>Dot Product:</strong> Compute the dot product of the Query with all Keys to measure the similarity between the Query and each Key.</li><li><strong>Scaling:</strong> Scale the dot products by sqrt dk​​. This step helps to stabilize the gradients during training by preventing the dot products from growing too large.</li><li><strong>Softmax:</strong> Apply the softmax function to the scaled dot products to obtain the attention weights. The softmax function converts these scores into probabilities that sum to 1, allowing the model to weigh the importance of different Keys.</li><li><strong>Weighted Sum:</strong> Compute the weighted sum of the Values using these attention weights. This weighted sum represents the output of the attention mechanism, where more relevant Values (based on the attention weights) contribute more to the output.</li></ol><p><strong>Transition to Multi-Head Attention</strong></p><p><strong>Single-Head Attention</strong> has its limitations it can focus on only one aspect of the input at a time, which might not capture all the intricate dependencies in the input sequence.<br><strong>Multi-Head Attention </strong>addresses this limitation by allowing the model to jointly attend to information from different representation subspaces at different positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*lfHEXk0Nty2mBa3O4Y0BJQ.png" /></figure><ul><li><strong>Linear Projections:</strong> The inputs Q, K, and V are linearly projected h times with different learned projections. Each projection produces a set of Qi, Ki​, and Vi matrices.</li><li><strong>Parallel Attention:</strong> Each set of projections undergoes the Scaled Dot-Product Attention mechanism in parallel, resulting in h different attention outputs.</li><li><strong>Concatenation and Final Linear Projection:</strong> The h attention outputs are concatenated and once again linearly projected to form the final output.</li></ul><p>Mathematically, it can be described as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*zbTDe1IEXjK5P_-Hz5Sxiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*_ZMp4CSJAVmwCot46gLHRQ.png" /></figure><ul><li>Each head in Multi-Head Attention performs its own attention calculation independently. This allows the model to capture different aspects of the relationships in the input sequence.</li><li>By concatenating the outputs of all heads, the model can incorporate a richer set of features and dependencies.</li><li>The final linear projection ensures that the combined output has the desired dimensions for subsequent layers.</li></ul><h4>Add &amp; Norm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*X4uOCfmDZh6yg82t3XAuUw.png" /></figure><p>The next layer in the encoder is Add &amp; Norm and to introduce the other Norm we need the layer normalization.<br>Layer normalization is applied to stabilize and accelerate the training process by normalizing the inputs across the features, making the training less sensitive to the scale of the input weights.</p><p>In the Transformer model, each sub-layer in the encoder and decoder stacks is followed by layer normalization. This is done using the formula: <strong>LayerNorm(x + Sublayer(x))</strong>, where x is the input to the sub-layer, and Sublayer(x) is the output from the sub-layer itself. <br>Layer normalization normalizes the output of each sub-layer to have a mean of 0 and a variance of 1. By normalizing the output, the model can prevent issues related to covariate shift, where the distribution of inputs to a layer changes during training. This helps the model converge faster and achieve better performance.</p><h4>Feed Forward</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*uYH1a5l3Sk0AVoHrSJ8wmg.png" /></figure><p>The Feed-Forward Network (FFN) consists of two linear transformations with a ReLU activation function in between. The FFN operates independently on each position, applying the same linear transformations to all positions.</p><p>Mathematically, it is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*wGr7gSVkVY37fdP9BHP2Uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*dXFDdU5diYL8oO7JQtfEYw.png" /></figure><p>This simple yet powerful mechanism allows the model to introduce non-linearity and enhance its capacity to capture complex patterns in the data.</p><h4>Decoder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*5tFNLzfcXxaT6KsADGvAtQ.png" /></figure><p>In the encoder we saw the input embeddings in this case they are called output embeddings but the underlying working is the same. Similarly, the positional encoding used in the decoder is identical to that in the encoder.</p><p>The next layer in the decoder is the <strong>Masked Multi-Head Attention</strong>, which we will explore in detail later on.</p><p>The output of this masked multi-head attention serves as the query for the next<strong> Multi-Head Attention</strong> layer, where the keys and values are sourced from the encoder’s output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*Aej4W6WBdlY3_MAgw9Jaew.png" /></figure><p>This setup leads to a cross-attention mechanism rather than self-attention, as it involves two different sequences: one from the encoder and one from the decoder. After this cross-attention operation, layer normalization is applied.<br>The feed-forward layer, which is essentially a fully connected layer, processes the output before another layer normalization step. Finally, the result is passed through a linear layer, completing the decoding process.</p><h4>Masked Multi-Head Attention</h4><p>Masked Multi-Head Attention ensures that the predictions for a given position depend only on the known outputs at preceding positions. This mechanism prevents the model from cheating by looking at the future positions in the output sequence during training.</p><p><strong>Single-Head Masked Attention:</strong></p><p>Similar to the regular attention mechanism, but with an additional masking step (Apply a mask to the scaled dot products to set the scores of future positions to negative infinity. This prevents attention to these positions).</p><p>Mathematically, it is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*ErUfoIW5-P0cR78uPwgLWA.png" /></figure><p>where M is the mask matrix with −∞ values at positions that should not be attended to.</p><p><strong>Multi-Head Masked Attention</strong></p><p>The concept extends to Multi-Head Attention in the same way as the regular Multi-Head Attention, but with masking applied in each head.</p><p>Mathematically, it can be described as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*PpOP9zId3utlb_agzAVU7g.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*7JbH2dv2VGM8dVI1rUMg1Q.png" /></figure><h3>Conclusion</h3><p>The Transformer model has changed the way we handle natural language processing by using attention mechanisms instead of traditional methods like recurrence and convolution. This allows it to better understand long-range dependencies in data. Because of this, Transformers have become the new standard in AI, leading to many advancements in the field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e34353d6a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install Apache Web Server on Ubuntu 24.04]]></title>
            <link>https://medium.com/@hasfatauil12/how-to-install-apache-web-server-on-ubuntu-24-04-d52accff66be?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/d52accff66be</guid>
            <category><![CDATA[ubuntu-24-04]]></category>
            <category><![CDATA[apache]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 17:59:48 GMT</pubDate>
            <atom:updated>2024-07-18T18:35:34.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*CFRtolMFEmC-eexZLADLhQ.png" /></figure><h3><strong>Introduction</strong></h3><p>Apache is an open-source web server that is free, secure, rapid, effective, and extensible. It offers HTTP services compliant with the HTTP standards and boast support for modules, SSL/TLS encryption, virtual hosts, and URL redirection.</p><p>In this guide, you’ll install Apache on Ubuntu 24.04, set up virtual hosts, configure ports, and create a simple web application.</p><h3><strong>Install Apache</strong></h3><p>Apache is available in the default APT repositories on Ubuntu. Follow the steps below to install the Apache web server.</p><h4><strong>1. Update the server package index.</strong></h4><pre>sudo apt update</pre><h4><strong>2. install the Apache Web Server.</strong></h4><pre>sudo apt install apache2</pre><h4><strong>3. Verify the Installation.</strong></h4><p>To confirm Apache is running, you can either check the status of the Apache service or open the default Apache welcome page.</p><p><strong><em>check the status of the Apache service.</em></strong></p><pre>sudo systemctl status apache2</pre><p>You should see an output indicating that the Apache service is active (running).</p><p><strong>Output:</strong></p><blockquote>apache2.service — The Apache HTTP Server</blockquote><blockquote>Loaded: loaded (/lib/systemd/system/apache2.service; enabled; preset: enabled)</blockquote><blockquote>Active: active (running) since Sat 2024–05–25 21:34:56 +01; 4min 41s ago</blockquote><blockquote>Main PID: 1265 (apache2)</blockquote><blockquote>Tasks: 55 (limit: 9256)</blockquote><blockquote>Memory: 31.9M</blockquote><blockquote>CPU: 409ms</blockquote><blockquote>CGroup: /system.slice/apache2.service</blockquote><blockquote>├─1265 /usr/sbin/apache2 -k start</blockquote><blockquote>├─1311 /usr/sbin/apache2 -k start</blockquote><blockquote>└─1313 /usr/sbin/apache2 -k start</blockquote><blockquote>May 25 21:34 systemd[1]: Starting The Apache HTTP Server…</blockquote><blockquote>May 25 21:34 apachectl[1228]: AH00558: apache2:</blockquote><p><strong><em>Open the default Apache welcome page.</em></strong></p><p>Get your server IP.</p><pre>hostname -I</pre><p>Your output should be a few addresses separated by spaces, use the first IP address in the output as a URL `http://your_ip_address` to access the Apache default welcome page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*JdfUuuIpY3e-y5E-EzVFsg.png" /></figure><h3><strong>Setting Up Apache Virtual Hosts</strong></h3><p>Apache virtual hosts allow you to run multiple websites on a single server with a single public IP address. In this section, you’ll set up a virtual host with Apache on your Ubuntu 24.04 LTS server.</p><h4>1. Create the Directory Structure for your website.</h4><pre>sudo mkdir -p /var/www/example.com/public_html</pre><h4>2. Set the appropriate permissions.</h4><pre>sudo chown -R $USER:$USER /var/www/example.com/public_html<br>sudo chmod -R 755 /var/www</pre><h4>3. Create a Sample Web Page.</h4><pre>nano /var/www/example.com/public_html/index.html</pre><p>Add the following content.</p><blockquote>html</blockquote><blockquote>&lt;!DOCTYPE html&gt;</blockquote><blockquote>&lt;html&gt;</blockquote><blockquote>&lt;head&gt;</blockquote><blockquote>&lt;title&gt;Welcome to Example.com!&lt;/title&gt;</blockquote><blockquote>&lt;/head&gt;</blockquote><blockquote>&lt;body&gt;</blockquote><blockquote>&lt;h1&gt;Hello world!&lt;/h1&gt;</blockquote><blockquote>&lt;/body&gt;</blockquote><blockquote>&lt;/html&gt;</blockquote><p>Save and close the file.</p><h4>4. Create the Virtual Host File.</h4><p>Create a new virtual host configuration file.</p><pre>sudo nano /etc/apache2/sites-available/example.com.conf</pre><p>Add the content below to the file.</p><blockquote>&lt;VirtualHost *:80&gt;</blockquote><blockquote>ServerAdmin webmaster@example.com</blockquote><blockquote>ServerName example.com</blockquote><blockquote>ServerAlias <a href="http://www.example.com/">www.example.com</a></blockquote><blockquote>DocumentRoot /var/www/example.com/public_html</blockquote><blockquote>ErrorLog ${APACHE_LOG_DIR}/error.log</blockquote><blockquote>CustomLog ${APACHE_LOG_DIR}/access.log combined</blockquote><blockquote>&lt;/VirtualHost&gt;</blockquote><p>Save and close the file.</p><h4>5. Enable your new virtual host file.</h4><pre>sudo a2ensite example.com.conf</pre><p>Disable the default site if not needed:</p><pre>sudo a2dissite 000-default.conf</pre><h4>6. Activate your new configuration.</h4><pre>sudo systemctl reload apache2</pre><h4>7. Restart Apache to apply the changes.</h4><pre>sudo systemctl restart apache2</pre><h3><strong>Configuring Apache to Listen on Specific Ports</strong></h3><p>By default, Apache listens on port 80 for HTTP and port 443 for HTTPS. To add more listening ports, follow these steps.</p><h4>1. Modify the Ports Configuration File.</h4><pre>sudo nano /etc/apache2/ports.conf</pre><p>Add the desired ports.</p><pre>Listen 80<br>Listen 8080</pre><p>Save the file and exit the editor.</p><h4>2. Update your virtual host file to listen on the new port.</h4><pre>sudo nano /etc/apache2/sites-available/000-default.conf</pre><p>Add the content below to the file.</p><blockquote>&lt;VirtualHost *:8080&gt;</blockquote><blockquote>ServerAdmin webmaster@example.com</blockquote><blockquote>ServerName example.com</blockquote><blockquote>DocumentRoot /var/www/example.com/public_html</blockquote><blockquote>ErrorLog ${APACHE_LOG_DIR}/error.log</blockquote><blockquote>CustomLog ${APACHE_LOG_DIR}/access.log combined</blockquote><blockquote>&lt;/VirtualHost&gt;</blockquote><p>Save the file and exit the editor.</p><h4>3. Restart Apache to apply the changes.</h4><pre>sudo systemctl restart apache2</pre><h3><strong>Configuring Firewall to Allow Apache Traffic</strong></h3><p>Configure the firewall to allow Apache traffic.</p><h4>1. Allow both HTTP and HTTPS traffic through the firewall.</h4><pre>sudo ufw allow ‘Apache Full’</pre><h4>2. Verify the firewall settings.</h4><pre>sudo ufw status</pre><p>The output should include similar lines to the following, indicating that Apache Full is allowed:</p><p><strong>Output:</strong></p><blockquote>Status: active</blockquote><blockquote>To Action From</blockquote><blockquote>— — — — — —</blockquote><blockquote>Apache Full ALLOW Anywhere</blockquote><blockquote>Apache Full (v6) ALLOW Anywhere (v6)</blockquote><h3><strong>Creating a Simple Web Application</strong></h3><p>Create a simple web application that outputs “Hello world!”:</p><h4>1. Navigate to the Default Webroot Directory.</h4><pre>cd /var/www/html</pre><h4>2. Create an HTML File.</h4><pre>sudo nano index.html</pre><p>Add the following content:</p><blockquote>html</blockquote><blockquote>&lt;!DOCTYPE html&gt;</blockquote><blockquote>&lt;html&gt;</blockquote><blockquote>&lt;head&gt;</blockquote><blockquote>&lt;title&gt;Welcome!&lt;/title&gt;</blockquote><blockquote>&lt;/head&gt;</blockquote><blockquote>&lt;body&gt;</blockquote><blockquote>&lt;h1&gt;Hello world!&lt;/h1&gt;</blockquote><blockquote>&lt;/body&gt;</blockquote><blockquote>&lt;/html&gt;</blockquote><p>Save the file and exit the editor.</p><h3><strong>Conclusion</strong></h3><p>In this tutorial, you’ve installed, configured, and managed the Apache web server on Ubuntu 24.04. You set up virtual hosts, enabling you to host multiple websites easily, configure different ports, and serve dynamic content. Apache can handle various web technologies and create dynamic, secure websites. For more advanced configurations and features, refer to the [official Apache documentation](https://httpd.apache.org/docs/).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d52accff66be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a web development environment with Docker under Linux]]></title>
            <link>https://medium.com/@hasfatauil12/building-a-web-development-environment-with-docker-under-linux-b52b4b25190a?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/b52b4b25190a</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Fri, 31 May 2024 20:15:31 GMT</pubDate>
            <atom:updated>2024-07-16T18:49:40.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfmH1QGbcwYkeviH5tsY-w.jpeg" /></figure><p>A company’s development team members may use different operating systems and various versions of the technologies, such as PHP/Laravel and Angular. This heterogeneity can lead to dependency conflicts, inconsistencies in results, and difficulties during application deployment. Task merging becomes complex, and the development process can be slowed down.</p><p>To solve such problems, companies use<strong> standardized web development environments</strong> that ensure consistency across all team members’ systems. One effective solution is Docker, allowing developers to create isolated, consistent environments that work seamlessly across different platforms.</p><p><strong>In this blog, we’ll learn how to create a web development environment on Linux using Docker.</strong></p><h4><strong>Let’s get started and make your development process easier!</strong></h4><h3>Introduction</h3><p>In today’s software development landscape, team collaboration is essential for project success. Diverse development environments often lead to inconsistencies and integration challenges. Our goal is to create a standardized, collaborative development environment for web applications using Docker. By ensuring uniformity across all team members’ setups, we streamline integration and deployment processes. Additionally, we will utilize modern tools like GitHub for version control and Jira for task management to enhance team efficiency and collaboration.</p><h3>Choice of the Web Application Subject</h3><p>We opted for a <strong>Todo List </strong>application as the subject of our web application. This application will allow users to create task lists, add tasks to these lists, mark tasks as completed, and delete tasks once they are done.</p><p>This application was developed using the following technologies:</p><ul><li><strong>PHP:</strong> for server-side logic.</li><li><strong>MySQL:</strong> for database management.</li><li><strong>HTML and CSS:</strong> for creating the user interface.</li></ul><p>The goal of this choice is to provide a simple but functional application that demonstrates the use of Docker to standardize development environments, as well as the implementation of basic CRUD features with PHP and MySQL.</p><h3>Installation and Configuration of Docker under Linux</h3><p>To install Docker, we will use the following command:</p><blockquote>sudo apt install docker.io</blockquote><p>The output should be something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*DPY511Hy6rcLogSeHPwbPQ.png" /></figure><p>After the installation, we need to verify its functionality to do so we use:</p><blockquote>sudo systemctl status docker</blockquote><p>It should give you a similar output to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsmN8EJgHLeNxEv-gCl72Q.png" /></figure><h3>Creation, Building, and Sharing of a Docker Image for a Development Environment</h3><h4>Creating the Dockerfile</h4><ol><li><strong>Create a directory for our Docker environment and access it by</strong></li></ol><blockquote>mkdir directory_name</blockquote><blockquote>cd directory_name</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*3tsQ6QgG4f_Qa9JulLjMbg.png" /></figure><p><strong>2. Create a Dockerfile in this directory by:</strong></p><blockquote>touch Dockerfile_name</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*YtgiikIJ3P4LuMCdbglxgg.png" /></figure><p><strong>3. Open the Dockerfile with a text editor by:</strong></p><blockquote>nano Dockerfile_name</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*uEkfnAxzDy5t_jGNxIu0_g.png" /></figure><p><strong>4. Configure our development environment.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*ApWfQlh9b-aw-kNFFqaDoA.png" /></figure><p><strong>We used the following instructions:</strong></p><ol><li>FROM php:7.4-apache</li></ol><p>Specifies the base image to use for building our Docker image. In this case, we use an image that already contains Apache2 and PHP version 7.4.</p><p>2. RUN apt-get update &amp;&amp; apt-get install -y \ git \ curl \ zip \ unzip \ libpng-dev \ libjpeg-dev \ libfreetype6-dev \ &amp;&amp; docker-php-ext-configure gd --with-freetype --with-jpeg \ &amp;&amp; docker-php-ext-install gd pdo pdo_mysql mysqli</p><p>Installs the necessary dependencies for development with Laravel and Angular.</p><p>3. RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - &amp;&amp; apt-get install -y nodejs</p><p>Installs Node.js to work with Angular.</p><p>4. RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer</p><p>Installs Composer, a dependency manager for PHP.</p><p>5. EXPOSE 80</p><p>Exposes port 80 on the Docker container, allowing Apache to listen for HTTP requests on this port.</p><p>6. COPY . /var/www/html</p><p>Copies the content of the current directory (where the Dockerfile is located) into the /var/www/html directory of the Docker container.</p><p>7. CMD [&quot;apache2-foreground&quot;]</p><p>Specifies the command to run when the container starts. Here, we use the apache2-foreground command to start Apache in the foreground, ensuring the web server runs continuously.</p><h4>Building the Docker Image</h4><p>To build the Docker image, navigate to the directory containing the Dockerfile and run the command:</p><p>docker build -t docker_image_name .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*09pGSeUhEe7r0gDJrccZGw.png" /></figure><p>This command creates a Docker image named docker_image.</p><p>To verify the creation of the docker image we can use the command sudo docker images who list all Docker images that are currently available on our system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*q7L91Oi54hRHDDFzswffHw.png" /></figure><h4>Creating a Docker Hub Account and Sharing the Image</h4><ol><li><strong>Create an account on Docker Hub if you don’t already have one.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*X0SOOsyYS_NQ3ZUJCA7Rhw.png" /></figure><p><strong>2. Create a repository.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*uf-5i8UrWmvNfhV5vF7ogQ.png" /></figure><p><strong>3. Log in to Docker Hub from the command line using:</strong></p><blockquote>docker login</blockquote><p>It should give you a similar output to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*L1kfcdenUx2HX_ZkYXqo3A.png" /></figure><p><strong>4. Tag the Docker image for Docker Hub using:</strong></p><blockquote>docker tag docker_image_name your_dockerhub_username/repository_name:TAG_of_docker_image</blockquote><p><strong>N.B:</strong> You can find the TAG of the docker image by using the command sudo docker images</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*F94PCCMTTXAgi9Kf1OYN6A.png" /></figure><p><strong>5. Push the image to Docker Hub:</strong></p><blockquote>docker push <em>your_dockerhub_username/repository_name:TAG_of_docker_image</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Gx4LYt5OOy543pbUPnCIJA.png" /></figure><p><strong>6. Verification</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*_Xuu1uTkVBoF3WdMtkPJ_A.png" /></figure><h3>Deployment and Linking of the Application with the Database</h3><h4>Creating a Docker Image for the Database</h4><p>We will create a file called `init.db` containing the database, which will create the tables in the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*-XiD3jaweBngR0xynkZ0mA.png" /></figure><p>The `init.sql` file contains the tables that we will use in this file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*mRNyiTFTxd_dxbW5JGKc5g.png" /></figure><p><strong>N.B: </strong>This Dockerfile must be in the same directory as the project.</p><p><em>Since we have created two separate Dockerfiles, one for the PHP part and the other for the database, we need to ensure that the Dockerfile for the PHP part uses the other Dockerfile for MySQL by linking the two Dockerfiles through Docker Compose.</em></p><h4>Installing Docker Compose</h4><p>Install Docker Compose using:</p><blockquote>sudo apt-get install docker-compose</blockquote><p>It gives the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*FYOOuTZaIcUIX_ePUN-nOA.png" /></figure><h4>Configuring the Docker Compose File</h4><p>After installation, we will configure a `docker-compose.yml` file that will serve to:</p><p>- Link the two Dockerfiles<br>- Define the port to be used<br>- Configure the MySQL login in this file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*w2b8bjdb_SKMsZal3P686A.png" /></figure><p>This file consists of two parts:</p><p><strong>1. Services part: </strong>This is where we will import the Dockerfiles. We can also import predefined images. For example, in our case, the PHP part of the Dockerfile is found on Docker Hub in the repository <strong>`hafsatauil/mini_projet`</strong>, and it depends on `mysql-db`. It will run on port <strong>86:441</strong>.<br><strong>2. MySQL-DB part:</strong> This contains the MySQL image as well as the login information.</p><p>To execute it, type docker-compse up — build in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*TyHOSYJMdsl-MqGAaaAY5Q.png" /></figure><p><strong>N.B:</strong> This `docker-compose.yml` must be in the same directory as the application files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*26Kfcj-RyqSip8q_ZZlXXw.png" /></figure><h3>Configuring GitHub</h3><h4><strong>Create a new repository on GitHub:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kw9-VmLTLUJd4V8Mn7WtpQ.png" /></figure><p><strong>N.B: </strong>You can provide access to your teammates using their Gmail addresses.</p><p>Here’s the GitHub link: <a href="https://github.com/iseeubad/Projet-SE"><em>https://github.com/iseeubad/Projet-SE</em></a></p><p><strong>Clone the repository to your local machine:</strong></p><p>Using: <a href="/service/mailto:git@github.com"><strong>git@github.com</strong></a><strong>:iseeubad/Projet-SE.git</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*V9ukHL-gsekuJ5lHCzhH6Q.png" /></figure><p><strong>N.B: </strong>We used the access token as a password to authenticate with our account on the virtual machine, and the login username is your GitHub username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuQD4uZfgRlK02HtYiRnwA.png" /></figure><h3>Configuring Jira for Task Management</h3><h4>Creating a Jira Account</h4><ol><li>Sign up for a Jira account.</li><li>Create a new project for task management.</li></ol><h4>Configuring the Project and Dividing Tasks</h4><ol><li>Define tasks and subtasks in the Jira project.</li><li>Assign tasks to team members and set deadlines.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*870ft8ERObYCsa-RJ883qw.png" /></figure><p>Here’s the link: <a href="https://iseeubad.atlassian.net/jira/software/projects/PS/boards/2"><em>https://iseeubad.atlassian.net/jira/software/projects/PS/boards/2</em></a></p><h3>Integration of Jira with GitHub</h3><p><strong>Installing the GitHub App</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*60CtFpXBqOv2iQdSrFaALw.png" /></figure><p><strong>Authentication with GitHub</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*6b4QzJrtyV30TTso0CUzUg.png" /></figure><p><strong>Managing Repositories</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*CEXRypoQ4HhF1C8Fbxth2Q.png" /></figure><p><strong>Publishing Code to GitHub (In Jira)</strong></p><p>This is done by adding a branch to the project repository from Jira and then making the necessary modifications in this branch, either by adding files or resolving issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXxXprhJ7f2SysgaujUchg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*0ywx2WHBwvY0zAXeU7jM_g.png" /></figure><p>All the main project tasks and their subtasks are listed with their status (completed or not) and the person to whom they are assigned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nwfUwk4Mft62GSuUEDBZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBLx5w1qyOjoE0M_SBpCpQ.png" /></figure><h3>Conclusion</h3><p>We aimed to create a standardized development environment for web applications using Docker. By following these steps, you can create a powerful and consistent web development environment with Docker on Linux, ensuring smoother and more efficient development processes. <strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b52b4b25190a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Data Science and Machine Learning Fundamentals]]></title>
            <link>https://medium.com/@hasfatauil12/introduction-to-data-science-and-machine-learning-fundamentals-a7274eb0aba2?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7274eb0aba2</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 23:24:20 GMT</pubDate>
            <atom:updated>2024-07-16T18:57:30.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*B7zuRsm13jKhGHfEg-DyDw.png" /></figure><p><strong>Welcome to the gateway of possibility: data science and machine learning.</strong></p><p>In this blog, we’ll explore the essence of data science and machine learning — where algorithms unravel patterns and machines prognosticate outcomes. <br>Let’s embark on this journey together, where every data point holds a world of potential.</p><h3><strong>What is data science?</strong></h3><p>Data science is an interdisciplinary field that blends statistics, computer science, and domain expertise to extract knowledge from data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*_68Koh2QlR-FI6E8pRgS5w.png" /></figure><h4>Where is it used?</h4><p>From predicting movie recommendations to optimizing traffic flow, data science makes its mark in countless industries:</p><ul><li><strong>Healthcare: </strong>Analyzing medical records to predict patient risks and personalize treatment.</li><li><strong>Finance:</strong> Detecting fraudulent transactions and managing financial risks.</li><li><strong>Retail: </strong>Understanding customer behavior and recommending products based on preferences.</li><li><strong>Environment: </strong>Monitoring climate change and predicting natural disasters.</li></ul><h4>Its impact:</h4><p>Data science is not just about numbers; it’s about shaping our lives. It drives innovation, informs decisions, and improves efficiency across various fields. By understanding data, we can make better choices, solve complex problems, and build a brighter future.</p><h3>The Data Science Workflow</h3><p>A data science workflow defines the phases (or steps) in a data science project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GMrYRmZdez1gKOTg7fExg.jpeg" /></figure><p><strong>1. Acquisition: </strong>Every journey starts with a destination. In data <br>science, that means finding the right data — from internal databases to public datasets. It’s like sifting through sand, searching for the pieces <br>that hold the puzzle together.</p><p><strong>2. Cleaning:</strong> Raw data is rarely pristine. Missing values, <br>inconsistencies and errors can trip you up. Cleaning involves <br>scrubbing and polishing the data, making it accurate and consistent — a smooth pathway for analysis.</p><p><strong>3. Analysis: </strong>Exploratory data analysis involves visualizing and <br>summarizing the data, seeking patterns and relationships.</p><p><strong>4. Modeling: </strong>Based on your analysis, you build a model — a <br>mathematical map that captures the data’s underlying relationships. <br>This model then becomes your bridge, predicting future outcomes or classifying new data points.</p><p><strong>5. Evaluation:</strong> Evaluating your model involves testing its accuracy on unseen data. Refining the model based on the feedback ensures <br>you reach the real treasure, not just fool’s gold.</p><h3>Data Types</h3><p>There aretwo main categories of data; structured and unstructured data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im--OjjLzdKU70A039XO0g.jpeg" /></figure><p><strong>Structured data</strong> is organized data that follows a defined format, typically stored in rows and columns in tables or spreadsheets.<br>This makes it easy for computers to process and analyze. <br>A good example of structured data is a client database, where each client has their name, address, and other details stored in an appropriate format.</p><p><strong>Unstructured data</strong>, on the other hand, is data that has no predefined format. It could acknowledge text documents, images, videos, audio files as well as social media posts.<br>Because of its varied nature, unstructured data is more difficult for computers to process.</p><h3>What is Machine Learning</h3><p>Imagine a robot, learning by experience like a child. That’s the meat of Machine Learning ML!</p><p>It’s about creating algorithms that can automatically learn from data and make predictions without being explicitly programmed.</p><h4>The Learning Process</h4><ul><li>You feed the algorithm vast amounts of data as well as images, text, or numbers.</li><li>The algorithm analyzes the data, searching for patterns and relationships.</li><li>The algorithm starts to understand the data as well as identifying key features and connections.</li><li>Armed with its new knowledge as well as the algorithm can now make predictions about new, undetected data!</li></ul><h4>The Power of Machine Learning:</h4><p><strong>Automates tasks: </strong>The algorithm never got tired of analyzing data, saving time and resources.</p><p><strong>Handles complex problems: </strong>The algorithm can learn from massive datasets, revealing hidden insights humans might miss.</p><p><strong>Improves over time: </strong>The more data the algorithm sees, the better it gets at making accurate predictions.</p><h4><strong>Supervised Learning vs Unsupervised Learning:</strong></h4><p><strong>Supervised Learning: </strong>The algorithm has a teacher giving labeled examples. The goal here is to predict known outputs from new data.</p><blockquote><strong>Real-world examples</strong>: Spam filters, medical diagnosis</blockquote><p><strong>Unsupervised Learning: </strong>The algorithm figures things out on its own, finding hidden patterns with no labeled data.</p><blockquote><strong>Real-world examples</strong>: Recommender systems, fraud detection</blockquote><p>There’s another type which is<strong> “Reinforcement learning”</strong> when the algorithm learns from mistakes.</p><h4><strong>Types of Machine Learning problems:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvzZzvovTKrXybdj0_PZDA.png" /></figure><p><strong>Supervised learning tasks include classification and regression.</strong></p><p><strong>Classification problems</strong> involve predicting a categorical label for a data point.<br><strong>Regression problems</strong> involve predicting a continuous numerical output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoCLpvk29E5j4lgwUGMvJQ.png" /></figure><p><strong>Unsupervised learning</strong> is useful for tasks like customer segmentation, where you want to group customers into different categories based on their behavior or attributes.</p><ul><li><strong>Clustering:</strong> Groups like data points together, like sorting customers by purchase history.</li><li><strong>Association:</strong> Discovers relationships between data, like finding items often bought together at a store.</li></ul><p><strong>Reinforcement learning </strong>is used in applications like training a self-driving car to navigate its surroundings.</p><h3>Hands-On Activity “Titanic-M.L from Disaster”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKwp6nGAhaIPeugXyHEMDA.png" /></figure><p>Our Goal here is to predict survival on the Titanic based on the data.</p><p>Here’s the link to the <a href="https://www.kaggle.com/competitions/titanic">c</a>ompetition. It’s a “Hello Word!” for M.L.</p><p>I’ll be working in a Kaggle notebook; here’s the <a href="https://www.kaggle.com/code/hafsatauil/m-l-hand-s-on-activity">link</a>.</p><h3>About data:</h3><p>The data has been split into two groups.</p><ul><li><strong>Training set</strong> # with Ground truth.</li><li><strong>Test set </strong># without Ground truth.</li></ul><p>Later we gonna split the training set into <strong>train 80%</strong> and <strong>evaluation 20%.</strong></p><h4>Let’s now see the features in our data:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*l1xHJyIlQNaUaPeJBHCVXw.png" /></figure><p><strong>Variable Notes</strong></p><blockquote><strong>pclass: </strong>A proxy for socio-economic status (SES)<br>1st = Upper<br>2nd = Middle<br>3rd = Lower<br><strong>age:</strong> Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5<br><strong>sibsp: </strong>The dataset defines family relations in this way…<br>Sibling = brother, sister, stepbrother, stepsister<br>Spouse = husband, wife (mistresses and fiancés were ignored)<br><strong>parch: </strong>The dataset defines family relations in this way…<br>Parent = mother, father<br>Child = daughter, son, stepdaughter, stepson<br>Some children travelled only with a nanny, therefore parch=0 for them.<br><strong>We have the label ‘survival’</strong></blockquote><h3>Preprocessing</h3><p><strong>First, let’s open the notebook </strong><br>By default in Kaggle, we have this cell of code</p><pre># This Python 3 environment comes with many helpful analytics libraries installed<br># It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python<br># For example, here&#39;s several helpful packages to load<br><br>import numpy as np # linear algebra<br>import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)<br><br># Input data files are available in the read-only &quot;../input/&quot; directory<br># For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory<br><br>import os<br>for dirname, _, filenames in os.walk(&#39;/kaggle/input&#39;):<br>    for filename in filenames:<br>        print(os.path.join(dirname, filename))<br><br># You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using &quot;Save &amp; Run All&quot; <br># You can also write temporary files to /kaggle/temp/, but they won&#39;t be saved outside of the current session</pre><p>That contains:</p><ul><li>import <strong>numpy </strong>as np for linear algebra</li><li>import <strong>pandas </strong>as pd for data manipulation</li><li>import <strong>os </strong>which means operation system.</li></ul><p>The output of the cell is the path of the files in our dataset.</p><p>When we run the cell it gives us three paths:</p><ul><li>/kaggle/input/titanic/train.csv</li><li>/kaggle/input/titanic/test.csv</li><li>/kaggle/input/titanic/gender_submission.csv</li></ul><p>Let’s now read our dataset using pandas</p><blockquote>We use pd.read _csv (“path”)</blockquote><pre>train             = pd.read_csv(&#39;/kaggle/input/titanic/train.csv&#39;)<br>test              = pd.read_csv(&#39;/kaggle/input/titanic/test.csv&#39;)<br>gender_submission = pd.read_csv(&#39;/kaggle/input/titanic/gender_submission.csv&#39;)</pre><pre>train</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TpLYYaufeuMae2fdUWFJg.png" /><figcaption>As we see the train data contains 891 rows (info of person) and 12 columns (11 features for each + 1 for the label)</figcaption></figure><pre>test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObUbcxTlOqgsUqUfARx9fQ.png" /><figcaption>For the test data we have 418 rows and 11 columns without the label</figcaption></figure><pre>gender_submission</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*v5CjVb-BIewiuyYIm9H1SQ.png" /><figcaption>For the gender-submission, we have just the PassengerId and the label.</figcaption></figure><h4>Exploratory Data Analysis (EDA)</h4><p>Now let’s have some fun with our data before starting the cleaning using the matplotlib library.<br><strong>So let’s import it.</strong></p><pre>import matplotlib.pyplot as plt</pre><p>To count (survived + non survived) in the train data we can use:</p><pre>train[&#39;Survived&#39;].value_counts()</pre><p>The output is:</p><blockquote><strong>Survived</strong><br>0 =&gt; 549<br>1 =&gt; 342</blockquote><p><strong>Let’s try some visualizations:</strong></p><pre># Count the occurrences of each class<br>class_counts = train[&#39;Survived&#39;].value_counts()<br><br># Plotting a bar chart for the &#39;Survived&#39; column<br>class_counts.plot(kind=&#39;bar&#39;) # to specify the type of the plot<br>plt.xlabel(&#39;Survived&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Bar Chart of Survived Frequencies&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*WRJmgXmWvBfouPs9mYK43g.png" /></figure><pre>for column in [&#39;Pclass&#39;, &#39;Sex&#39;, &#39;Embarked&#39;]:<br><br>    # Count the number of survivors and non-survivors for each column<br>    survival_counts = train.groupby([column, &#39;Survived&#39;]).size().unstack()<br><br>    # Reordering the columns for better visualization<br>    survival_counts = survival_counts[[1, 0]]  # 1 represents survived, 0 represents unsurvived<br><br>    # Plotting<br>    x = np.arange(len(survival_counts.index)) <br>    width = 0.35  # Width of the bars<br><br>    fig, ax = plt.subplots()  <br>    rects1 = ax.bar(x - width/2, survival_counts[1], width, label=&#39;Survived&#39;, color=&#39;lightgreen&#39;)  # Bars for survived<br>    rects2 = ax.bar(x + width/2, survival_counts[0], width, label=&#39;Not Survived&#39;, color=&#39;lightcoral&#39;)  # Bars for unsurvived<br>    <br>    # Adding labels and title<br>    ax.set_title(f&#39;Survival Count by {column}&#39;)  # Setting the title<br>    ax.set_xlabel(column)  # Setting the label for the x-axis<br>    ax.set_ylabel(&#39;Count&#39;)  # Setting the label for the y-axis<br>    ax.set_xticks(x)  # Setting the tick positions on the x-axis<br>    ax.set_xticklabels(survival_counts.index)  # Setting the tick labels<br>    ax.legend()  # Adding legend<br><br>    # Show plot<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*5HuVsqoxBzEFRq3zm4YB3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*B6zk3LlwncSsSmIrUx0Z2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*0OiC063I2iQDxnYL88bBrA.png" /></figure><pre>color    = [&#39;lightcoral&#39;, &#39;lightgreen&#39;]<br>Survived = [&#39;Unsurvived&#39;, &#39;Survived&#39;]<br><br>for column in [&#39;Age&#39;, &#39;Fare&#39;]:<br>    _,ax = plt.subplots(1,2, figsize=(10,3))<br>    for k in range(2):<br>        ax[k].hist(train[column][train[&#39;Survived&#39;]==k], edgecolor=&#39;black&#39;, color=color[k]) <br>        ax[k].set_title(f&#39;Histogram of {column} ({Survived[k]})&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgAd7z2ZQUdePKg59pFhdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3yRg5X43w9LFR3OxFGJnQ.png" /></figure><p><strong>Now let’s the cleaning begin:</strong></p><p>First, let’s start by checking for any missing values.</p><pre>train.isnull().sum()</pre><p>The output should be each feature plus how many missing values it contains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*idoFRjnOjuw26yITu3FPjw.png" /><figcaption>As we see there missing values in Age, Cabin, and Embarked.</figcaption></figure><p>For the Cabin 77% of it is missing so our model may not learn anything from it. That is why we will not use it to train our model.</p><p>To deal with missing values there are three ways:<br><strong>1. Drop the whole column.<br>2. Drop the rows that contain missing values.</strong></p><blockquote><strong>Note: </strong>In our case (1&amp;2) are not efficient at all cause we have small samples of data.</blockquote><p><strong>3- the last one is to fill the missing values with a value.</strong><br>For numbers usually we use the (mean or average) to fill it .We will use the ‘<strong>fillna’ </strong>(fill none) function.<br>but for Embarked its not a number so we can’t use the mean, let’s choose the Sclass cause the most in it.</p><pre>train[&#39;Age&#39;].fillna(train[&#39;Age&#39;].mean(), inplace=True)<br>train[&#39;Embarked&#39;].fillna(&#39;S&#39;, inplace=True)</pre><p>Let see our missing values again to chack if we fill them right.</p><pre>train.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*yAJ2C9ZcUfLJwLDBSbc0SA.png" /></figure><p><strong>Let’s move to the second phase of the cleaning.</strong></p><p>M.L is all about mathematical operations, which means it only can handle numbers so we need to convert the Categorical features into numerical ones.</p><p>To do that there is two ways :</p><ul><li><strong>Label Encoding: </strong>Assigns a unique integer to each unique categorical value, treating them as ordered</li></ul><blockquote>Example: “dog”=1 , “cat”=2</blockquote><ul><li><strong>One-Hot Encoding: </strong>Creates a new binary feature for each unique category, with a value of 1 for the corresponding category and 0 for all others</li></ul><blockquote><strong>Example:</strong> Colors<br>G B R<br>1 0 0 <strong># for Green</strong><br>0 1 0 <strong># for Blue</strong><br>0 0 1 <strong># for Red</strong></blockquote><p>In our case the features we will convert ‘Sex’ and ‘Embarked’. In both, we will use <strong>Label Encoding.</strong></p><p>To do so we utilize the <strong>map </strong>function.</p><pre>train[&#39;Sex&#39;]      = train[&#39;Sex&#39;].map({&#39;male&#39;: 0, &#39;female&#39;: 1})<br>train[&#39;Embarked&#39;] = train[&#39;Embarked&#39;].map({&#39;C&#39;: 0, &#39;Q&#39;: 1, &#39;S&#39;: 2})</pre><p>Here’s our train data after the conversion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHiEC6sFM9QEBzg5LDEexw.png" /></figure><p>Now we will create a list of features that we will feed our model with.</p><p>‘PassengerId’, ‘Name’, ‘Ticket’, and ‘Cabin’ will add nothing to our model so we will not involve them.</p><p>Also, we will creat another variable for the label.</p><pre>features = [&#39;Pclass&#39;,&#39;Sex&#39;,&#39;Age&#39;,&#39;SibSp&#39;,&#39;Parch&#39;,&#39;Fare&#39;,&#39;Embarked&#39;]<br>label    = [&#39;Survived&#39;]</pre><p>Now we will split the training set into train 80% and evaluation 20% (to evaluate the performance of our model on unseen data) as we already said.</p><p>To do so we will use <strong>train_test_split</strong> from <strong>Scikit-learn</strong>.</p><p>Let’s import it.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>xtrain, xvalid, ytrain, yvalid = train_test_split(<br>    train[features],<br>    train[label],<br>    test_size    = 0.2, #to give evaluation 20%<br>    random_state = 42,  #for the same subdivision of the data each time we ran the cell<br>    shuffle      = True,#to mix our data <br>)</pre><p>To see their shape we can use “<strong>.shape”.</strong></p><pre>xtrain.shape, ytrain.shape, xvalid.shape, yvalid.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*cuSBDTH1aTsSY5NDkBunuA.png" /></figure><h3>Modeling &amp; Evaluation</h3><p><strong>Welcome to the heart of machine learning, where data transforms into predictions.</strong></p><p><strong>Modeling</strong> in machine learning is the process of creating mathematical representations of real-world phenomena, allowing us to make predictions, uncover patterns, and derive insights from data. At its core, modeling involves selecting and training algorithms on historical data to build predictive models that can generalize to unseen data.</p><p><strong>Evaluation</strong> checks how well models work on new data. It tests accuracy and generalization beyond training. Metrics like accuracy and precision help decide if the model is good enough for real-world use.”</p><p><strong>Model selection</strong> is a crucial step in this process, as it ensures that the chosen model is well-suited to the problem at hand and can perform optimally in real-world scenarios. By carefully considering factors such as model complexity, interpretability, and performance metrics, we can harness the full potential of machine learning to solve diverse challenges across various domains.</p><p>I will gonna try with you three common-use models and compare between them.</p><blockquote><strong>XGBoost</strong> is a machine learning library designed for efficient and scalable implementation of gradient boosting. It is widely used for classification and regression tasks due to its high performance and flexibility.</blockquote><p>Our problem is to classify if the person gonna survived or not. So it’s a <strong>supervised M.L classification problem</strong>.</p><p>That is why we will use <strong>XGBClassifier.</strong></p><blockquote><strong>Note:</strong> For regression problems we use <strong>XGBRegressor.</strong></blockquote><pre>from xgboost import XGBClassifier <br>model = XGBClassifier(random_state=42)<br>model.fit(xtrain,ytrain)<br><br>from sklearn.metrics import mean_squared_error<br>preds_valid = model.predict(xvalid)<br>print(mean_squared_error(yvalid, preds_valid, squared =False))</pre><blockquote><strong>LightGBM (LGB):</strong>is a gradient boosting framework designed for efficiency and scalability. It uses techniques to improve training speed and handle large datasets effectively.</blockquote><pre>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>from lightgbm import LGBMClassifier<br>model = LGBMClassifier(random_state=42) #verbose=-1<br>model.fit(xtrain, ytrain)<br><br>from sklearn.metrics import mean_squared_error<br>preds_valid = model.predict(xvalid)<br>print(mean_squared_error(yvalid, preds_valid, squared=False))</pre><blockquote><strong>CatBoost: </strong>is a gradient boosting library optimized for handling categorical features. It automatically converts categorical variables into numerical values during training and employs ordered boosting to reduce overfitting, resulting in high-quality predictions with minimal parameter tuning.</blockquote><pre>from catboost import CatBoostClassifier<br><br># Define and train the CatBoost model<br>model = CatBoostClassifier(random_state=42)#verbose=0<br>model.fit(xtrain, ytrain)<br><br># Make predictions and calculate mean squared error<br>preds_valid = model.predict(xvalid)<br>print(mean_squared_error(yvalid, preds_valid, squared=False))</pre><p>The three models in this case give us a kinda similar result:</p><p>for XGBoost <strong>0.4484610556511615</strong><br>for LightGBM<strong> 0.422813138065352</strong><br>for CatBoost <strong>0.41615424729527806</strong></p><p>Still, CatBoost gives us the best results.</p><p><strong>In conclusion</strong>, understanding the basics of data science and machine learning fundamentals is essential for navigating today’s data-driven world. With the power to draw insights, make predictions, and drive informed decisions, these foundational concepts empower individuals to leverage data effectively in various domains and industries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7274eb0aba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fundamentals of Python: A beginner’s guide.]]></title>
            <link>https://medium.com/@hasfatauil12/fundamentals-of-python-a-beginners-guide-8e15d4a6a900?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e15d4a6a900</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 17:07:57 GMT</pubDate>
            <atom:updated>2024-07-16T19:02:43.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*LHmbSROGPOXGpDIduVYXpQ.png" /></figure><p>Forget robot screwdrivers; meet Python the data whisperer! Python is a powerful yet beginner-friendly high-level, general-purpose programming language that emphasizes readability and ease of use.</p><p>Created by Guido van Possum and first released in 1991, Python has fit one of the most common programming languages due to its simpleness and versatility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-WaIPX1b7xlLZXnbOOVbA.jpeg" /><figcaption><strong>Guido van Possum</strong></figcaption></figure><h3>Basic syntax</h3><h4>Indentation</h4><p>Python uses indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code.</p><h4>Comments</h4><p>There are two types of comment in Python:<br><strong>Single line comments:</strong> starts with hashtag symbol with no white spaces.</p><blockquote># This is a comment</blockquote><p><strong>Multi-line string as comment:</strong> is a piece of text enclosed in a delimiter (“””) on each end of the comment.</p><blockquote>“””<br>This is a multi-line comment in Python.<br>It can span across several lines,<br>allowing for detailed explanations or notes.<br>“””</blockquote><h4>Variables</h4><p>Variables in Python are not<strong> “statically typed”.</strong> We do not need to declare <br>variables before using them or declare their type. A variable is created the <br>moment we first assign a value to it.</p><blockquote># An integer assignment <br>age = 45 <br># A floating point <br>salary = 1456.8 <br># A string <br>name = “John”</blockquote><h4>Operators</h4><p>Operators are the main building block of any programming language. These operators can be categorized based upon their different functionality</p><p><strong>Arithmetic operators</strong> are used to perform mathematical operations like addition, subtraction, multiplication and division.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*6kJBBsYgu5ReQ9WPnT5jgw.png" /></figure><p><strong>Relational operators </strong>compare the values. It either returns True or False according to the condition.</p><blockquote><strong># Examples </strong><br>a = 13<br>b = 33<br>print(a &gt; b) <br> <strong>Output: </strong>False<br>print(a != b) <br><strong> Output: </strong>True</blockquote><p><strong>Logical operators</strong> perform Logical AND, Logical OR and Logical NOT operations.</p><blockquote><strong># Examples</strong><br>a = True<br>b = False<br>print(a and b)<br>print(a or b)<br>print(not a)<br><strong>Output:</strong><br>•False<br>•True<br>•False</blockquote><p><strong>Bitwise operator</strong> acts on bits and performs bit by bit operation.</p><blockquote><strong># Examples</strong> <br>a = 10<br>b = 4<br>print(a &amp; b) <strong>Output </strong>0<br>print(a | b) <strong>Output</strong> 14<br>print(~a) <strong>Output</strong> -11<br>print(a ^ b) <strong>Output </strong>14<br>print(a &gt;&gt; 1) <strong>Output</strong> 5<br>print(a &lt;&lt; 1) <strong>Output </strong>20</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*4HO6e36sNK156L8LiJhhjw.png" /></figure><p><strong>Assignment operators</strong> are used to assign values to the variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOZ6NULrG_ewxtbermAy3g.png" /></figure><p><strong>Special operators</strong></p><ul><li><strong>Identity operator </strong>that contains is and is not.</li></ul><blockquote><strong># Examples</strong><br>x = [1, 2, 3]<br>y = [1, 2, 3]<br># ‘is’ checks if both variables refer to the same object<br>print(x is y) <strong># False</strong><br># ‘is not’ checks if both variables do not refer to the same object<br>print(x is not y) <strong># True</strong></blockquote><ul><li><strong>Membership operator </strong>that contains in and not in.</li></ul><blockquote><strong># Examples</strong><br>fruits = [‘apple’, ‘banana’, ‘orange’]<br># ‘in’ checks if a value exists in the sequence<br>print(‘apple ‘ in fruits) <strong># True</strong><br># ‘not in’ checks if a value does not exist in<br>the sequence<br>print(‘grape’ not in fruits) <strong># True</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*3e3UDlYMEh9G26pJft0OSw.png" /></figure><h4><strong>Basics of Input/Output</strong></h4><p>Imagine a friendly conversation between your code and the user. Input/output is how they communicate, exchanging information back and forth.</p><p><strong>1. Print Statements: </strong>Your Code’s Voice</p><p>Use <strong>print() </strong>to display messages or results on the screen</p><p><strong>2. User Input: </strong>Listening to the User</p><p>Employ<strong> input()</strong> to gather information from the user</p><h4><strong>Data Types</strong></h4><p>Data types are like containers for information. They tell Python what kind of data you’re working with, so it knows how to handle it correctly. It’s like organizing your books, games, and clothes in separate shelves — each has its own space and purpose!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARi8uwMEwLogJerghFcxjQ.png" /></figure><p><strong>Numbers</strong></p><ul><li><strong>Integers (int): </strong>Whole numberswithout decimals.</li></ul><blockquote>42, -10, or 0.</blockquote><ul><li><strong>Floats (float):</strong> Numbers with decimals.</li></ul><blockquote>3.14, 1.5, or -0.001</blockquote><p><strong>Text</strong></p><ul><li><strong>Strings (str): </strong>Sequences of characters enclosed in quotes</li></ul><blockquote>“Hello, world!“</blockquote><p><strong>Booleans</strong></p><ul><li><strong>Booleans (bool): </strong>Represent True or False values. Great for making decisions and checking conditions!</li></ul><p><strong>Collections</strong></p><ul><li><strong>Lists (list):</strong> Ordered sequences of items,</li></ul><blockquote>[1, 2, 3] or [“apple”, “banana”, “cherry”]</blockquote><p>Perfect for storing collections of things!</p><ul><li><strong>Tuples (tuple):</strong> Similar to lists, but they’re immutable<br>(can’t be changed after creation).</li></ul><blockquote>(10, 20, 30)</blockquote><p>Useful for representing fixed sets of data!</p><ul><li><strong>Sets (set): </strong>Unordered collections of unique items.</li></ul><blockquote>{1, 2, 2, 3}</blockquote><p>Great for removing duplicates and checking membership!</p><ul><li><strong>Dictionaries (dict):</strong> Unordered collections of key-value pairs.</li></ul><blockquote>{“name”: “Alice”, “age”: 30}</blockquote><p>Perfect for storing information like phonebooks or product catalogs!</p><h3><strong>Control Flow</strong></h3><p>Imagine your code as an explorer on a quest. Control flow is the map that guides its path, deciding which routes to take based on different conditions and how many times to repeat certain actions.</p><h4><strong>1. Conditional Statements: Making Decisions</strong></h4><p><strong>“if” statements: </strong>Check a condition and execute code if it’s true.</p><blockquote>if temperature &gt; 25:<br> print(“It’s a hot day!”)</blockquote><p><strong>“else” statements:</strong> Provide an alternative path if the condition is false.</p><blockquote>if age &gt;= 18:<br> print(“You’re eligible to vote.”)<br>else:<br> print(“You’re not old enough to vote yet.”)</blockquote><p><strong>“elif” statements:</strong> Offer multiple possibilities for decision-making</p><blockquote>grade = 85<br>if grade &gt;= 90:<br> print(“Excellent!”)<br>elif grade &gt;= 80:<br> print(“Very good!”)<br>else:<br> print(“Keep working hard!”)</blockquote><h4>2. Looping Statements</h4><p><strong>“for” loops:</strong> Repeat code for each item in a sequence.</p><blockquote>friends = [“Alice”, “Bob”, “Charlie”]<br>for i in friends:<br> print(“Hello,”, i + “!”)</blockquote><p><strong>“while” loops: </strong>Easy to change colors, photos and Text.</p><blockquote>i= 0<br>while i&lt; 5:<br> print(i)<br> i += 1 # Increment count to avoid an infinite loop</blockquote><h3>Functions</h3><p>Imagine building a robot. Functions are like its modular parts — reusable blocks of code that perform specific tasks, making your code organized, efficient, and easy to maintain.</p><h4>1. Defining Functions:</h4><blockquote><strong>def function_name(parameters):</strong><br># Code to be executed<br> return output</blockquote><p><strong>Parameters: </strong>Inputs the function receives to customize its actions.<br><strong>Return values:</strong> Outputs that the function sends back to be used elsewhere.</p><h4>2. Calling Functions:</h4><blockquote><strong>result = function_name(arguments)</strong></blockquote><p><strong>Arguments: </strong>Actual values passed to the function, matching its parameters.</p><h4>3. Built-in Functions: Ready-to-use functions for common tasks:</h4><blockquote><strong>len(my_list):</strong> Returns the length of a list.<br><strong>sum(my_numbers): </strong>Calculates the sum of numbers in a list.<br><strong>print(my_message): </strong>Displays a message.<br>And many more!</blockquote><h4>4. User-Defined Functions: Creating custom functions for specific needs:</h4><blockquote><strong>def greet(name):</strong><br> print(“Hello,”, name + “!”)</blockquote><blockquote><strong>def calculate_area(length, width):</strong><br> area = length * width<br> return area</blockquote><h4>Benefits of Functions</h4><ul><li><strong>Modularity: </strong>Break down complex problems into smaller, manageable <br>chunks.</li><li><strong>Reusability: </strong>Use the same code multiple times without duplication.</li><li><strong>Abstraction:</strong> Hide implementation details and focus on the task at hand.</li><li><strong>Readability: </strong>Improve code clarity and understanding</li></ul><h3>Libraries</h3><p>Python libraries are collections of pre-written code that provide functionality to perform specific tasks. They enhance the capabilities of Python by providing ready-to-use modules and functions.</p><h4>Importing Libraries:</h4><p>Use the <strong>‘import’ </strong>keyword to bring a library into your Python script or Jupyter Notebook.</p><blockquote><strong>Common examples: </strong>‘import math’, ‘import numpy as np’, ‘import pandas as pd’.</blockquote><h4>Popular Python Libraries:</h4><p><strong>NumPy (Numerical Python)</strong> is a powerful Python library for working with numerical data. It provides support for large, multi-dimensional arrays and matrices, where elements must be of the same data type. <br>NumPy also includes a wide range of mathematical functions to operate on these arrays, including element-wise operations, linear algebra, and statistical operations.</p><p><strong>Pandas</strong> is a powerful data manipulation and analysis library for Python. <br>It provides data structures like Series and DataFrame that are designed to handle and analyze structured data efficiently.</p><p><strong>Matplotlib</strong> is a 2D plotting library for Python, which produces high-quality charts and figures, bringing your data to life. <br>It visualizes trends, patterns, and relationships to uncover insights.<br>Also it provides a wide variety of plotting options and customization features.</p><p><strong>Scikit-learn</strong> is a machine learning library for Python that provides simple and efficient tools for data analysis and modeling. It includes various algorithms for classification, regression, clustering, and more.</p><h3>Hands-On Activity</h3><h4><strong>Number Analysis</strong></h4><blockquote><strong><em>Goal </em></strong><em>is to create a simple program that analyzes a list of numbers.</em></blockquote><p><strong><em>create a list of numbers.</em></strong></p><pre>numbers = [12, 7, 15, 24, 10, 8, 16]</pre><p><strong><em>check whether the list is empty.</em></strong><em> If it is, print a message indicating that the list is empty. Otherwise, proceed with the analysis.</em></p><pre>if not numbers:<br>    print(&quot;The list is empty&quot;)<br>else:<br>    # Analysis</pre><p><em>Write a function named</em><strong><em> ‘find_maximum’ </em></strong><em>that takes a list of numbers as an argument and returns the maximum value in the list.</em></p><pre>def find_maximum(numbers):<br>    return max(numbers)</pre><p><em>Write another function named </em><strong><em>‘calculate_average’ </em></strong><em>that takes a list of numbers as an argument and returns the average (mean) of the numbers.</em></p><pre>def calculate_average(numbers):<br>    return sum(numbers) / len(numbers)</pre><p><strong><em>Perform Analysis</em></strong></p><pre>    max_value = find_maximum(numbers)<br>    average_value = calculate_average(numbers)<br><br>    print(&quot;Maximum value in the list:&quot;, max_value)<br>    print(&quot;Average of the numbers:&quot;, average_value)</pre><p><strong>Rock, Paper, Scissors Game in Python:</strong></p><blockquote><strong><em>Goal:</em></strong><em> Create a fun and interactive game where you play against the computer, choosing between Rock, Paper, and Scissors!</em></blockquote><p><strong><em>Import the random library:</em></strong></p><pre>import random</pre><p><strong><em>Define game options:</em></strong></p><pre> options = [&#39;Rock&#39;, &#39;Paper&#39;, &#39;Scissors&#39;]</pre><p><strong><em>Get user input:</em></strong></p><pre>user_choice = input(&quot;Enter your choice (Rock/Paper/Scissors): &quot;).capitalize()</pre><p><strong><em>Generate computer choice:</em></strong></p><pre>computer_choice = random.choice(options)</pre><p><strong><em>Determine the winner:</em></strong></p><pre>if user_choice == computer_choice:<br>        result = &quot;It&#39;s a tie!&quot;<br>    elif (user_choice == &#39;Rock&#39; and computer_choice == &#39;Scissors&#39;) or \<br>         (user_choice == &#39;Paper&#39; and computer_choice == &#39;Rock&#39;) or \<br>         (user_choice == &#39;Scissors&#39; and computer_choice == &#39;Paper&#39;):<br>        result = &quot;You win!&quot;<br>    else:<br>        result = &quot;Computer wins!&quot;</pre><p><strong><em>Print the results:</em></strong></p><pre>print(&quot;Your choice:&quot;, user_choice)<br>print(&quot;Computer&#39;s choice:&quot;, computer_choice)<br>print(result)</pre><p><strong>Calculates the factorial of a given number using both types of loops.</strong></p><blockquote><em>for loop</em></blockquote><pre>def factorial_for_loop(n):<br>    result = 1<br>    for i in range(1, n + 1):<br>        result *= i<br>    return result</pre><blockquote><em>while loop</em></blockquote><pre>def factorial_while_loop(n):<br>    result = 1<br>    while n &gt; 1:<br>        result *= n<br>        n -= 1<br>    return result</pre><h3>Conclusion</h3><p>Delving into the fundamental aspects of Python sets a rigid basis for any aspiring programmer. Through this journey, we have explored key concepts such as data types as well as control flow, functions, and libraries, all of which form the anchorperson of Python programming.</p><p>By mastering these fundamentals, you not only gained a deeper understanding of Python syntax and deictic but also acquired the base skills needed to guarantee more compound projects with confidence. Remember, work and experiment are important in solidifying your understanding as well as so keep coding and exploring the vast possibilities that Python has to offer.</p><h4>Happy coding!.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e15d4a6a900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Docker and Kubernetes: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@hasfatauil12/getting-started-with-docker-and-kubernetes-a-step-by-step-guide-61a0c1d101b2?source=rss-151fc28d0829------2</link>
            <guid isPermaLink="false">https://medium.com/p/61a0c1d101b2</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[os]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[TAUIL Hafsa]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 23:07:59 GMT</pubDate>
            <atom:updated>2024-07-16T18:40:28.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQfia2ozYplUmvt41maW3g.jpeg" /></figure><p>In today’s rapidly evolving commercial landscape, as well as Docker and Kubernetes have emerged as important tools in the realm of parcel growing and deployment.</p><h3>Brief Overview of Docker and Kubernetes</h3><p><strong>Docker </strong>revolutionized the way we package, distributed,’ and run applications by introducing containerization.<br>With Docker as well as developers could capsulize their applications and all their dependencies into lightweight, take away containers that could run systematically crossway single environments, from growing to production.</p><p><strong>Kubernetes</strong>, on the other hand, takes containerization to the next level by providing a right instrumentation platform.<br>It automates the deployment,’ scaling, and direction of containerized applications, offering features like mechanical load balancing, self healing, and rolling updates. Kubernetes abstracts away the complexness of managing infrastructure, allowing teams to focus on building and shipping software.</p><h3>Importance of Containerization and Orchestration in Modern Software Development</h3><p>Containerization and instrumentation are important in modern day parcel growing for single key reasons;</p><blockquote><strong>Portability:</strong> Containers boxful an coating and its dependencies, ensuring consistence crossway single environments and reducing compatibility issues.</blockquote><blockquote><strong>Scalability:</strong> Platforms like Kubernetes enable broadloom scaling of applications based on demand,’ optimizing executing and resourcefulness usage.</blockquote><blockquote><strong>Reliability:</strong> Container instrumentation frameworks heighten coating dependableness with features like mechanical restarts and self healing, minimizing downtime.</blockquote><blockquote><strong>Efficiency: </strong>Standardizing growing and deployment processes streamlines workflows, allowing teams to focus on coding while improving basis direction efficiency.</blockquote><h3>Understanding Docker and Containerization</h3><p>Docker simplifies coating deployment by packaging parcel and its dependencies into standardized units called containers. These containers can run on any system,’ ensuring uniform behavior crossway clear cut environments.</p><p><strong>Docker architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tjpTsAUCzKRL3cfSnB8KA.png" /></figure><h3><strong>Installing Docker</strong></h3><ol><li><strong>Updating Package Index</strong></li></ol><blockquote>`sudo apt update`</blockquote><p><strong>2. Installing Dependencies</strong></p><blockquote>`sudo apt install apt-transport-https ca-certificates curl software-properties-common`</blockquote><p><strong>3. Adding Docker’s Official GPG Key</strong></p><blockquote>```<br> curl -fsSL <a href="https://download.docker.com/linux/ubuntu/gpg">https://download.docker.com/linux/ubuntu/gpg</a> | sudo apt-key add -<br> ```</blockquote><p><strong>4. Configuring Docker Repository</strong></p><blockquote>```<br> sudo add-apt-repository “deb [arch=amd64] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> $(lsb_release -cs) stable”<br> ```</blockquote><p><strong>5. Installing Docker Engine</strong></p><blockquote>`sudo apt install docker-ce`</blockquote><p><strong>6. Verifying the Installation</strong></p><blockquote>`docker — version` <strong>(To check Docker Engine version)<br></strong>`sudo systemctl status docker` <strong>(To check Docker service status)</strong></blockquote><h3>Understanding Kubernetes and Its Architecture</h3><p>Kubernetes is a right container instrumentation choline that automates the deployment, scaling,’ and direction of containerized applications.<br>Its architecture consists of a master node that controls the cluster and worker nodes where containers are deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCqX-4WIm8T--apASyIQag.png" /></figure><h3><strong>Installing Kubernetes</strong></h3><ol><li><strong>Adding Kubernetes Repository and Key</strong></li></ol><blockquote>```<br> sudo apt-get update &amp;&amp; sudo apt-get install -y apt-transport-https curl<br> curl -s <a href="https://packages.cloud.google.com/apt/doc/apt-key.gpg">https://packages.cloud.google.com/apt/doc/apt-key.gpg</a> | sudo apt-key add -<br> ```</blockquote><p><strong>2. Adding Kubernetes Repository</strong></p><blockquote>```<br> echo “deb <a href="https://apt.kubernetes.io/">https://apt.kubernetes.io/</a> kubernetes-xenial main” | sudo tee /etc/apt/sources.list.d/kubernetes.list<br> ```</blockquote><p><strong>3. Updating Package Index</strong></p><blockquote>`sudo apt-get update`</blockquote><p><strong>4. Installing Kubernetes Tools</strong></p><blockquote>```<br> sudo apt-get install -y kubelet kubeadm kubectl<br> ```</blockquote><p><strong>5. Preventing Automatic Updates</strong></p><blockquote>```<br> sudo apt-mark hold kubelet kubeadm kubectl<br> ```</blockquote><p><strong>6. Verifying the Installation</strong></p><blockquote>`kubectl version — client` <strong>(To check Kubernetes client version)</strong></blockquote><blockquote>`kubeadm version` <strong>(To check Kubeadm version)</strong></blockquote><h3>Harnessing Docker and Kubernetes for Application Containerization, Deployment, and Management</h3><h4>1. Creating and Containerizing Applications (CALCULATOR/NODE.JS)</h4><p><strong>**Creating the First Application (CALCULATOR)**</strong><br> — Develop a basic calculator application using HTML, CSS, and JavaScript.</p><p><strong>**Creating the Second Application (NODE.JS)**</strong><br> — Write a simple Node.js application that performs a specific task or displays information.</p><p><strong>**Displaying the First Application (CALCULATOR)**</strong><br> — Set up a local server or hosting environment to display the calculator application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*LOjpoOt3NsW65jL8PhmVmg.png" /></figure><p><strong>**Displaying the Second Application (NODE.JS)**</strong><br> — Configure a web server or hosting environment to serve the Node.js application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*tDVg4XdSgOgvEsjhF2rRmQ.png" /></figure><p><strong>**Containerizing the First Application (CALCULATOR)**</strong></p><blockquote><strong>— Create a Dockerfile: </strong>A Dockerfile is a text document that contains all the commands needed to assemble an image.<br> ```Dockerfile<br> # Dockerfile for calculator application<br> FROM nginx:latest<br> COPY . /usr/share/nginx/html<br> ```</blockquote><blockquote><strong>— Build the Docker image:</strong><br> ```<br> docker build -t calculator-app .<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjcB9xV06wkhuEvLKNmw6w.png" /></figure><blockquote><strong>— Verify the image:</strong><br> ```<br> docker images<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ig17UQbEWxxVnbnJ5ujTwg.png" /></figure><blockquote><strong>— Run the Docker container:</strong><br> ```<br> docker run -d -p 8080:80 calculator-app<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlXr4PNKrKrKlhgsmD0uGw.png" /></figure><blockquote><strong>— Verify the container:<br></strong> ```<br> docker ps<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ahPB3F7GIn_CGmJDHhmBFw.png" /></figure><h4>2. Configuring the Kubernetes Cluster and Deploying Containers as Pods in the Cluster</h4><p><strong>**Understanding Docker Hub**</strong><br> — Docker Hub is a cloud-based repository that allows you to store and share Docker images publicly or privately.<br><strong>**Deployment to Docker Hub**</strong></p><blockquote><strong>— Register at </strong><a href="https://hub.docker.com/"><strong>https://hub.docker.com</strong></a></blockquote><blockquote><strong>— Connect to Docker Hub:</strong><br> ```<br> docker login<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJSEsTmF72XNhQ-33zt_vw.png" /></figure><blockquote><strong>— Tag the Docker image:</strong><br> ```<br>docker tag &lt;image-id&gt; &lt;your-docker-username&gt;/&lt;image-name&gt;:&lt;tag&gt;<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLxchmwpowF2kxCntiwY6g.png" /></figure><blockquote><strong>— Push the image to Docker Hub:</strong><br> ```<br>docker push &lt;your-docker-username&gt;/&lt;image-name&gt;<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*WQcxQ8EDc5kksz-yfofsLw.png" /></figure><blockquote><strong>— Verification:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWuxEeCHEK8GQ8XKAEYLPQ.png" /></figure><p><strong>**Setting Up Minikube**</strong><br> — Minikube is a tool that enables you to run Kubernetes locally on your machine for development and testing purposes.</p><p><strong>**YAML Configuration**</strong><br> — YAML (YAML Ain’t Markup Language) is a human-readable data serialization format used for configuration files in Kubernetes.<br>The Kubernetes configuration file is the primary tool for creating and configuring components in a Kubernetes cluster. <br>To deploy an application, we need both a deployment and a service. The deployment manages the pods of our application, ensuring they run as desired, while the service provides network access to these pods. Each configuration file in Kubernetes has three parts. <br>- The first part is where the metadata of this component resides. One of the metadata is the name of the component itself. <br>- The second part in the configuration file is the specification; where we essentially put all types of configurations we want to apply to this component. <br>- For the third part in the configuration file, it’s the status. The status is generated and added automatically by Kubernetes.<br>The first two lines simply declare what we want to create (deployment or service) and each has a different API version.</p><p>=&gt;<strong>YAML Configuration for the first application (CALCULATOR):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*n6EKorAqwCf_9zlt0dlfDg.png" /></figure><p>=&gt;<strong>YAML Configuration for the second application (NODE.JS):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*BgtyfY7g3R_YKH765LGlDw.png" /></figure><p><strong>**Applying YAML Configurations**</strong><br> — Apply the YAML configurations to deploy containers as pods in the Kubernetes cluster:</p><blockquote>```<br> kubectl apply -f deployment.yaml<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlqtdtYHawjtc-zoiXJ59w.png" /></figure><h4>3. Managing and Orchestrating Containerized Applications with Kubernetes</h4><p><strong>**Checking Deployment Status**</strong><br> — Verify the status of deployments in Kubernetes:</p><blockquote>```<br> kubectl get deployments<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*nGAwgdUzrmjyNc7bwirJ7g.png" /></figure><p><strong>**Checking Service Status**</strong><br> — Ensure the status of services deployed in Kubernetes:</p><blockquote>```<br> kubectl get services<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*F1R9aeMGjErsi_OOXm22Lg.png" /></figure><p><strong>*Getting Pod Information**</strong><br> — Retrieve information about pods running in the cluster:</p><blockquote>```<br> kubectl get pods<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*aMNTOd_6sNgKRkyHlntVOw.png" /></figure><p><strong>**Viewing Details of Specific Deployments or Services**</strong><br> — Access detailed information about particular deployments or services:</p><blockquote>```<br> kubectl describe deployment &lt;deployment-name&gt;<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*xrKTYtXMyIt77JEyFeVN_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jT933MxzJx1kSUVYn0CNw.png" /></figure><p><strong>**Scaling a Deployment**</strong><br> — Scale up or down the number of replicas for a deployment:</p><blockquote>```<br> kubectl scale deployment &lt;deployment-name&gt; — replicas=&lt;number-of-replicas&gt;<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHkPzASBAKfGZ9IvJ3w4gg.png" /></figure><p>=&gt;Here we changed the number of replicas to 5<br><strong>**Viewing Container Logs in a Pod**</strong><br> — Check the logs of containers within a pod:</p><blockquote>```<br> kubectl logs &lt;pod-name&gt;<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svQw9NF6kpExYkEEO8kdgw.png" /></figure><p><strong>**Executing a Command Inside a Container**</strong><br> — Run a command inside a container for troubleshooting or debugging:</p><blockquote>```<br> kubectl exec -it &lt;pod-name&gt; — &lt;command&gt;<br> ```</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*OY07f8uuUmFBmAj-abcHCQ.png" /><figcaption>N.B: The command `ls /` displays the contents of the root directory of the container within the pod.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*aHRSVtFBeAP1FEVMrBHeig.png" /><figcaption>N.B: The command `ls ..` displays the contents of the parent directory of the current directory inside the container within the pod.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*85mc0ALHEhArhKxPxNS8oQ.png" /><figcaption>N.B: This command will display the environment variables within the specified pod.</figcaption></figure><p><strong>**Deleting a Deployment or Service**</strong><br> — Remove a deployment or service from the Kubernetes cluster when no longer needed:</p><blockquote>```<br> kubectl delete deployment &lt;deployment-name&gt;<br> kubectl delete service &lt;service-name&gt;<br> ```</blockquote><h3>Conclusion:</h3><p>In the realm of modern day parcel development, Docker and Kubernetes have emerged as important tools. Docker simplifies coating packaging and distribution, ensuring consistence crossway single environments.</p><p>Meanwhile, Kubernetes automates deployment and direction tasks, providing scalability and resilience.</p><p>Mastering Docker and Kubernetes streamlines growing workflows and enhances coating reliability.</p><p>These tools adorn teams to meet the challenges of today is fast paced commercial landscapist with efficiency and agility. As you keep your trip with Docker and Kubernetes as well as covering the uninterrupted possibilities they offer for shaping the rising of parcel development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61a0c1d101b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>