<?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 Ashwin Shekhar on Medium]]></title>
        <description><![CDATA[Stories by Ashwin Shekhar on Medium]]></description>
        <link>https://medium.com/@ashwin_68285?source=rss-21ab527e5454------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4QCUh5wWvcu3IYiMxuO_cQ.png</url>
            <title>Stories by Ashwin Shekhar on Medium</title>
            <link>https://medium.com/@ashwin_68285?source=rss-21ab527e5454------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:42:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashwin_68285/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[I fine-tuned Llama 3 on a single GPU (with help)]]></title>
            <link>https://medium.com/@ashwin_68285/i-fine-tuned-llama-3-on-a-single-gpu-with-help-2dc9fe9f01a8?source=rss-21ab527e5454------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dc9fe9f01a8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[fine-tuning-llm]]></category>
            <category><![CDATA[unsloth]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Ashwin Shekhar]]></dc:creator>
            <pubDate>Fri, 31 May 2024 07:26:19 GMT</pubDate>
            <atom:updated>2024-06-06T03:24:25.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-Kz6wOpYO285_zRtS6SXA.png" /><figcaption>generated by Midjourney</figcaption></figure><p>Large language models (LLMs) are currently very popular in the AI field. General models like OpenAI’s GPT, Gemini, and Anthropic are being widely used and are highly effective for various tasks. More than often, crafting clever prompts is enough to get good results from these models. However, as we start using these models for more specialized and demanding tasks in real-world applications, simply using clever prompts might not be enough. This is where fine-tuning becomes important. Fine-tuning allows us to customize these models to meet specific needs and improve their performance for particular tasks or to respond “better” or more “accurately”.</p><h4>Why do we need to fine-tune?</h4><p>In my own work I have come across a couple of cases where the model responses are not what we “wanted to see”. For example:</p><ol><li>Market Segmentation: Fine tuning of models can craft different types of responses to different segments of markets and customers allowing for a more personalised feel to the response.</li><li>Language and Dialects: Fine tuning can help us tune models so that it understands dialects or slang and respond in kind.</li><li>Specific Domain: We can fine tune models to understand a specific domain that it may not understand all that well such as specific details regarding music products.</li></ol><p>The step by step guide should allow anyone with some understanding of python coding to simply just run the code and see it working.</p><p>Please note that there are terms that will be used in this articles that you may not initially understand but there are excellent references and resources at the end of the article that explain these concepts in more detail.</p><h4><strong>Step 1: Choice</strong></h4><p>Step 1 is to understand the use case and then pick a pre-trained (or what is known as a foundation model) that best aligns to your chosen requirements. For this demonstration we decided to train a relatively small but powerful LLM to be able to follow specific instructions.</p><p>We chose LLama 3–8B (the 8B parameter model) as this was good enough for this demonstration. We also used a pre-prepared data set that aligns to this model and to our use case.</p><h4><strong>Step 2: Download the model (and tokenizer)</strong></h4><pre>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/llama-3-8b-bnb-4bit&quot;,<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit)</pre><p>The <strong>FastLanguageModel </strong>from <strong>Unsloth </strong>is a library that retrieves a specific pretrained model and tokenizer from the <strong>HuggingFace </strong>repository. A lot of the code here can be seen as replicated from the <strong>Unsloth </strong>codebase which you can see by clicking on the link the references section. Using this code base was a huge help and took care of a lot of the “magic” (as described later) with respect to training on single GPU. I strongly recommend having a look at <strong>Unsloth.</strong></p><h4><strong>Step 3: Prepare the data</strong></h4><pre>#load the dataset that we are going to use to finetune (publicly available on HuggingFace)<br>from datasets import load_dataset<br>dataset = load_dataset(&quot;yahma/alpaca-cleaned&quot;, split = &quot;train&quot;)</pre><p>The dataset loaded from <strong>HuggingFace </strong>is a high quality instructional dataset that we don’t need to do any “cleaning up “ on originally released by <strong>Stanford:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*tpXBRlfmRBhQZK3yhqzMzA.png" /><figcaption>Alpaca Cleaned Dataset example</figcaption></figure><p>So basically we are going to fine-tune the model so that it can follow instructions.</p><h4>Step 4: Model Understanding</h4><p>First lets understand the model that we will use. We use the <strong>unsloth/llama-3–8b-bnb-4bit. </strong>This model is the llama3 8 billion parameter model which has been quantized to 4bit.</p><p><strong>Quantization </strong>to 4-bit involves reducing the precision of model parameters to just 16 possible values (0–15), which significantly decreases memory usage and speeds up computations. While this can impact the quality of the model’s output due to the reduced precision, not all calculations are performed in 4-bit. Higher precision formats like 32-bit or 16-bit are still used for critical computations to balance performance and accura</p><p>We also set the max_seq_length to the maximum length of the data. In this case this doesn’t matter too much as this model uses Rotary Position Embedding (<strong>RoPE).</strong></p><p>The above is a just a couple of quick statements around Quantization and RoPE but there are better resources at the end of this article.</p><p>To get the length of the sequence we create a prompt for the llm based on the data:</p><pre>alpaca_prompt = &quot;&quot;&quot;Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.<br><br>### Instruction:<br>{}<br><br>### Input:<br>{}<br><br>### Response:<br>{}&quot;&quot;&quot;</pre><p>Using the above prompt we can encode each data item from the dataset to look like the following (as an example):</p><pre>Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.<br><br>### Instruction:<br>Give three tips for staying healthy.<br><br>### Input:<br><br><br>### Response:<br>1. Eat a balanced and nutritious diet: Make sure your meals are inclusive of a variety of fruits and vegetables, lean protein, whole grains, and healthy fats. This helps to provide your body with the essential nutrients to function at its best and can help prevent chronic diseases.<br><br>2. Engage in regular physical activity: Exercise is crucial for maintaining strong bones, muscles, and cardiovascular health. Aim for at least 150 minutes of moderate aerobic exercise or 75 minutes of vigorous exercise each week.<br><br>3. Get enough sleep: Getting enough quality sleep is crucial for physical and mental well-being. It helps to regulate mood, improve cognitive function, and supports healthy growth and immune function. Aim for 7-9 hours of sleep each night.&lt;|end_of_text|&gt;<br>Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.<br><br>### Instruction:<br>Generate a list of random words.<br><br>### Input:<br><br><br>### Response:<br>Here is a list of ten random words: <br><br>1. Quibble<br>2. Avarice<br>3. Embellish<br>4. Resonance<br>5. Mercurial<br>6. Conflagration<br>7. Indefatigable<br>8. Mischievous<br>9. Delineate<br>10. Paragon&lt;|end_of_text|&gt;</pre><pre>import pandas as pd<br><br>df = pd.DataFrame(dataset)<br><br># Calculate the maximum length of a specific column<br>max_length = df[&quot;text&quot;].apply(len).max()<br><br># Print out the result<br>print(f&quot;The maximum length of the text or prompt column is: {max_length}&quot;)</pre><p>From this we found the maximum length to be ~5200 and we can then set the maximum length accordingly. Again it doesn’t matter too much but I prefer to be data driven.</p><h4>Step 5: (Optional) — Test the model</h4><p>Before we start tuning lets just pass a request into the loaded base model and see what happens. Remember that the model needs to be asked as per the prompt and needs to be tokenized as these models don’t understand letters but numbers.</p><pre>FastLanguageModel.for_inference(model=model)<br>inputs = tokenizer(<br>    [<br>        alpaca_prompt.format(&quot;List the top 10 movies of 2016&quot;, &quot;&quot;, &quot;&quot;)<br>    ], return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>out = model.generate(**inputs, max_new_tokens=256, use_cache=True)<br>tokenizer.batch_decode(out)<br></pre><p>And the output is:</p><p><em>&lt;|begin_of_text|&gt;Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\nList the top 10 movies of 2016\n\n### Input:\n\n\n### Response:\nSELECT * FROM movies WHERE year = 2016 ORDER BY rating DESC LIMIT 10\n&lt;|end_of_text|&gt;</em></p><p>Not very useful as its trying to create an sql based on my request.</p><h4><strong>Step 6: Setup for Tuning</strong></h4><p>The first step here is part of the “magic” that allows us to tune such a large model on a single GPU. We use a technique that is know as Low-Rank Adaption (<strong>LoRA). </strong>LoRA is a technique that fine-tunes large models by learning and adding low-rank matrices to the existing weights. This means that instead of adjusting the entire model, LoRA only adjusts smaller additional matrices, saving time and computational resources. By applying this change to just a subset of the model, LoRA ensures that fine-tuning remains efficient while still being effective.</p><p>Combining both Quantization and LoRA gives a tuning mechanism commonly known as <strong>QLoRA</strong>. Again for a deeper understanding a great set of references and resources has been added to the end of the article.</p><p>We have to wrap the base model using <strong>HuggingFace’s </strong>state of the art <strong>Parameter Effecient Fine-Tuning (PEFT)</strong> library.</p><pre>model = FastLanguageModel.get_peft_model(<br>     model,<br>     r = 16, # Choose any number &gt; 0 ! Suggested 8, 16, 32, 64, 128<br>     target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,<br>                       &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;,],<br>     lora_alpha = 16,<br>     lora_dropout = 0, # Supports any, but = 0 is optimized<br>     bias = &quot;none&quot;,    # Supports any, but = &quot;none&quot; is optimized<br>     # [NEW] &quot;unsloth&quot; uses 30% less VRAM, fits 2x larger batch sizes!<br>     use_gradient_checkpointing = &quot;unsloth&quot;, # True or &quot;unsloth&quot; for very long context<br>     random_state = 3407,<br>     use_rslora = False,  # We support rank stabilized LoRA<br>     loftq_config = None, # And LoftQ<br>)</pre><p>The <strong>rank (r)</strong> hyper-parameter, which defines the rank/dimension of the adapter to be trained.</p><p><strong>lora_alpha</strong>: Can be considered to be like a learning rate.</p><p><strong>target_modules: </strong>We don’t need to train the entire model and thus adjust all the parameters but can adjust a subset of the models. The modules specified here are the layers where we will use LoRA as per the original model specification.</p><p>After implementing this we can see how small the trainable parameters have become:</p><pre>model.print_trainable_parameters()</pre><p>trainable params: 41,943,040 || all params: 8,072,204,288 |<strong><em>| trainable%: 0.5195983464188562</em></strong></p><p>This shows that from 8 Billion parameters we will only be training (tuning) ~ 0.52%</p><h4>Step 7: Setup Trainer</h4><p>Now we attach the trainer. The trainer will take the model and initialise the model and add the required hyper parameters needed for the training process:</p><pre>from trl import SFTTrainer<br>from transformers import TrainingArguments<br><br>trainer = SFTTrainer(<br>    model = model,<br>    tokenizer = tokenizer,<br>    train_dataset = dataset,<br>    dataset_text_field = &quot;text&quot;,<br>    max_seq_length = max_seq_length,<br>    dataset_num_proc = 2,<br>    packing = False, # Can make training 5x faster for short sequences.<br>    args = TrainingArguments(<br>        per_device_train_batch_size = 2,<br>        gradient_accumulation_steps = 4,<br>        warmup_steps = 5,<br>        max_steps = 60,<br>        learning_rate = 2e-4,<br>        fp16 = not torch.cuda.is_bf16_supported(),<br>        bf16 = torch.cuda.is_bf16_supported(),<br>        logging_steps = 1,<br>        optim = &quot;adamw_8bit&quot;,<br>        weight_decay = 0.01,<br>        lr_scheduler_type = &quot;linear&quot;,<br>        seed = 3407,<br>        output_dir = &quot;outputs&quot;,<br>    ),</pre><p>The trainer we the use is Supervised Fine Tuning Trainer (or <strong>SFTTrainer</strong>). The standard hyper parameters are added to this via the <strong>TrainingArguments. </strong>The above code shows the hyperparameters I used for this tuning process (you can of course experiment with your own values).</p><h4>Step 8: Fine Tuning</h4><p>We start the training process now that everything is set up:</p><pre>trainer_stats = trainer.train() </pre><p>For this particular demonstration we have used a Colab provided GPU (L4). We can see that something (hopefully) is happening:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_scp76NZpDxdtyIQl8KYDQ.png" /><figcaption>Training Progress</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*zH45evjoRnNUI6RpjgIr-g.png" /><figcaption>GPU Usage</figcaption></figure><p>This will take a bit of time based on your GPU but nowhere near the time taken if we hadn’t used QLoRA. We can also print the training stats:</p><pre>print(trainer_stats)</pre><p>TrainOutput(global_step=60, training_loss=1.0685642500718435, metrics={‘train_runtime’: 232.9986, ‘train_samples_per_second’: 2.06, ‘train_steps_per_second’: 0.258, ‘total_flos’: 5726714157219840.0, ‘train_loss’: 1.0685642500718435, ‘epoch’: 0.00927357032457496})</p><p>So now we have a tuned model.</p><h4>Step 9: Testing</h4><p>We first saved the model to our <strong>HuggingFace </strong>repository and then reloaded it. I then asked the same question about the best movies of 2016 (remember previously it gave us a pretty useless output). The code below “asks” the model the question:</p><pre>FastLanguageModel.for_inference(model=instruct_saved_model)<br>inputs = instruct_saved_tokenizer(<br>    [<br>        alpaca_prompt.format(&quot;List the top 10 movies of 2016&quot;, &quot;&quot;, &quot;&quot;)<br>    ], return_tensors=&quot;pt&quot;).to(&quot;cuda&quot;)<br><br>out = instruct_saved_model.generate(**inputs, max_new_tokens=256, use_cache=True)<br>instruct_saved_tokenizer.batch_decode(out)</pre><p>We ask in the same way as before and this time the output is <strong>very</strong> different:</p><p>&lt;|begin_of_text|&gt;Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\nList the top 10 movies of 2016\n\n### Input:\n\n\n### Response:\n1. La La Land\n2. Moonlight\n3. Arrival\n4. Hidden Figures\n5. Rogue One: A Star Wars Story\n6. Manchester by the Sea\n7. Hacksaw Ridge\n8. Lion\n9. Fences\n10. Silence</p><p>That looks much better!</p><h4>Conclusion</h4><p>As we can see that by simply tuning an LLM we can change the way that the LLM behaves. We can also use help from libraries that allow us to take advantages of “tricks” (such as quantization, and low rank adaptors) to make the tuning more accessible for those of us who do not have millions of dollars worth of hardware. Be sure to have a read of the references and watch the videos below as they are great resources to get a deeper understanding of the concepts.</p><h4>The code</h4><p>The working code:</p><p><a href="https://gist.github.com/ashwin-vx/3979356ccc8d01ba122e784469255118">https://gist.github.com/ashwin-vx/3979356ccc8d01ba122e784469255118</a></p><h4>References and Useful Information</h4><p><strong>Attention Is All You Need: </strong><a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></p><p><strong>Unsloth.ai: </strong><a href="https://github.com/unslothai/unsloth">https://github.com/unslothai/unsloth</a></p><p><strong>RoPE (Rotary positional embeddings) explained: The positional workhorse of modern LLMs: </strong><a href="https://www.youtube.com/watch?v=GQPOtyITy54">https://www.youtube.com/watch?v=GQPOtyITy54</a></p><p><strong>RoFormer: Enhanced Transformer with Rotary Position Embedding:</strong> <a href="https://arxiv.org/abs/2104.09864">https://arxiv.org/abs/2104.09864</a></p><p><strong>Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference:</strong> <a href="https://arxiv.org/abs/1712.05877">https://arxiv.org/abs/1712.05877</a></p><p><strong>Low-Rank Adaptation of Large Language Models: </strong><a href="https://arxiv.org/abs/2106.09685%60">https://arxiv.org/abs/2106.09685`</a></p><p><strong>QLoRA paper explained (Efficient Finetuning of Quantized LLMs): </strong><a href="https://www.youtube.com/watch?v=6l8GZDPbFn8">https://www.youtube.com/watch?v=6l8GZDPbFn8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dc9fe9f01a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Duality of AI: A Fine Balance]]></title>
            <link>https://medium.com/@ashwin_68285/the-duality-of-ai-a-fine-balance-d15b12a04edd?source=rss-21ab527e5454------2</link>
            <guid isPermaLink="false">https://medium.com/p/d15b12a04edd</guid>
            <category><![CDATA[ai-ethics]]></category>
            <category><![CDATA[ai-evolution]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Ashwin Shekhar]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 01:11:15 GMT</pubDate>
            <atom:updated>2023-07-28T01:11:15.570Z</atom:updated>
            <content:encoded><![CDATA[<p>The duality of artificial intelligence (AI) demands the acknowledgement of the fear surrounding its potential risks while embracing the vast opportunities it presents for transformative progress and positive impact on society. The key is not to dismiss AI based on the fears or blindly embrace it due to opportunties, but to to strike a (fine) balance. As we delve deeper into AI’s complexities, we must constantly question and strike a balance between caution and innovation to shape a responsible and ethically-driven future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPbZ4a9OHlKRwJwKQjBO1A.png" /><figcaption>Made with MIdjourney</figcaption></figure><p>There is no denying that we have shrugged off the curse of the past winters of Artificial Intelligence (AI) and are now on the cusp of a new and promising era of AI. Amplified by the recent surge in Generative AI(a type of AI that creates new content based on patterns it has learned using data ), we are now witnessing a constant inundation of news showcasing the remarkable disruptions caused by Artificial Intelligence. From cutting-edge advancements to ground-breaking applications, AI’s relentless momentum is reshaping the world we know. However, alongside the excitement, loom fears of job losses, ethical dilemmas and even the idea of AI taking over the world (and so many more). Let’s navigate this duality of AI — balancing its potential to drive human evolution to the next stage while addressing the genuine concerns it raises.</p><p>In just a few years, AI and generative AI technology have achieved incredible feats once considered impossible. ChatGPT surpassed the bar exam for human lawyers, now reaching top 10 percentile scores with GPT-4. Meanwhile, GitHub’s Copilot functionality significantly accelerates development and boosts functional accuracy with its code-writing assistance. Moreover, AI’s potential in healthcare is evident through disease detection, with health professionals using AI to identify dangerous illnesses like prostate or breast cancer whilst eliminating the need for invasive and costly procedures and possibly even removing human error from such vital diagnoses. Companies like Babylon Health exemplify how generative AI is revolutionizing healthcare, offering scalable and AI-based diagnosis and healthcare services. These examples highlight AI’s remarkable power and the vast possibilities it holds, with countless more promising applications that can be readily found through a quick Google search.</p><p>Amidst the promises and abundant opportunities, a pertinent question arises: What are the potential negative impacts of AI? Among the concerns, job displacement remains a significant worry for many. Other examples such as its effects on learning and human interaction should also be pondered. Ethical concerns further come to the forefront, raising questions about how data is used, the bias in algorithms, and the ethical use of AI in decision-making processes. Are these fears justified, or do they echo the sentiment of the modern-day Luddite? Let’s look further and explore its potential drawbacks alongside its advancements.</p><p>I recently discovered that due to the advancement of generative AI we will be getting a new and “last” Beatles song with AI recreating the voice of John Lennon. If that is the case then will there ever be a “last” Beatles song? As AI technology progresses, it holds the potential to carry forward the Beatles’ legacy long after they and we are gone, generating new lyrics and melodies. The technologist in me is excited to see the possibilities and the music lover in me is looking forward to a “new” Beatles song. As we contemplate the future of creativity in the age of AI, a pressing question emerges: Are we heading down a path of “outsourcing” creativity? Alternatively, could the inventive application of this technology open doors to new realms of creativity? Take for example AI being used to bring Elvis back to sing the “timeless classic” — Baby Got Back by Sir Mix-a-Lot<a href="https://www.youtube.com/watch?v=MINwa4_BVsY"> </a>The AI generated rendition sounds surprisingly good making it highly plausible to sway the uninitiated into believing it’s a genuine Elvis song.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMINwa4_BVsY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMINwa4_BVsY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMINwa4_BVsY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f60dd061322d1ba84f46a175b799ff/href">https://medium.com/media/a4f60dd061322d1ba84f46a175b799ff/href</a></iframe><p>Today, GPT-based tools serve as invaluable aids in various work tasks. Software engineers leverage them to boost productivity by writing code and documentation, while others find assistance in transcribing meeting notes and composing professional emails. This allows the engineer to focus on more critical tasks and creative tasks and not spend time on the mundane. The use of AI in the workplace can evoke contrasting perspectives: some view it as potentially unethical to outsource tasks to technology, while others embrace it as a creative tool for everyday life.</p><p>This leads us to a crucial question and a pertinent fear: Will AI render certain jobs obsolete? It’s a valid and pressing concern that warrants analysis. Drawing lessons from history, we’ve witnessed technology introductions causing workforce disruptions before. However, in many cases, jobs were not obliterated but rather redefined and reallocated. The advent of computers, for instance, fostered demand for computer-literate professionals, thus creating new opportunities. As for AI’s impact, the answer is not as simple.</p><p>The apprehension about AI-related job losses is most pronounced in roles with repetitive tasks and limited decision-making, like data entry and customer service positions. As AI adoption increases, impacted employees will need to up-skill or explore new fields and roles to adapt to the changing job landscape. The potential for AI to take over jobs is also evident in the entertainment industry. The current Screen Actors Guild-American Federation of Television and Radio Artists strike, is seeking protection for actors against AI-related job displacement. However, it is clear that more AI adoption across various roles and industries can present potential cost reductions and a reduction in human errors and can also brings forth opportunities for new jobs in areas such as data analysis and machine learning or even in creative fields such as movies (e.g. Val Kilmer’s voice in Top Gun:Maverick was only made possible due to AI). This duality raises a crucial question: Will AI create more jobs, enhancing our capabilities, or will it displace jobs, leading to significant human repercussions? The difficulty in providing a simple answer comes from the fact that never before has a technology had such far-reaching implications or is able to be scaled so quickly and easily. We also have no way of knowing how much more “intelligent” the next generation of AI technology will get.</p><p>Generative AI is definitely a double-edged sword when it comes to learning and the way we consume information. Access to vast knowledge at our fingertips can be advantageous and can save us copious amounts of time. As someone who learned from Encyclopaedia Britannica, I recall the frustration of missing volumes at the local library on my quest to find information while researching the JFK assassination and then spending hours if not days to get the information I needed. This adversity, however, taught resilience, a valuable trait potentially impacted by our reliance upon AI to solve our problems for us. As ChatGPT and related technologies integrate further into learning, we must confront this potential impact. When faced with complex problems, will we seek creative solutions, explore additional resources, or opt out simply because it’s just too hard; potentially leading to a generation of people lacking resilience?</p><p>As AI and related technologies get better, they will take on more advisory roles, or become trusted companions rather than mere information tools. They will enable us to get answers quickly and easily and even make decisions for us. However, we must remain cautious. If these models were trained on biased or incomplete data, the answers they provide may be inaccurate or skewed, leading to potential biases or hallucinations (making up something in an effort to please the user that is largely false). The decisions it makes might also be steeped in bias, potentially leading to unethical, divisive, or even insulting and unwanted outcomes. We must be vigilant and balance the readily available AI based answers with our own ability to critically analyse and synthesise the information; ensuring that we don’t blindly accept the returned answer as truth. We must also strive to ensure that we have diverse and comprehensive data for training the AI so that we can avoid these pitfalls and meet our needs effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80y62Q8cEhKT8Ywf0U53rg.png" /><figcaption>This future does not exist.. yet (made by Midjourney)</figcaption></figure><p>Ethical considerations regarding AI’s use are undoubtedly valid, but like with any ethical issue, they can be intricate and subjective. For instance, using ChatGPT to compose an entire novel might be seen as unethical by many. However, consider an author facing writer’s block while working on her creative masterpiece. Seeking inspiration from ChatGPT to describe a scene or character, and subsequently finding the creativity to finish her work, could be akin to seeking advice from a trusted friend, advisor, colleague, or peer. This raises questions about the nature of AI’s role in creative endeavours and the complex intersection of ethics and technology and the where the balance is.</p><p>The above may be a simple example so let’s turn to one with much more far reaching and impactful concerns. If AI can be used for the advancement of the good what about the nefarious use of AI to be used as some form of weapon. I very recently watched Oppenheimer (amazing movie and I thoroughly recommend it) and saw how theory can be put into practice in the most destructive ways. However dramatised, I watched the portrayal of scientists first marvel and then lament their own discoveries. So, what if we are on the cusp of something similar now (I can hear the virtual scoffs)? What if, we are currently at the marvel stage of AI and the ability to scale this technology allows us to create easily digestible tools like PowerPoint slide creators, or pictures of people that don’t exist? What if these simple tools are desensitising our awareness of its potential downsides. As we traverse this duality, it becomes critical to strike a balance — to harness the opportunity for discovery while cautiously navigating its powerful potential for harm. Will we, in years to come (and as per the nuclear experiment), look back and lament our discovery and say was there more that could have been done?</p><p>As AI gets smarter and better it is evident that it will “learn” to make decisions and help alleviate some of the human burden and may even help reduce stresses involved with decision making. This however, leads to a fear that is a basis of many past and contemporary works of fiction: Will AI take over the world? At present, AI is not at the stage of making the smallest self-aware decisions let alone taking over the world. While I may not fully subscribe to the notion of self-aware reasoning machines that will one day judge humanity (and possibly find them lacking), I acknowledge that such a possibility cannot be entirely ruled out. Nevertheless, I believe that this scenario is still distant, and the realization of such an event would likely require another ground-breaking discovery (possibly in the realm of quantum computing or other uncharted territories). For me, Skynet or Ultron is still closer to science fiction than science fact.</p><p>Advancements like AI, that have such a dual nature and with such far-reaching and life altering impacts, necessitate boundaries and regulations. Yet, determining these guidelines raises vital questions about decision-makers such as who makes these policies and guidelines? As humans surely, they are also flawed and biased? We must also ensure that the making and enforcement of these guidelines still provides a simple way to explore AI more ethically and for the good of all. Governing bodies such as the United Nations as well as great thinkers and entrepeneurs are all now working on understanding the unique challenges AI presents to humanity. They are also looking at how the risks and fears can be mitigated through policy and guidelines . The balance and hope lies in a thoughtful and concerned undertaking, aiming to regulate AI’s potential for harm and prevent malicious use whilst still allowing the ability to discover new and exciting possibilities. Amidst the pursuit of these guidelines and policies, one thing remains clear: ethics will always be an inherently “human” concern.</p><p>AI, with its undeniable power, stands ready to shape our lives in ways we have yet to fathom, even surpassing the transformative impact of the internet. The duality of this technology leads to a simple question: Will the impact be for our betterment, or will it lead to our downfall? As we have no crystal ball and our future remains shrouded in mystery, we find ourselves at a defining moment — will we embrace the uncharted territory of AI’s potential, or shy away from the unknown? In our quest to navigate this new landscape, we must strive to maintain a fine balance, a delicate equilibrium between harnessing AI’s power for human progress and safeguarding against potential dangers. This balance, while challenging, will define our coexistence with AI. And as this unfolding chapter beckons, the most thought-provoking question of all lingers — what legacy will we leave behind as AI and humanity converge on this extraordinary journey?</p><h3>References</h3><p><a href="https://www.bbc.com/news/entertainment-arts-65881813">https://www.bbc.com/news/entertainment-arts-65881813</a></p><p><a href="https://www.nytimes.com/2023/03/05/technology/artificial-intelligence-breast-cancer-detection.html">https://www.nytimes.com/2023/03/05/technology/artificial-intelligence-breast-cancer-detection.html</a></p><ul><li><a href="https://arxiv.org/abs/2303.08774">GPT-4 Technical Report</a></li><li><a href="https://ia.acs.org.au/article/2023/hollywood-actors-strike-to-protest-ai-replacement.html">Hollywood actors strike to protest AI replacement</a></li><li><a href="https://unsceb.org/principles-ethical-use-artificial-intelligence-united-nations-system">Principles for the Ethical Use of Artificial Intelligence in the United Nations System</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d15b12a04edd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks and the Titanic Challenge]]></title>
            <link>https://medium.com/@ashwin_68285/neural-networks-and-the-titanic-challenge-6052144a51ae?source=rss-21ab527e5454------2</link>
            <guid isPermaLink="false">https://medium.com/p/6052144a51ae</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[kaggle-competition]]></category>
            <category><![CDATA[titanic-disaster]]></category>
            <dc:creator><![CDATA[Ashwin Shekhar]]></dc:creator>
            <pubDate>Tue, 26 Jul 2022 23:14:42 GMT</pubDate>
            <atom:updated>2022-07-26T23:14:42.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*4Pnj1pJzP_ncBvr_T2VdlQ.jpeg" /><figcaption><a href="https://en.wikipedia.org/wiki/Sinking_of_the_Titanic">https://en.wikipedia.org/wiki/Sinking_of_the_Titanic</a></figcaption></figure><h3>Introduction</h3><p>The purpose of this article is to show a solution to the Kaggle Titanic Survival competition.</p><p>As a brief, there is a set of data given whereby we know which passengers survived and which passengers perished in the fated voyage of the Titanic in the early morning hours of 15 April 1912.</p><p>This article will show how this challenge can be addressed using artificial neural networks.This article will be part of a larger series of articles that will hopefully allow people to see and learn how <em>artificial intelligence </em>concepts can be used to solve problems.</p><h3>The Data</h3><p>Details for the data can be found on the Kaggle page: <a href="https://www.kaggle.com/competitions/titanic">https://www.kaggle.com/competitions/titanic</a>. (anyone can see this solution or a number of other excellent solutions through this link)</p><p>The data dictionary has been included here for the sake of convenience.</p><p><strong>survival: </strong>0=No, 1=Yes</p><p><strong>pclass</strong>: A proxy for socioeconomic status (SES)<br>1st = Upper<br>2nd = Middle<br>3rd = Lower</p><p><strong>age</strong>: Age is fractional if less than 1. If the age is estimated, is it in the form of xx.5</p><p><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)</p><p><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.</p><p><strong>ticket: </strong>Ticket number</p><p><strong>fare: </strong>How much people paid for their ticket</p><p><strong>cabin: </strong>Cabin number</p><p><strong>embarked: </strong>The port of the passenger’s embarkation. C = Cherbourg, Q = Queenstown, S = Southampton</p><h3>The Process</h3><p>When analysing data and more specifically using machine learning to develop insights from data we <em>generally </em>follow a very similar process as outlined below:</p><figure><img alt="The data and insights process" src="https://cdn-images-1.medium.com/max/563/1*5gSta_52NBArouhO5JRNig.png" /><figcaption>Data and Insights process</figcaption></figure><p>This solution will loosely follow this process. For the sake of brevity (and another article) I have left the <em>Deliver Value</em> process flow out which explains how we generally operationalise models to deliver value.</p><h3>Analyse data</h3><p>To analyse data the first thing that must be done is to store the data. For this example data can be obtained from Kaggle and stored as a CSV. This data can then be quickly viewed with a few simple lines of code.</p><p>These simple lines of code can provide good insights into what the data looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7028018b8d821a5ad5ed9cacd0857293/href">https://medium.com/media/7028018b8d821a5ad5ed9cacd0857293/href</a></iframe><p>This will give us enough information to understand the data. For example, the last line shows how many null values there are in the data.</p><h3>Cleaning</h3><p>One of the columns found to be null was that of age of the passenger. Whilst there are multiple ways to handle the null values, the following simple approach was taken for the age column:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4660f0cc0d644ddc9875dad395b10c4d/href">https://medium.com/media/4660f0cc0d644ddc9875dad395b10c4d/href</a></iframe><p>The above code shows that, the mean of the age will be used for any null values. Similar approaches were taken for other columns as part of the data cleaning process.</p><h3>Exploratory Data Analysis (or EDA)</h3><p>Once data cleaning has been performed to an adequate level more detailed data analysis can be performed.</p><p>The purpose of this was to see if there was any intuition or learning that can be gained.</p><p>A simple visualisation can be done to see the survival rate of passengers based on a single variable (e.g gender)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bcb03e83da318ee6ede95330236d7fe/href">https://medium.com/media/4bcb03e83da318ee6ede95330236d7fe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*xZGZshT7HTyg9uKTfdMmvg.png" /><figcaption>Survival rate visualisation 1</figcaption></figure><p>To get even more insights we can do even more visualisations using the <em>seaborn </em>package</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d48d0cf770d1c04e37049f384c4f85ed/href">https://medium.com/media/d48d0cf770d1c04e37049f384c4f85ed/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*wY3qhaPXUIduKOYdiCs14A.png" /><figcaption>Survival count based on family size</figcaption></figure><p>The above graph is interesting and shows that proportionately, those with children or have parents seem to survive more than the ones with none. This intuitively supports the <em>save the women and children first</em> story.</p><h3>Feature Engineering</h3><p>When training and using neural networks, the inputs (or training data) need to be <em>engineered</em> to be more neural network <em>friendly</em>.</p><p>This means that we need to represent inputs basically as numbers. As an example let’s take the <em>Sibsp </em>data point:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4bcd9a5f9ddeb7a57151cc809343146/href">https://medium.com/media/c4bcd9a5f9ddeb7a57151cc809343146/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*tsPrlllqcd2WfgsXx4Pgqw.png" /><figcaption>Family Size Categorisation</figcaption></figure><p>The above makes the <em>Sibsp</em> data point as a family size category. Similar was done with other features such as age and fare.</p><p>Now we need to convert all these to number quantities. To do this we convert each feature to a number value and then scale the values to similar values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e71e361e0af006b5edaac3379b46a90/href">https://medium.com/media/9e71e361e0af006b5edaac3379b46a90/href</a></iframe><p>The <em>pandas get_dummies </em>function allows us to split categorical data into columns of 0s and 1s (for more information: <a href="https://dataindependent.com/pandas/pandas-get-dummies-pd-get_dummies/">https://dataindependent.com/pandas/pandas-get-dummies-pd-get_dummies</a>/). We then need to standardise the data as machine learning features generally need to look like normally distributed data. This was done using the <em>sklearn.preprocessing </em>package.</p><p>Before moving on to building the model the same data cleaning and engineering process must be performed with the <em>unseen</em> data (or in this case the test data that needs to be input into the model and the predictions made).</p><p>When the inputs are compared (training and test data), we must ensure that the shapes are similar to each other with the training data having more rows than the unseen or test data (in this case).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f0d636bfef1330bafaa51ab47ccd5d6/href">https://medium.com/media/7f0d636bfef1330bafaa51ab47ccd5d6/href</a></iframe><h3>Neural Network</h3><p>Building a neural network can be a very slow and iterative process. The first neural network is designed and built and then trained.Data is then <em>validated</em> against the neural network architecture to find accuracy. Accuracy can then be improved in a variety of ways such as:</p><ol><li>Different features chosen</li><li>Tuning of hyperparameters (such as learning rate)</li><li>Changing the network architecture (add more nodes / layers)</li></ol><p>One such model that worked and gave ~<strong>76% accuracy </strong>was built as per below:</p><ul><li>2 Hidden Layers</li><li>RELU activation function</li><li>2 Dropout layers</li><li>2 Hidden Layers</li><li>Output layer with Sigmoid activation</li><li>Stochastic Gradient Descent for Optimizer</li><li>Loss Function — Binary Crossentropy</li></ul><p>This is just one example of an architecture that worked for us. There are many ways to develop different NN architectures (and/or different hyperparameters that can be tuned). Whilst a full theory on Keras and Tensorflow is out of scope here, the code was commented to give as much detail as possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63e659fca82613d277c3e9cd1e73525f/href">https://medium.com/media/63e659fca82613d277c3e9cd1e73525f/href</a></iframe><p>After building the model the model is trained on a subset of the training data and validated using the remaining data. The neural network was trained using:</p><p><strong>100 Epochs</strong>: An epoch is basically when all data has passed through the network (forward and backward propagation) once</p><p><strong>Batch Size of 50</strong>: The training data is broken up into batches of 50</p><p><strong>Binary Cross Entropy</strong> loss function: As this is a binary classification problem (0 death or 1 for survival) this is a valid choice.</p><p>We also use the <strong>stochastic gradient descent</strong> as the optimizer (with learning rate 0.1 and momentum of 0.6) which is the chosen algorithm to reduce the loss.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/780b3b03c6d67cfd0720b8a040e4a2a1/href">https://medium.com/media/780b3b03c6d67cfd0720b8a040e4a2a1/href</a></iframe><p>The loss and accuracy per epoch can then be plotted to see how the training process went:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3522c90f7bbe3b895cd55657308db20b/href">https://medium.com/media/3522c90f7bbe3b895cd55657308db20b/href</a></iframe><h3>Finally</h3><p>Once training is completed and we are satisfied with the accuracy and loss we can then create a csv that can submitted to the Kaggle competition.</p><p><a href="https://gist.github.com/ashwin-vx/4d688fcd001829acd2259dfbd568d78b">https://gist.github.com/ashwin-vx/4d688fcd001829acd2259dfbd568d78b</a></p><p>There are obviously many ways to improve on this code but as a general rule this is the process that we follow when it comes to delivering insights from data.</p><p>A final step that can be taken which can be very useful is to take a random sample or samples of the training data and turn it into input data for the model. The input can then be passed through the model and result should reflect the known training data and this gives us some intuition that the model has <em>learned </em>the data correctly.</p><p>This article includes code snippets as examples of what was done. For the full code you can visit Kaggle at:</p><p><a href="https://www.kaggle.com/code/ashekhar/titanic-with-neural-networks">Titanic with Neural Networks</a></p><p>Here you can see my code as well as many other excellent notebooks.</p><p>Please feel free to leave a comment as well and follow for more updates and notebooks coming soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6052144a51ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>