<?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 Honzik J on Medium]]></title>
        <description><![CDATA[Stories by Honzik J on Medium]]></description>
        <link>https://medium.com/@honzj?source=rss-19877de6126c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wkrx5OfRiUCcUck4D9lxIA.jpeg</url>
            <title>Stories by Honzik J on Medium</title>
            <link>https://medium.com/@honzj?source=rss-19877de6126c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:26:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@honzj/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 a 7B vision model on steel defects.]]></title>
            <link>https://medium.com/@honzj/i-fine-tuned-a-7b-vision-model-on-steel-defects-9906c91e0b53?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9906c91e0b53</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 03:38:44 GMT</pubDate>
            <atom:updated>2026-09-08T03:38:44.164Z</atom:updated>
            <content:encoded><![CDATA[<h3>I fine-tuned a 7B vision model on steel defects. It beat an untuned frontier API by almost 50 percentage points.</h3><p>The model classified 97.5% of test images correctly. It got both the defect class and location right on 63.1%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWxYffCLPZScFAC2O9qyCA.png" /></figure><p>The system takes a steel surface image and produces a three-line report: the defect class, its location and a short description. The goal was to learn the full fine-tuning process, from preparing training data to evaluating whether it improved the model.</p><p>The evaluation pipeline compared a QLoRA fine-tune of Qwen2.5-VL-7B with three baselines: its original version, a classical image classifier, and Claude Opus 4.6 through an API. The Claude prompt included no task-specific examples.</p><p>Training took 63 minutes on a free Colab T4 GPU. The tuned model classified 97.5% of test images correctly, compared with 86.4% for the classical classifier and 48.0% for Claude. It got both class and location right on 63.1%, and every description came from a training template.Six kinds of surface defect on hot-rolled steel, 1,800 photographs, and a question a steel or mining vision team faces every quarter: call an API, train a classifier, or fine-tune an open model?</p><h3>The dataset</h3><p>NEU-DET contains 1,800 greyscale images of hot-rolled steel, each 200 by 200 pixels. There are 300 images per defect class: crazing, inclusion, patches, pitted surface, rolled-in scale and scratches. In a mill this classification grades the coil. It points at the roller or the de-scaler behind a recurring mark, and it feeds the process controls. It is a proxy for any real plant’s cameras, and nothing here is evidence about mining imagery. What transfers is the shape of the problem: an industrial image in, a structured verdict out, and a control loop that trusts the model only if the evaluation is honest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pTBNzqGMD3JMyxz6bMAzOw.png" /><figcaption><em>The six classes, three training images each. Crazing is a mesh of fine cracks, an inclusion is a few sharp dark marks, patches are broad areas of different tone, a pitted surface is many small holes, rolled-in scale is dark flakes pressed in, and scratches are straight lines. None of the images shown here is in the test set.</em></figcaption></figure><h3>Four systems sat the same exam, and the ranking surprised me</h3><p>Four systems answered the same 198 sealed test images with the same instruction, given here in full because the served model’s result depends on it:</p><blockquote><em>Inspect this hot-rolled steel strip image and report the surface defect. Answer in exactly three lines and nothing else: CLASS, one of crazing, inclusion, patches, pitted surface, rolled-in scale, scratches. LOCATION, one of top-left, top-centre, top-right, centre-left, centre, centre-right, bottom-left, bottom-centre, bottom-right, whole. DESCRIPTION, one sentence on the defect’s appearance and where it sits.</em></blockquote><p>The six names are listed. They are not defined. One scorer marked all four systems. Accuracy is exact match on the class, and a report the strict parser rejects scores zero. No report was rejected: all three language models produced the three-line format on all 198 images, so nothing below is a formatting effect.</p><p>Qwen2.5-VL-7B, QLoRA fine-tuned: 0.975 (95% CI 0.949 to 0.995) Classical HOG and SVM pipeline: 0.864 (95% CI 0.813 to 0.909) Claude Opus 4.6, zero-shot: 0.480 (95% CI 0.409 to 0.551) Qwen2.5-VL-7B, untuned: 0.283 (95% CI 0.222 to 0.348)</p><figure><img alt="A four-row table titled “Same 198 sealed images, same instruction, one scorer. Exact-match class accuracy.” Columns are System, Class accuracy and 95% CI. Qwen2.5-VL-7B QLoRA fine-tuned, 0.975, 0.949 to 0.995. Classical HOG and SVM pipeline, 0.864, 0.813 to 0.909. Claude Opus 4.6 zero-shot, 0.480, 0.409 to 0.551. Qwen2.5-VL-7B untuned, 0.283, 0.222 to 0.348." src="https://cdn-images-1.medium.com/max/1024/1*kW4vn7Q4GBNjm42Y9f1JVA.png" /><figcaption>The four rows. Intervals are 95% percentile bootstrap over the 198 test images with 10,000 resamples, so they describe sampling of images, not training randomness: the fine-tune is a single run.</figcaption></figure><p>The paired differences are the honest comparisons, because each is computed image by image and cancels the noise both systems share. Tuned minus classical is +0.111 (interval +0.061 to +0.162). Tuned minus served is +0.495 (+0.419 to +0.566). Tuned minus base is +0.692 (+0.626 to +0.758). Every interval excludes zero.</p><p>A frontier model, the fastest thing to try, sits under a classifier built from edge histograms and a support vector machine tuned on the validation split. That classifier sits under a fine-tune that took 63 minutes on a free Colab T4 GPU and trained 0.48% of the model’s weights.</p><p><strong>QLoRA</strong>, for the practitioner reader: the 7B model’s weights stay frozen, stored in 4-bit numbers so the whole thing fits a free GPU, and training updates only small adapter matrices bolted alongside them. “7B” names the language model. With the vision encoder the whole model is 8.3 billion parameters, and the adapter is 40 million of them.</p><h3>A frontier model reached for the vivid word and missed the subtle one</h3><p>On this task, called zero-shot with the class names listed and not defined, general capability did not equal domain vocabulary.</p><p>Claude Opus 4.6 said “crazing” 56 times for 33 real cases and “inclusion” 4 times for 33. The untuned Qwen did something else again. It said “pitted surface” for 91 of 198 images and never once said “crazing”. It said “rolled-in scale” 16 times and was wrong every time. Two different priors, one underlying gap, and 1,500 labelled examples closed it. Whether a prompt carrying the one-line tells from the figure above would have closed some of it is an open question: this project tested the instruction the fine-tune was trained on, and nothing else.</p><figure><img alt="A six by six confusion matrix shaded blue by count. The diagonal holds 31 crazing, 1 inclusion, 17 patches, 20 pitted surface, 4 rolled-in scale and 22 scratches. The heaviest off-diagonal counts are 19 rolled-in scale called pitted surface, 17 inclusion called rolled-in scale and 10 scratches called rolled-in scale." src="https://cdn-images-1.medium.com/max/1024/1*XSB6wNHMPTkVrduPxMDFhg.png" /><figcaption>The served model over the 198. Rows are the true class, columns what it said. The crazing column holds 56 answers for 33 real cases, and inclusion 4. <em>Opus over-predicted crazing and rarely predicted inclusion. I did not test whether providing class definitions would improve its accuracy.</em></figcaption></figure><h3>Class and location were both correct on 63.1% of images</h3><p>The class is right 97.5% of the time. The grid cell is right 64.1% of the time, and always answering “whole” would score 51%, because half the labels are “whole”. The served model, at 57.1% on location, was closer to the fine-tune here than anywhere else.</p><p>The model got both class and location right on 63.1% of test images. Description quality was evaluated separately.</p><figure><img alt="Two three by three grids of counts shaded blue, one for the labels and one for the model’s answers, with a wide bar under each for the “whole” answer. The labels hold 38 centre, 13 top-centre, 13 bottom-centre and 101 whole. The model answers 34 centre, 19 centre-right, 14 bottom-centre, 10 top-centre and 105 whole." src="https://cdn-images-1.medium.com/max/1024/1*nun4_lbX24pL_rzHaxD_cA.png" /><figcaption>Where the defects are, and where the fine-tune said they were. The two spreads nearly match, and it still places only 64.1% of them correctly. Matching the shape of the labels is not the same as getting each image right.</figcaption></figure><h3>Every tuned description came from a training template</h3><p>Training answers were rendered from the labels by three template sentences per class. It showed up in the tuned outputs. Every description is a template with the location slotted in: 40 distinct strings, drawn from 11 of the 18 templates. Nothing in the sentence came from the image that the CLASS and LOCATION lines do not already say. The base model writes fresh prose instead, about the wrong defect.</p><p>The fine-tune learned to classify and not to describe, as the answers it trained on never asked it to.</p><figure><img alt="Two panels of 198 small square tiles each. The left panel resolves into large blocks of a few repeated colours. The right panel is a scatter of many different colours with almost no repetition." src="https://cdn-images-1.medium.com/max/1024/1*8QPS05FU8iowQjr2vrKeXA.png" /><figcaption>One tile per test image, coloured by the sentence the model produced. The fine-tune’s 198 descriptions are 40 distinct strings, every one of them a template with the location slot filled, and they use 11 of the 18 templates. The base wrote 123 sentences of its own, so its panel is noise.</figcaption></figure><h3>A blind human read split 15 to 15, and a machine judge chose the tuned side 67% of the time</h3><p>The descriptions are the one thing a classifier cannot produce, so they were judged on their own, blind. A seeded key decided for each pair whether the tuned description was shown as A or B, and neither reader could see the key.</p><figure><img alt="A greyscale steel image of dense fine cracking beside two labelled descriptions. The fine-tune, class right, says hairline cracks criss-cross the surface over the whole image. The base model, class wrong, says fine linear scratches are visible across the bottom-centre area of the image." src="https://cdn-images-1.medium.com/max/1024/1*vzaxXBGGwK3JaeHoWLK-FQ.png" /><figcaption>One pair as the reader saw it, with the sides named here. The fine-tune got the defect right and said nothing a label does not say. The base wrote a specific sentence about scratches that are not there, and it reads better. I preferred the base one.</figcaption></figure><p>I scored 30 pairs before any judge existed: tuned 15, base 15. On 30 pairs that is compatible with anything from about 0.31 to 0.69 preference, so the fair reading is “not clearly better”, not “equal”. Still, on those same 30 pairs the tuned model named the right class and the base did not in 23 of 30, and in 10 of those 23 I preferred the base sentence. A model that is right about the defect three times as often did not read clearly better to me on 30 pairs, because what it had gained was the label and what it had lost was the prose.</p><p>The machine judge was Claude Opus 4.6, the same model that scored 0.480 as a contestant, now given the reference label it did not have as a contestant. It saw each pair twice with the sides swapped, and a pair counted only when both orderings agreed: 183 of 198 did, and the 15 that flipped were dropped and counted. Over those 183 it chose the tuned side 123 times, the base 57 times, and called 3 ties: 0.672 for the tuned side, interval 0.601 to 0.738.</p><h3>The judge scored the tuned descriptions higher on faithfulness</h3><p>Each side was scored 1 to 5 on three dimensions: faithfulness (is everything stated visible in the image), specificity (concrete features, and where), clarity (one plain sentence). The judge’s whole margin was faithfulness, +1.04 to the tuned side (interval +0.84 to +1.25), with specificity and clarity unchanged within their intervals. It preferred the tuned descriptions for naming the right defect and for nothing else.</p><p>Agreement between the two readers, on the 29 of my 30 pairs the judge kept: raw 0.66, Cohen’s kappa 0.32. Kappa is agreement corrected for chance, where 0 is chance and 1 is perfect, so 0.32 is fair and no better. The disagreement ran one way: in 8 of the 10 pairs where we differed, I chose the base and the judge chose the tuned side.</p><h3>The gap looks like what the label is worth to a reader</h3><p>The two readers differed in four ways. I did not have the reference label in view: I misread the protocol as “score the image and the two sentences”, and I did not know what crazing or rolled-in scale look like. The judge had the label, knew the words, is a machine, and read 183 pairs to my 30.</p><p>Without a name for what the image shows, faithfulness collapses to “is the position plausible”, and the signal left is prose quality, where the base wins. With the name, faithfulness is checkable, and the canned sentence wins. That is the reading the one-directional disagreement supports. It is not a measurement of the label’s value, because the four differences are confounded. The experiment that isolates the label is on the version two list: the same 30 pairs, the same reader, the reference sheet in view.</p><p>What it taught me is the importance of domain knowledge in this process, which is what the reference label was there to capture.</p><p>That is the result. The rest is how the numbers were made.</p><h3>The difficulty was measured before any GPU time was spent</h3><p>The text project lost because the base model was already competent, so tuning could only teach style, and the blind judge preferred the base 51.5% to 33.9%.</p><p>This time, before any training, the untuned model answered 50 of the 198 sealed images: 30.0% class accuracy, 100% schema compliance. Running the untuned model on sealed images is not peeking, because nothing learns from those answers and they were later reproduced byte for byte in the full control run. The rule, written the day before, said proceed below about 60% and otherwise harden the task once and re-pilot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRs4d5orkoCdptGCRGoPlA.png" /><figcaption>The gate as it ran. The rule was written before the number, and the number came in under it.</figcaption></figure><p>Calibration means changing the task before training. Changing the task, the evaluation or the results after seeing them introduces bias. Nothing moved after the pilot: not the test set, not the scorer, not the schema.</p><p>The pilot also said where the headroom was. The base already followed the three-line format perfectly. What it lacked was the six words.</p><h3>The classical baseline was tuned the way a real one would be</h3><p>Every image passes through the same preprocessing before any model sees it. Greyscale, then contrast stretched tile by tile with a cap so noise stays down (CLAHE, contrast limited adaptive histogram equalisation), then a resize to 224 by 224. HOG turns each image into 6,084 numbers, a histogram of edge directions and strengths per cell. An SVM with an RBF kernel draws the boundary. Its two knobs were chosen on the 102 validation images from a nine-point grid (validation accuracy 0.755 to 0.853), refitted on the 1,500 training images, and scored once on the 198.’</p><figure><img alt="Two greyscale panels of the same pitted steel surface side by side. The left panel is flat and low contrast at 200 by 200. The right panel at 224 by 224 shows the same pits with far stronger local contrast." src="https://cdn-images-1.medium.com/max/1024/1*GivdWJSLCsMjGz7DnyLtCg.png" /><figcaption>The same image as downloaded and as every model saw it. CLAHE lifts local contrast, so a faint texture becomes visible. The judge and the human reader saw these pixels too, <em>so nobody was asked to describe a feature the raw image hides.</em></figcaption></figure><figure><img alt="Two rows of six panels. The top row shows one greyscale steel image per defect class. The bottom row shows the same six images rendered as grids of small radiating line clusters, dense and multidirectional for the texture classes and dominated by one direction for scratches." src="https://cdn-images-1.medium.com/max/1024/1*dkSNxmSUbN0Q-1x3eL29dQ.png" /><figcaption>What the classifier sees. Top row: one preprocessed training image per class. Bottom row: the same image as HOG represents it, a small star of lines in every cell, longest in the direction the edges run. Scratches give one long spoke. Crazing and rolled-in scale give spokes in every direction. The two textures without a dominant direction are the two the classifier confuses.</figcaption></figure><p>Its confusion matrix is readable by eye. It mixes up patches and pitted surface, four each way, and both of those have a lack of directional features, unlike a scratch, which is a long straight line. Edge histograms cannot separate two textures that point nowhere in particular.</p><figure><img alt="A four-row table titled “Same 198 sealed images, same instruction, one scorer. Exact-match class accuracy.” Columns are System, Class accuracy and 95% CI. Qwen2.5-VL-7B QLoRA fine-tuned, 0.975, 0.949 to 0.995. Classical HOG and SVM pipeline, 0.864, 0.813 to 0.909. Claude Opus 4.6 zero-shot, 0.480, 0.409 to 0.551. Qwen2.5-VL-7B untuned, 0.283, 0.222 to 0.348." src="https://cdn-images-1.medium.com/max/1024/1*2LpbgMCq0P3G-eOd6U1wIQ.png" /><figcaption><em>The classical pipeline’s confusion matrix over the 198 test images: 171 right. Rows are the true class, columns what it said.</em></figcaption></figure><h3>The exam was sealed, and every row carries a fingerprint</h3><p>The 198 test ids were frozen before anything ran, with the labels in the file, and a command recomputes the split from its seed to prove the file was not hand-edited.</p><p>Nine test images correlate at 0.97 or above with a training image. They were kept and listed, not dropped. A byte copy is proof of leakage. A correlation on a low-contrast texture is a suspicion, and with a suspicion you cannot confirm, the honest thing is to leave them in and report the metric both ways. Without them: tuned 0.974, classical 0.873. Nothing changes.</p><figure><img alt="A notebook cell running the data download and holdout check, with output reading 1800 pairs extracted, digest bb5cfdfed2ead982, and holdout matches the seed." src="https://cdn-images-1.medium.com/max/1024/1*YvHE-q6CFSEVadRIX2FYDA.png" /><figcaption>The pinned dataset and the frozen split, both checked by command before any generation ran.</figcaption></figure><p>Every generation row carries a fingerprint over the prompt, the preprocessing and the decoding, and the pairing code refuses two rows whose fingerprints differ. Decoding was greedy, meaning the most likely token every time, so a rerun reproduces a row exactly.</p><h3>Training took an hour and changed half a percent of the weights</h3><p>376 steps, 63 minutes, 40,370,176 trainable parameters of 8,332,536,832.</p><p>The vision encoder stayed frozen. The adapter can only map what the encoder already sees onto six names, and it cannot fix a bad vision encoder, as it is frozen. Validation loss fell from 0.325 to 0.0737 and was lowest at the final checkpoint. The loss flattened near 0.08 from step 125, which is the template answers being learned.</p><figure><img alt="A line chart with optimiser step on the horizontal axis and loss on the vertical. Two curves fall from about 0.94 and 0.32 to about 0.08 by step 125, then run almost flat to step 375. A dashed vertical line marks the end of epoch one at step 188. The final validation point, the lowest at 0.0737, is circled and labelled as the kept checkpoint." src="https://cdn-images-1.medium.com/max/600/1*vpFDZfFkVtVnRHLTDXOWAg.png" /><figcaption>Both losses fall steeply for 125 steps, then run flat near 0.08. The lowest validation loss is the final checkpoint. A flat loss here means the templates were learned, and it says nothing about whether the class is right.</figcaption></figure><p>A low loss says the model writes the templates well. It does not say the class is right. That is the exam’s job.</p><h3>Running on Bedrock took an afternoon and USD 2.83</h3><p>The judge and the served row ran on Amazon Bedrock through boto3, with the model id and the region recorded on every row and a cost estimate printed before any call.</p><p>Getting there took an afternoon. Claude Opus 5 is access-gated and the account did not qualify. The models documented as open needed an AWS Marketplace agreement. The retired model-access page no longer surfaces it, so it was created through the API after attaching Marketplace permissions to the key’s IAM user. The control plane then reported the agreement available while the runtime kept refusing, a lag other people have hit. A sweep of ids found Claude Opus 4.6 working immediately on the same credentials, so the judge was re-pinned to it and the run went ahead.</p><p>Total spend: USD 2.83 for 594 calls, against an estimate of 4.31.</p><h3>What this is not, and what a version two changes first</h3><p>Not a production system: no bounding boxes, no video, no deployment, one training run with no search, and a proxy dataset. The human anchor was one non-specialist reader without the label, stated beside the kappa rather than in a footnote.</p><p>The first change in a version two follows from the finding. Vary the training descriptions, so the model has something to learn about describing rather than a sentence to memorise. Then run the same blinded pass again. The second is to give the human reader the six-class reference sheet, and a mill inspector beside a naive one, so the kappa becomes a curve of what expertise adds instead of a single point.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9906c91e0b53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Did your fine-tune actually get better? The metric you trust cannot tell you]]></title>
            <link>https://medium.com/@honzj/did-your-fine-tune-actually-get-better-the-metric-you-trust-cannot-tell-you-a980f91c7266?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a980f91c7266</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 10:51:33 GMT</pubDate>
            <atom:updated>2026-08-29T13:22:16.974Z</atom:updated>
            <content:encoded><![CDATA[<p><em>ROUGE went up, the notes got worse, and a blind judge revealed it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsMMMMivDhcnw1itnJDlfw.png" /></figure><p>If you fine-tune a small model, how will you know it got better?</p><p>That question decided the shape of my first fine-tune before I trained anything. The task was to turn a doctor-patient conversation into one section of a clinical note, the ambient-scribe problem in miniature, on the public MTS-Dialog dataset. The model was Qwen2.5–1.5B-Instruct, QLoRA on a free Colab T4, fifteen minutes of training. The evaluation was the point of the project.</p><p>It lost to itself.</p><p>LoRA fine-tuning leaves the model’s 1.5 billion weights frozen. It trains small extra matrices bolted alongside them, about one percent of the size, and saves them as a 70 MB adapter. The Q in QLoRA stores the frozen base in 4-bit numbers so it fits a free GPU. For a small model on a T4, that is the difference between running and not running. What the adapter learns is whatever the training pairs reward, and that sentence is the whole story below.</p><h3>The loss curve would have told you it worked</h3><p><a href="https://medium.com/@honzj/how-to-build-a-machine-learning-model-ab8baf9e5dd8">Validation</a> loss fell from 1.62 to 1.38 and flattened. No overfitting. If you stop there, and most write-ups do, you call it a win.</p><figure><img alt="Line chart of training loss in grey and validation loss in orange over 300 steps, both falling and flattening, validation ending at 1.38." src="https://cdn-images-1.medium.com/max/1024/1*nmNmrsZM43As1h4UQd5-vA.png" /><figcaption>Training and validation loss over 300 steps: validation fell from 1.62 to 1.38 and flattened, with no sign of overfitting.</figcaption></figure><p>Four concepts to understand:</p><blockquote><strong><em>Sealed exam.</em></strong><em> The held-out conversations are chosen and their ids frozen before training. Nothing in that set is ever trained on.</em></blockquote><blockquote><strong><em>Control first.</em></strong><em> The base model writes its answers before any training, with the exact prompt the tuned model will get, so nobody can adjust the prompt after seeing results.</em></blockquote><blockquote><strong><em>Greedy decoding.</em></strong><em> Always the most likely next token, so the same prompt gives the same output every run and the committed outputs can be checked.</em></blockquote><blockquote><strong><em>Prompt fingerprint.</em></strong><em> Every output row carries a hash of the exact prompt. If the template changed between runs, the pairing code refuses to compare them.</em></blockquote><figure><img alt="Code editor showing 24 lines of JSON, alternating training loss and validation loss entries from step 25 to step 300." src="https://cdn-images-1.medium.com/proxy/1*FMLCerIHJHP3AjlRs1OE7g.png" /><figcaption>The committed training log: training and validation loss every 25 steps, 300 steps in 15 minutes on a free T4.</figcaption></figure><p>Loss measures how well the model predicts the dataset’s reference notes. It cannot see whether a note is true to the conversation. So the control came first: before any training, the untouched base model wrote a note for each of 194 held-out conversations, an exam envelope sealed before training and never opened during it. After training, the tuned model wrote the same 194 with the same prompt and the same decoding.</p><p>A judge then saw each pair blind, labelled A and B, and picked one. Every pair went through twice with A and B swapped, and a verdict only counted when both passes named the same note. Thirty pairs also got a human pass, mine, scored blind before the judge ran. The design is a loose cousin of a double-blind trial. Neither the judge nor the human knows which note is the treatment, and the allocation sits sealed in a separate file until scoring. For those working in health research, this will feel familiar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqjKTs8SXxEGcEsWtC76ug.png" /><figcaption>Every pair was judged blind twice with the order swapped and kept only when both verdicts agreed; the owner scored 30 pairs first.</figcaption></figure><p>Three terms for the judging:</p><blockquote><strong><em>Blinding key.</em></strong><em> Which side is the fine-tuned note is decided by a seeded draw and stored in a separate file that only the scoring code reads, after every verdict exists.</em></blockquote><blockquote><strong><em>Position swap.</em></strong><em> Language-model judges show position bias, a preference for whichever answer is shown first. So each pair is judged twice with the order reversed, and a pair the judge scores inconsistently is dropped and counted.</em></blockquote><blockquote><strong><em>Human anchor.</em></strong><em> Thirty pairs scored by a person before the judge runs, so the two are independent and their agreement can be reported.</em></blockquote><figure><img alt="A conversation about retirement, drinking and smoking, a reference note, two candidate notes labelled A and B, and a scores line preferring A because B calls the patient a smoker." src="https://cdn-images-1.medium.com/max/1024/1*N1QTN6jyQwklG5GUg8Fqaw.png" /><figcaption>One pair from the human blind pass: which of A and B is the fine-tuned model is sealed in a separate file.</figcaption></figure><p>Two terms for the evaluation:</p><blockquote><strong><em>Win rate with an interval.</em></strong><em> The share of kept pairs where the fine-tune was preferred, with a bootstrap interval. Parity is when the interval contains 50%, and only more pairs narrow it.</em></blockquote><blockquote><strong><em>ROUGE-L.</em></strong><em> The longest run of words shared with the reference, in order, turned into precision and recall. It rewards overlap with the reference, not truth to the conversation.</em></blockquote><p>Here is what the judge and the human pass saw, against what the metrics said.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g07xbKIH_G0wP_k1kpyvKg.png" /><figcaption>What the judge and I saw, against what the metrics said.</figcaption></figure><p>The tuned model was preferred in 33.9% of kept pairs (95% CI 26.9 to 40.9), the base model in 51.5%, tie 14.6%. The interval excludes 50%, so this is not parity: fine-tuning made the notes worse as judged blind.</p><figure><img alt="Two bar charts, base model in blue and fine-tuned in orange. Left: ROUGE-L F1 higher for the fine-tuned model. Right: blind preference lower for the fine-tuned model, with an interval bar that stays under the 50% line." src="https://cdn-images-1.medium.com/max/1024/1*PdiAHutSjWvyvsuvX_silw.png" /><figcaption>The overlap metric rose from 0.18 to 0.28 while blind preference for the fine-tuned model fell to 33.9% (95% interval 26.9 to 40.9), below parity.</figcaption></figure><p>The tuned model was preferred over the base in 33.9% of kept pairs (95% CI 26.9 to 40.9), the base model in 51.5%, tie 14.6%. The interval excludes 50%, so this is not parity: fine-tuning made the notes worse as judged blind.</p><h3>ROUGE rose by half while readers preferred the base model</h3><p>The dataset’s reference notes came first. The conversations were written afterwards to match them, and they often leave out the age, the date or the dose the note states. Fine-tuning on those pairs teaches the model that a good note contains specifics whether or not the patient said them.</p><p>It learned exactly that. Of the 88 pairs it lost, 41 were an invented fact. An age the patient never gave. A medication listed as current after the patient said it was stopped. “Denies stroke” from a patient who had reported one. Another 35 were omissions, because it also learned the dataset’s terse register and dropped the relative a condition belonged to, or why a drug was stopped.</p><blockquote><strong><em>Failure taxonomy.</em></strong><em> Every pair the fine-tune lost, read and labelled with its dominant failure, so “worse” becomes “worse how”.</em></blockquote><figure><img alt="Horizontal bar chart of five failure types, invented facts the longest bar." src="https://cdn-images-1.medium.com/max/1024/1*HVqUJaIAJ0ZgoZ91qbfKQA.png" /><figcaption>Of the 88 pairs the fine-tuned model lost, 41 contained a fact the patient never said and 35 left a relevant fact out.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPlnvglchpMOQ-NGSTVkKg.png" /><figcaption>A labelled loss: the fine-tuned note calls the patient a smoker and a social worker. The conversation says neither.</figcaption></figure><p>ROUGE rewarded the register and could not see the inventions. If you headline ROUGE, you ship the worse model.</p><h3>The evaluation caught three things the loss curve never would</h3><p><strong>A second kind of leakage.</strong> The duplicate check compared dialogue text across splits. The first tuned output read by eye stated a date that was in the reference note and nowhere in the conversation. The same source note sat behind a different dialogue in the training set. Five held-out rows went out, recorded, before any verdict existed. If you check only your inputs for leakage, check your targets too.</p><p><strong>The judge’s own bias.</strong> All 23 pairs it judged inconsistently were cases where it preferred whichever note was on the left. Single-pass judging would have folded that into the win rate, and you would never know.</p><p><strong>How far to trust the judge.</strong> Agreement with the human pass was 0.69 raw, kappa 0.41. Kappa is to raw agreement what <a href="https://medium.com/@honzj/mastering-validation-metrics-evaluate-your-models-like-a-pro-4fda25abe3cb">precision and recall</a> are to accuracy on an unbalanced dataset. Two raters who both say “base” most of the time will agree often by habit alone, and kappa subtracts that. Moderate, then. Enough to lean on 171 machine verdicts, not enough to skip the human.</p><h3>What this shows, and what it does not</h3><p>This project had some limitations. Built with Claude Code as the implementing agent and reviewed line by line, with limits worth naming: one judge, one human who is not a clinician, no hyperparameter search, and dialogues that were written to match existing notes rather than recorded in a clinic.</p><p>It does not show that fine-tuning is the wrong tool. It shows that this fine-tune, on this data, made a model less faithful, and that a prompted base model was a harder opponent than expected. Fine-tuning does exactly what you train it to do. The mistake was assuming the references were the truth.</p><p>Part two runs on the same sealed exam with the same judge. The same fine-tune on cleaned targets, with the unsupported specifics stripped out. If fixing the data fixes the faithfulness, that is a result with a mechanism. If it does not, that is a result too.</p><p>See the repo:</p><p><a href="https://github.com/J-Jurza/lora-eval-lab">github.com/J-Jurza/lora-eval-lab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a980f91c7266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep Your R Research Reproducible: A Quick Start Guide]]></title>
            <link>https://medium.com/@honzj/keep-your-r-research-reproducible-a-quick-start-guide-e40188ab2a7e?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e40188ab2a7e</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[health-analytics]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Thu, 08 May 2025 06:36:34 GMT</pubDate>
            <atom:updated>2025-05-08T07:52:10.253Z</atom:updated>
            <content:encoded><![CDATA[<p>Your R project doesn’t have to start in chaos. Here are a few tips to get you started on the right foot!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nk0K0vEA2r7_Ul3aEujoWQ.png" /><figcaption>Keep your analyses airtight: organisation, reproducibility and RStudio</figcaption></figure><p>Aimed at analysts new to R, this guide walks you through a clear, step-by-step framework to keep your R projects organised, your code reproducible and your results reliable.</p><p><strong>Note:</strong> This document covers some fundamentals but is not an exhaustive guide.</p><h3>1. Working with RStudio</h3><p>RStudio brings all the pieces of your R workflow into one place. Start by opening your project’s .Rproj file—this ensures every relative path resolves correctly. You’ll see four main panels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdBVglpXcOEbQqrwuUYF-A.png" /></figure><ul><li><strong>Script Pane</strong> for writing and saving your code</li><li><strong>Console Pane</strong> for quick tests and one-off commands</li><li><strong>Environment Pane</strong> where your data and objects appear</li><li><strong>Files Pane</strong> to browse and manage every file in your project</li></ul><h4>1.1 Script versus Console</h4><p>Scripts (top left) are your permanent record and the console (bottom-left) is temporary. Think of the console as your playground and scripts as your official record.</p><p><strong>Console</strong></p><ul><li>Use for testing small code snippets.</li><li>Do not store when you restart RStudio, it all disappears, so avoid leaving critical code behind.</li><li>Some users prefer to write all code in scripts, commenting out lines they’re not currently using.</li></ul><p><strong>Scripts</strong></p><ul><li>This is where your polished code lives.</li><li>You can copy code that works in the console here and save regularly.</li><li>Adopt a clear naming convention like 01_data_cleaning.R, 02_analysis.Rso you and your colleagues always know the intended execution order.</li></ul><p>Some analysts prefer to keep every experiment in scripts, simply commenting out blocks they’re not using. You can even create throwaway data frames named test or check for exploration, then remove them.</p><h4>1.2 The Files Pane</h4><p>The Files Pane (bottom right) lets you browse and manage your project’s files without leaving RStudio, making your work smoother:</p><ul><li><strong>Navigate folders</strong><br> View the project root (e.g., MyResearch_2025/) and Click into data/, scripts/ or any directory to see its contents (for example 01_data_cleaning.R), then use the up-arrow to return to the parent folder.</li><li><strong>Open R scripts</strong><br> Click a script name to load it into the Script Pane so you can start editing immediately.</li><li><strong>Import data</strong><br> In data/raw/, select a file like survey_data.csv and choose <strong>Import Dataset</strong>. RStudio will preview the data and show you the exact read.csv() (or readr::read_csv()) code to paste into your script.</li><li><strong>Manage files and folders</strong><br> Use <strong>New Folder</strong> to create directories. Right-click any item to rename or delete it. Just be aware that <strong>deletions cannot be undone</strong>.</li></ul><h4><strong>1.3 Environment Pane</strong></h4><p>This panel lists all the objects (<strong>data frames</strong>, <strong>vectors</strong>, <strong>functions </strong>and more) that are currently loaded into your R session. ‘You can click on an object to inspect its contents or double-click to open it in a spreadsheet-style view. Keeping an eye on the Environment Pane helps you verify that your scripts have produced the expected variables before you move on to analysis or reporting.</p><h3>2. Setting up Your R Project</h3><p>Getting your R project off the ground with a clear structure prevents chaos down the line. Follow these four essential steps to ensure every file, script and output lives exactly where you expect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*CsoUgj13SXrpiYtRhy3e5g.png" /><figcaption>New Project Wizard in R</figcaption></figure><p><strong>Overview of steps</strong></p><ol><li>Create your project folder and initialise the RStudio project</li><li>Establish the folder hierarchy</li><li>Create your first R script</li><li>Record the setup in CHANGELOG.md (for example: 2025-10-01: Created project structure)</li></ol><h4>2.1 Create a Project Folder</h4><ul><li>Create a new folder on your computer, e.g., MyResearch_2025</li><li>This keeps all project files together.</li></ul><h4>2.2 Use RStudio Projects</h4><ul><li>Open RStudio.</li><li>Go to <strong>File &gt; New Project.</strong></li><li>Choose <strong>Existing Directory</strong>, select your folder, and click <strong>Create Project</strong>.<br>This generates an .Rproj file (e.g., MyResearch_2025.Rproj) to link everything.</li></ul><h4>2.3 Organise Your Files</h4><p>Create these subfolders <strong>once </strong>inside your project folder and keep their names unchanged once set up:</p><pre>MyResearch_2025/<br>├── data/<br>│   ├── raw/              # Original data files (never edit)<br>│   └── processed/        # Cleaned or processed data files<br>├── scripts/              # R scripts (e.g., 01_data_cleaning.R, 02_analysis.R)<br>├── functions/            # Custom R functions (if any)<br>├── outputs/              # Generated figures, tables, etc.<br>├── docs/                 # Documentation and reference<br>│   └── session-info.txt  # R session information<br>├── README.md             # Project overview and instructions<br>├── CHANGELOG.md          # Log of project changes<br>└── MyResearch_2025.Rproj # RStudio project file</pre><h3>3. Creating R Scripts</h3><p>R scripts are the permanent record of your analysis. Unlike the console, they don’t vanish when you close RStudio. Store every script in your scripts/ folder so you can reproduce, share or revisit your work at any time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*AgZpxPJ_TRqETvrBAw6TOg.png" /><figcaption>Example R Script (Dummy Code)</figcaption></figure><h4><strong>Step 1: Create a New Script</strong></h4><ul><li>In RStudio, choose <strong>File &gt; New File &gt; R Script</strong>.</li><li>A blank script appears in the Script Pane (top-left).</li></ul><h4>Step 2: Write Your Code</h4><ul><li>Write your code with comments to explain each step.</li></ul><h4>Step 3: Save the Script</h4><ul><li>Save the script by clicking <strong>File &gt; Save a</strong>nd <strong>s</strong>ave it in the scripts/ sub folder. If the folder doesn’t exist, create it using the <strong>Files Pane</strong> or your file explorer.</li><li>Ideally, name it with a two-digit prefix, e.g., 01_data_cleaning.R, to keep scripts in order</li><li>The file will be saved as MyResearch_2025/scripts/01_data_cleaning.R.</li></ul><h3>4. Managing Data</h3><h4>4.1 Where to Store your Data</h4><ul><li><strong>Raw data:<br></strong>Place original files in data/raw and never edit them. This preserves the integrity of your source data.</li><li><strong>Processed Data:<br></strong>Use scripts to clean or modify data, saving results in data/processed/.<br><strong>Example:</strong> 01_data_cleaning.R loads data/raw/survey_data.csv and saves to data/processed/cleaned_survey_data.csv.</li></ul><h4>4.3 Importing and exporting files</h4><p>Before you dive into reading or writing data, it pays to understand how RStudio handles file paths.</p><p>By default, opening the .Rproj file sets your working directory to the project root, which means you can use simple, relative paths.</p><ul><li>Using <strong>relative paths </strong>allows <strong>portability</strong> and <strong>better reproducibility</strong> when importing and exporting files inside the project.</li><li>Using the <strong>here</strong> package allows paths to be set relative to the project root.</li></ul><pre># Instead of absolute path:<br>survey_data &lt;- read.csv(&quot;data/raw/survey_data.csv&quot;)<br>write.csv(clean_df, &quot;data/processed/clean_df_2025-05-06.csv&quot;, row.names = FALSE)<br><br># You can use a relative path  by using &#39;here&#39; <br>library(here)<br>survey_data &lt;- read.csv(here(&quot;data&quot;, &quot;raw&quot;, &quot;survey_data.csv&quot;))<br>write.csv(clean_df, here(&quot;data&quot;, &quot;processed&quot;, &quot;clean_df_2025-05-06.csv&quot;), row.names = FALSE)</pre><p><strong>Tips:</strong></p><blockquote>Always open the project via the .Rproj file to set the working directory correctly, and prefer here for robust file paths.</blockquote><blockquote>To work with files <strong>within the project folder, </strong>use <strong>relative paths</strong> to access files in subfolders to ensure portability.</blockquote><blockquote>To work with files <strong>outside the project folder,</strong> use<strong> absolute paths.</strong></blockquote><pre># Files outside project folder - Absolute paths <br>external_data &lt;- read.csv(&quot;/Users/yourname/Documents/external_data.csv&quot;)<br><br># Files within project folder - Relative paths<br>library(here)<br>survey_data &lt;- read.csv(here(&quot;data&quot;, &quot;raw&quot;, &quot;survey_data.csv&quot;))<br>write.csv(clean_df, here(&quot;data&quot;, &quot;processed&quot;, &quot;clean_df_2025-05-06.csv&quot;), row.names = FALSE)</pre><h4>4.4 Data handling and privacy</h4><p>Solid reproducibility begins with disciplined data handling.</p><ul><li>Treat everything in data/raw as read-only.</li><li>Use here::here() for all project file paths.</li><li>For sensitive information, follow your organisation’s data and privacy policies.</li></ul><h3>5. Saving and Resuming Your Work</h3><h4>Saving Your Work</h4><p>Think of saving like breathing: do it frequently and instinctively.</p><p><strong>Scripts</strong><br>Save frequently using <strong>Ctrl + S</strong> (Windows) or <strong>Cmd + S</strong> (Mac) every time you make a meaningful change. RStudio will even prompt you if you try to close without saving.</p><p><strong>Processed Data</strong><br>Never overwrite your raw files. When you write out cleaned data, include a date stamp in the filename so you can trace exactly when it was created. <br>For example:</p><pre># Manually add date<br>write.csv(<br>  clean_df, <br>  here::here(&quot;data&quot;, &quot;processed&quot;, &quot;clean_df_2025-05-06.csv&quot;), <br>  row.names = FALSE)<br><br># Automatically time stamp<br>write.csv(<br>  clean_df,<br>  here::here(&quot;data&quot;, &quot;processed&quot;, paste0(&quot;clean_df_&quot;, Sys.Date(), &quot;.csv&quot;)),<br>  row.names = FALSE<br>)</pre><p><strong>Avoid save.image()</strong><br> R’s built-in save.image() can feel convenient, but it often leads to hidden dependencies and version confusion.</p><ul><li>Instead, export each data object explicitly with write.csv(), saveRDS() or similar.</li><li>Re-run your scripts in order to rebuild your workspace from scratch. This is the ultimate test of reproducibility.</li></ul><p><strong>Change Log</strong><br> A <a href="https://keepachangelog.com/en/1.1.0/">change log</a> is a document to record every session’s milestones. <br>Create a CHANGELOG.mdin your root directory, and after each analysis session, append an entry like:</p><pre>## 2025-05-06<br>- Wrote cleaned survey data to data/processed/clean_df_2025-05-06.csv  <br>- Completed and reviewed scripts/01_data_cleaning.R  </pre><p>This single source of truth helps teammates and future you understand exactly what changed and when. An example of what a running change log may look like:</p><pre>## Changelog<br><br>#### 2025-05-10<br>- **Added**  <br>  - Section on using RStudio Projects  <br>  - Code examples for `here::here()`<br><br>- **Changed**  <br>  - Updated formatting in “Script vs Console” section<br><br>- **Fixed**  <br>  - Corrected typo in “Managing Data” heading<br><br>#### 2025-05-08<br>- Initial release of SOP for reproducible R projects<br>- Folder structure and script guidelines<br><br>## 2025-05-06<br>- Wrote cleaned survey data to data/processed/clean_df_2025-05-06.csv  <br>- Completed and reviewed scripts/01_data_cleaning.R</pre><h4>5.2 Resuming and Moving Projects</h4><ul><li><strong>Resuming:<br></strong>To resume work, reopen via the .Rproj file and run scripts to reload data.</li><li><strong>Moving: </strong>You can move your entire project folder anywhere. Opening the .Rproj file in the new location automatically updates the working directory. <br>There is no need to change any <strong>relative </strong>file paths in your code, but do check that absolute file paths are still accesssible.</li></ul><h3>6. Writing Code</h3><p>Writing code that’s both easy to follow and simple to validate is essential for reproducible research.</p><h4>Write Clear, Readable Code</h4><p>Good code reads like a well-written recipe. Aim for:</p><ul><li><strong>Descriptive names</strong> for objects and functions (clean_data rather than cd)</li><li><strong>Comments</strong> (#) to explain <em>why</em> you’re doing something, not just <em>what</em>:</li></ul><pre># Load raw survey data for March cohort<br>survey_data &lt;- read.csv(&quot;data/raw/survey_data.csv&quot;)</pre><ul><li><strong>Logical steps</strong>: group related lines together, leaving a blank line between distinct tasks</li><li><strong>Consistent style</strong>: adopt one indentation and naming convention (e.g. snake_case) throughout</li></ul><h4>Test and Iterate Quickly</h4><p>Rather than building long scripts in one go, test snippets as you write.</p><ul><li>Try code in the console or an R Notebook chunk</li><li>Once you confirm it works, copy the final lines into your script.</li><li>Use print() or View() sparingly to inspect intermediate results.</li></ul><p>By validating small blocks of code before integrating them, you catch errors early and keep your scripts flowing.</p><p><strong>Alternate workflow</strong><br>Some users prefer to write <strong>all code</strong> in scripts, commenting out lines they’re not currently using.</p><h4>Experiment</h4><p>You may want to explore new ideas without disrupting your main analysis:</p><ul><li>Create a separate test_code.R file for trial code and one-off experiments</li><li>Use throwaway data frames (e.g. test, check) to play with filters or plots</li><li>When you’re happy with an approach, transfer the polished version into your numbered script (e.g. 01_data_cleaning.R) and delete the test objects.</li></ul><pre># Delete test dataframes<br>rm(test, check)</pre><p>This approach keeps your working environment tidy and ensures that only vetted, reproducible code ends up in your final scripts.</p><h3>7. Using R Packages</h3><p>R packages extend R’s core functionality.</p><ul><li><strong>Base R</strong> equips you with fundamental tools</li><li><strong>Tidyverse </strong>collection offers a cohesive, intuitive set of packages (dplyr for data manipulation, ggplot2 for visualisation and more) that work together seamlessly.</li></ul><p>Proper package management means you can share your code with confidence, knowing it will run the same way on any machine.</p><h4>Installing and Loading Packages</h4><p>Installing a package is a one-off task on each computer. The below code demonstrates some common commands:</p><pre># For example, to install the Tidyverse suite:<br>install.packages(&quot;tidyverse&quot;)<br><br># Then, at the top of every session or script, load the packages you need<br>library(tidyverse)<br><br># If you prefer to load individual components, <br># you can do:<br>library(dplyr)<br>library(ggplot2)<br><br># Tip: To automate installation checks, <br># you might include at the start of your script<br>required_pkgs &lt;- c(&quot;tidyverse&quot;, &quot;here&quot;, &quot;renv&quot;)<br>for (pkg in required_pkgs) {<br>  if (!requireNamespace(pkg, quietly = TRUE)) install.packages(pkg)<br>  library(pkg, character.only = TRUE)<br>}</pre><h4>Ensuring Consistency with renv</h4><p>R’s renv package lets you lock in exact versions of every package, avoiding “it works on my machine” issues:</p><pre># Install and load renv<br>install.packages(&quot;renv&quot;)<br>library(renv)<br><br># Initialise the project environment<br>renv::init()<br><br># Snapshot the current state<br>renv::snapshot()<br><br># Restore on another system<br>renv::restore()</pre><p>By recording your package versions in renv.lock, you guarantee that anyone who opens your .Rproj and runs renv::restore() will rebuild the identical library you used, making your analysis fully reproducible.</p><h3>8. Documentation and Reproducibility</h3><p>Proper documentation ensures your project is understandable and reproducible for both yourself and others. Maintain the following files in your project to record essential metadata and instructions.</p><h3>8.1 Documentation</h3><p>Maintain these core files in your project:</p><p><strong>README.md</strong><br> Your front door. Describe in plain language what the project does, why it exists and how to run it. Include:</p><ul><li><strong>Purpose</strong>: A one-sentence summary (“Analyse health survey data to identify risk factors”)</li><li><strong>Prerequisites</strong>: R version, required packages</li><li><strong>Folder structure</strong>: Brief overview of data/, scripts/, outputs/, docs/</li><li><strong>Usage</strong>: How to run your scripts in order</li><li><strong>Contact</strong>: Who to reach if things break</li></ul><p><em>Example snippet</em></p><pre>**Purpose**  <br>Analyse survey data to examine patient outcomes by age group.  </pre><pre>**Prerequisites**  <br>- R ≥ 4.1.0  <br>- Packages: tidyverse, here, renv  </pre><pre>**Folder structure**  <br>- `data/raw/`  <br>- `data/processed/`  <br>- `scripts/01_data_cleaning.R` → run first  <br>- `outputs/`  </pre><pre>**Usage**  <br>1. Open `MyResearch_2025.Rproj`  <br>2. In RStudio, source `scripts/01_data_cleaning.R`  <br>3. Then source `scripts/02_analysis.R`</pre><p><strong>session-info.txt</strong><br> Capture your exact R environment. At the end of your final script, add:</p><pre>writeLines(<br>  capture.output(sessionInfo()),<br>  here::here(&quot;docs&quot;, &quot;session-info.txt&quot;)<br>)</pre><p>This logs R version, operating system and package versions — crucial for tracing subtle differences.</p><p><strong>CHANGELOG.md</strong><br> Track every meaningful update with dates. Follow a simple, reverse-chronological format:</p><pre>## 2025-05-07<br>- Added `scripts/02_analysis.R` for summary statistics  <br>- Updated data cleaning to handle missing BMI values  <br><br>## 2025-05-06<br>- Created `scripts/01_data_cleaning.R` to import and clean raw data  <br>- Defined project folder structure</pre><blockquote><strong><em>Tip</em></strong><em>: Consider including a small </em><strong><em>data dictionary</em></strong><em> (</em><em>docs/data_dictionary.md) that lists each CSV, its columns, data types and a brief description. New collaborators will thank you.</em></blockquote><h4>8.2 Creating Reports with R Markdown</h4><p>Turn your analysis into polished reports that combine code, visuals and explanations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*3H_Ck02uy2iZwyoE" /><figcaption>Source: <a href="https://smac-group.github.io/ds/rmarkdown.html">https://smac-group.github.io/ds/rmarkdown.html</a></figcaption></figure><ol><li>In RStudio choose <strong>File &gt; New File &gt; R Markdown</strong>.</li><li>Save it in docs/ (e.g. docs/report.Rmd) to keep reports organised.</li><li>Write your story, mixing written text and code chunks:</li></ol><pre>```markdown<br># Data Completeness Check<br><br>Before analysis, we checked for missing values in key variables.<br><br>```{r missing-check}<br>df &lt;- read.csv(here(&quot;data&quot;, &quot;processed&quot;, &quot;clean_df.csv&quot;))<br>missing_pct &lt;- sapply(df[, c(&quot;age&quot;, &quot;outcome&quot;)], function(x) mean(is.na(x)))<br>missing_pct</pre><p>4. Click <strong>Knit</strong> to generate HTML, PDF or Word output.</p><p>5. Store the final output in docs/ or outputs/reports/ so it’s versioned alongside your code.</p><h4>8.3 Reproducibility Checklist</h4><p>Before you share or archive your project, run through this checklist to guarantee someone else (or future you) can pick up exactly where you left off:</p><ol><li><strong>Save your work </strong>and<strong> Restart R</strong> to clear the environment.</li></ol><p>2. <strong>Open the </strong><strong>.Rproj</strong> to ensure the working directory is correct.</p><p>3. <strong>Run all scripts</strong> in the correct order to recreate your analysis. For example:</p><pre># Run all scripts in the correct order (with relative paths)<br>source(here(&quot;scripts&quot;, &quot;01_data_cleaning.R&quot;)) <br>source(here(&quot;scripts&quot;, &quot;02_analysis.R&quot;))</pre><p>4. <strong>Verify outputs</strong>: Confirm that figures, tables or CSVs in outputs/ are up to date.</p><p>5. <strong>Knit reports</strong>: If applicable, knit your R Markdown document and check for errors.</p><p>6.<strong> Update </strong><strong>CHANGELOG.md</strong> with today’s date and any final changes.</p><p>7. <strong>Close RStudio</strong>, allowing it to prompt you to save any unsaved scripts.</p><h3>Troubleshooting</h3><ul><li><strong>Files missing? </strong>Open the .Rproj file and verify folder names and paths.</li><li><strong>Package won’t load? </strong>Run install.packages(&quot;pkg&quot;) or renv::restore() then library(pkg).</li><li><strong>Script errors? </strong>Check you’ve run earlier scripts in order, confirm object names and loaded libraries.</li><li><strong>Plots not appearing? </strong>In R Markdown, knit the document. In the console, wrap plots in print() or call dev.off().</li><li><strong>Cache issues? </strong>Clear the cache folder or set cache=FALSE on the chunk.</li><li><strong>Performance or memory problems? </strong>Try <strong>data.table</strong>, process data in chunks or increase R’s memory limit.</li><li><strong>Write permission errors? </strong>Ensure you have write access to the target directory or run RStudio with elevated rights.</li><li><strong>Need more error detail? </strong>Use traceback(), debug() or insert browser() to inspect failures.</li></ul><h3>Resources</h3><ul><li><strong>here</strong>: <a href="https://cran.r-project.org/package=here">https://CRAN.R-project.org/package=here</a></li><li><strong>renv</strong>: <a href="https://rstudio.github.io/renv/articles/renv.html">https://rstudio.github.io/renv/articles/renv.html</a></li><li><strong>Tidyverse Style Guide</strong>: <a href="https://style.tidyverse.org/">https://style.tidyverse.org/</a></li><li><strong>Reproducible Research</strong>: <a href="https://bookdown.org/rdpeng/reproducible-research/">https://bookdown.org/rdpeng/reproducible-research/</a></li><li><strong>R for Data Science</strong> (2nd ed): <a href="https://r4ds.hadley.nz/">https://r4ds.hadley.nz/</a> <a href="https://r4ds.hadley.nz/?utm_source=chatgpt.com">R for Data Science</a></li><li><strong>R Markdown: The Definitive Guide</strong>: <a href="https://bookdown.org/yihui/rmarkdown/">https://bookdown.org/yihui/rmarkdown/</a> <a href="https://bookdown.org/yihui/rmarkdown/?utm_source=chatgpt.com">Bookdown</a></li><li><strong>Learn the tidyverse</strong>: <a href="https://www.tidyverse.org/learn/">https://www.tidyverse.org/learn/</a> <a href="https://www.tidyverse.org/learn/?utm_source=chatgpt.com">Tidyverse</a></li><li><strong>R Packages</strong> (2nd ed): <a href="https://r-pkgs.org/">https://r-pkgs.org/</a> <a href="https://r-pkgs.org/?utm_source=chatgpt.com">R Packages</a></li><li><strong>R Graphics Cookbook</strong> (2nd ed): <a href="https://r-graphics.org/">https://r-graphics.org/</a> <a href="https://r-graphics.org/?utm_source=chatgpt.com">R Graphics Cookbook, 2nd edition</a></li><li><strong>Posit Cheatsheets</strong>: <a href="https://posit.co/resources/cheatsheets/">https://posit.co/resources/cheatsheets/</a> <a href="https://posit.co/resources/cheatsheets/?utm_source=chatgpt.com">Posit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40188ab2a7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12 Ways to Use Gen AI in Your Data Science Workflow]]></title>
            <link>https://medium.com/@honzj/12-ways-to-use-gen-ai-in-your-data-science-workflow-4a18ddef4298?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a18ddef4298</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 09:21:28 GMT</pubDate>
            <atom:updated>2024-01-28T10:27:25.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>12 Ways to Use Generative AI in Your Data Science Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecAVyxDF_C20QMTxPhbT_w.png" /></figure><p>It‘s’ been a crazy few years. Just a short while ago, the buzz around transformer models was confined to the inner circles of data science.</p><p>Rewinding a few years, a <a href="https://www.economist.com/graphic-detail/2018/04/24/a-study-finds-nearly-half-of-jobs-are-vulnerable-to-automation">Harvard Study</a> stirred the pot by predicting which jobs were most susceptible to automation. It painted a grim future for many blue-collar roles, fueling a mantra that urged people to ‘learn to code’ as a safe harbour against the automation wave.</p><p>Today, Gen AI has not just dipped its toes but plunged headfirst into transforming how we do our work, leaving few domains untouched. Interestingly enough, the knowledge workers felt the ripples first…including coders.</p><p>In this article, I’ll share my 12 top Generative AI (Gen AI) use cases to maximise productivity after a year of regular use in my data science workflow. We’ll also learn about tools, crafting effective prompts, and the necessary cautions for using Gen AI.</p><h3>Will I Be Replaced by Gen AI?</h3><p>The rise of Gen AI poses a critical question: Will it replace data scientists?</p><p>While arguments exist on both sides, it certainly indicates a shift. As data scientists, our advantage lies not in routine tasks but in leveraging these tools to stay ahead.</p><p>In my opinion, Gen AI is a collaborator, not a competitor. We can use it to augment our strengths and let it take over these monotonous, time-consuming tasks. This frees us to focus on areas where we excel, such as strategic thinking, complex problem-solving, nuanced domain knowledge, and genuine human creativity.</p><p>This is where our true value lies. Our role is evolving from being pure data handlers to strategic, innovative thinkers. In embracing Gen AI, we’re not stepping back. We’re stepping up. This doesn’t just maintain our relevance in the field, it amplifies it.</p><h3>Gen AI Tools</h3><p>We now have a wide range of Gen AI tools at our disposal. However, there are two standout tools that I find myself consistently relying on in my daily work:</p><h4><strong>ChatGPT</strong></h4><p>The original disruptor we all know about. It’s a valuable resource for answering questions, generating code snippets, and brainstorming ideas.</p><p>The free version is sufficient for most cases. However, if you can afford the subscription, premium access to GPT4 offers a decent quality improvement.</p><h4><strong>GitHub Copilot</strong></h4><p>This AI-powered code assistant from GitHub helps provide code suggestions, auto-completion, and documentation.</p><p>With the introduction of the ‘Chat’ feature, this has become a recent favourite of mine. The VS Code extension gives you a chat window directly in your code editor. This further streamlines the process and enables you to ask questions about any programs you have open. It is also quite good value when compared to the cost of chatGPT premium.</p><h3>Writing a Great Prompt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8mFwxY6YEQJBhg6mba3Yw.png" /></figure><p>Crafting great prompts for interactions with Gen AI can dramatically improve your results. Here are some essential tips to ensure your prompts yield accurate and relevant responses:</p><ol><li><strong>Detailed prompts: </strong>Provide comprehensive and precise prompts that leave no room for ambiguity. Clarity in your request enhances the AI’s understanding of your needs.</li><li><strong>Context matters: </strong>Furnish context by describing the relevant background or scenario. This context aids the AI in generating responses that align with the specific context. You can also develop and refine the context over multiple prompts.</li><li><strong>Specify the role: </strong>When necessary, instruct the AI to “act as” a particular entity or persona. This directive helps in tailoring the response from a specific perspective.</li><li><strong>Scope and tone:</strong> Define the scope of your request, specifying the level of detail required. Additionally, you can communicate the desired tone, whether it should be professional, casual, or any other style appropriate for the context.</li></ol><p>For Example:</p><p><strong>Bad:</strong></p><blockquote>“Tell me about AI”</blockquote><p>This prompt is too broad and lacks focus. It doesn’t specify what aspect of AI the user is interested in, leading to a generic response.</p><p><strong>Good:</strong></p><blockquote>“Please play the role of a senior data scientist speaking to a non-technical stakeholder. Expand on the impact of artificial intelligence on healthcare, considering its applications in diagnosis, treatment, and patient care.”</blockquote><p>This prompt defines the topic, scope, and focus areas, allowing the AI to provide a comprehensive response.</p><h3>Cautions for Using Gen AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-0D_adydkSxhOTvdOUZmA.png" /></figure><p>Like any powerful tool, it’s crucial to use Gen AI judiciously, understanding both its strengths and limitations. Here are some key things to keep in mind:</p><ul><li><strong>Critical thinking: trust but verify<br></strong>Never take AI-generated content as the absolute truth. Always exercise your own judgment. Personally, I use Gen AI to expedite repetitive tasks or to provide alternative perspectives, but I always ensure I understand what it is doing. If you don’t understand the outputs, <strong>always </strong>verify them.</li><li><strong>AI hallucinations: expect the unexpected<br></strong>Gen AI can sometimes produce inaccurate or nonsensical outputs. This is particularly common with generated links, quotes, or references (as of the writing of this article, anyway). Approach these with a healthy dose of scepticism.</li><li><strong>Questionable internet sources: tread carefully<br></strong>Language Models (LLMs) are trained on content from the internet, and there is a lot of junk out there. Be mindful of potential bias, misinformation or inaccuracies in AI responses.</li><li><strong>Data sensitivity: protect your information<br></strong>Remember, any prompt you input is sent to an AI model on an external server. Never share any personal, sensitive, or proprietary data in your prompts to safeguard your privacy.</li><li><strong>Lack of human judgment: AI is not human<br></strong>LLMs lack human judgment, even though they can mimic it convincingly. Their responses are based on patterns learned from data, not genuine understanding or ethical reasoning.</li><li><strong>Overreliance: maintain a balanced approach<br></strong>While Gen AI tools are incredibly powerful, relying on them too heavily can hinder the development of your own skills and critical thinking. It’s important to use these tools as aids, not crutches. Remember that original and out-of-the-box thinking often comes from human insight.</li><li><strong>Copyright awareness<br></strong>Be aware of potential copyright issues. Gen AI models can inadvertently reproduce or plagiarise content from their training data. Always use generated content responsibly and ethically.</li></ul><h3>Time-Saving Use Cases for Gen AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FK4Wu_z6-uC571bUC9wBg.png" /></figure><p>Here are 12 use cases where I’ve found massive time savings. Let’s go!</p><h4><strong>1. Formatting and commenting code</strong></h4><p>We now have zero excuses for not producing well-formatted and commented code. Luckily, adhering to best practices has never been easier. Trust me, anyone who has to read your code will thank you.</p><p><strong>Always </strong>proofread the outputs to ensure the comments accurately reflect the code’s purpose and functionality and <strong>Never </strong>paste personal, sensitive or proprietary data into a chat window (this applies to all interactions with Gen AI, so I won’t repeat myself from here on).</p><p>Example prompts:</p><blockquote>“Give my function a docstring, and inline comments explaining what it is doing &lt;insert code here&gt;”.</blockquote><blockquote>“Format this code to PEP8 Standards: <br>&lt;insert code here&gt; ”.</blockquote><pre># Before PEP8:<br># =============<br>def doComplexCalculation(x,y):<br>    if x&gt;10 and y&lt;5:z=x*y<br>    else:z=x+y<br>    return z<br><br># After PEP8:<br># =============<br>def do_complex_calculation(x, y):<br>    &quot;&quot;&quot;<br>    Perform a complex calculation based on input values.<br><br>    If x is greater than 10 and y is less than 5, multiply x and y.<br>    Otherwise, add x and y.<br><br>    Args:<br>        x (int): The first input value.<br>        y (int): The second input value.<br><br>    Returns:<br>        int: The result of the complex calculation.<br>    &quot;&quot;&quot;<br>    if x &gt; 10 and y &lt; 5:<br>        # Multiply x and y if the condition is met<br>        result = x * y<br>    else:<br>        # Add x and y if the condition is not met<br>        result = x + y<br>    return result</pre><h4>2. Documenting your work</h4><p>The importance of documenting your work cannot be overstated. While essential, this task often falls into the ‘tedious but necessary’ category, and it’s easy to procrastinate. Here are some things you can try:</p><ul><li>Explain your process at various levels of complexity.</li><li>Generate a README file for your Git repository.</li><li>Produce documentation using a standardised template.</li></ul><p>Example prompt:</p><blockquote>“You are a technical writer tasked with documenting code. Using the headings: Title, Description, Author, Date Created, Version, Dependencies, Usage, Example, write a high level overview of the code. <br>&lt;insert code here&gt;”.</blockquote><h4>3. Generating visualisations</h4><p>Some of us may know various plotting packages back to front, but for us mere mortals, this is yet another massive time saver. Gen AI allows us to simply describe the chart we want to see and skip the whole lookup process.</p><p>This will dramatically reduce the time you spend in documentation and on stack overflow looking up the parameters for that plotting function.</p><p>Example prompt:</p><blockquote>“Generate Python code using Seaborn to create a line plot that visualises the trend of monthly sales data. The x-axis should represent months, and the y-axis should show the sales figures. Please include appropriate labels, titles, and legend.</blockquote><h4>4. Generating regex</h4><p>Regular expressions (regex) are a powerful tool in data science, essential for parsing and processing text data. However, mastering regex can be daunting.</p><p>With Gen AI, you can generate regex patterns that precisely match your criteria: emails, phone numbers, or a custom text pattern. This lets you focus on text-processing tasks without memorising complex regex rules.</p><p>Example prompt:</p><blockquote>“Generate a regular expression pattern to match email addresses. The email addresses should follow the format ‘user@example.com’. Please provide the regex pattern that accurately matches email addresses in this format.”</blockquote><pre>^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$</pre><h4>5. Generalising your functions</h4><p>If you have worked through a chunk of code, you may want to ‘modularise’ it as a generalised function to follow good practice.</p><p>Doing this manually can lead to an impromptu debugging session that can waste your valuable time. Luckily, this is an area where Gen AI can be much more detail-oriented than we often are (especially late afternoon when the coffee has worn off)</p><p>Example prompt:</p><blockquote>“Transform the given code into a Python function named plot_histogram that takes the following inputs: dataset_path, x_column, title, x_label and y_label. &lt;insert code here&gt;”</blockquote><h4>6. Text summarisation</h4><p>If you’re faced with the daunting task of parsing through a lengthy technical document or need to find specific information quickly, Gen AI can do the following for you:</p><ul><li>Summarise the text, highlighting key points and themes.</li><li>Direct the AI to extract precise answers for specific questions, effectively making it a focused reader.</li><li>Tailor summary for different audiences with requests like “Explain this like I’m five years old”.</li></ul><p>Example prompts:</p><blockquote>“Condense this lengthy research paper into a concise summary. Provide key findings, methodology, and conclusions.<br>&lt;insert text here&gt;”</blockquote><blockquote>“Search through this technical manual and extract information about troubleshooting common issues with ‘Product X’.<br>&lt;insert text here&gt;”</blockquote><blockquote>“Rewrite this complex scientific article in a way that a high school student can easily understand.<br>&lt;insert text here&gt;”</blockquote><h4>7. Polishing content</h4><p>You can have Gen AI proofread your written content and make tweaks. This is useful for emails, presentations, articles and documentation. If you have the core message of the content down, you don’t have to grind away ‘wordsmithing’ it to perfection.</p><ul><li>Make concise and punchy headlines</li><li>Proofreading for spelling and grammatical mistakes</li><li>Modifying the tone to be more polite/clear/professional</li></ul><p>Example prompts:</p><blockquote>“Please proofread this content for any spelling and grammatical errors. Focus on clarity and readability.<br>&lt;insert text here&gt;”</blockquote><blockquote>“Edit this email for brevity and clarity. It should convey the intended message in a polite and professional tone.<br>&lt;insert text here&gt;”</blockquote><blockquote>“Revise this technical documentation to ensure it is clear, concise, and free of jargon. Make it accessible to a non-technical audience.<br>&lt;insert text here&gt;”</blockquote><h4>8. Performance optimising your code and queries</h4><p>This is a great one. You can actually learn a fair bit from the outputs, too. Manually optimising code can be a drawn-out journey of trial and error, often involving hours scouring Stack Overflow and repeatedly running your code.</p><p>Optimising code can also translate to tangible savings for you or your employer in a cloud computing environment, where you’re billed for the resources you consume.</p><p>If you’re out of ideas on how to speed your process or query up, you can try the below examples:</p><p>Example prompts:</p><blockquote>“I’m looking to make this data processing function more computationally efficient. Can you suggest improvements to speed it up?<br>&lt;insert code here&gt;”</blockquote><blockquote>“The current query is running slowly on large datasets. Please provide optimisations to make it more efficient and reduce processing time.<br>&lt;insert code here&gt;”</blockquote><h4>9. Debugging code</h4><p>Don’t waste your brainpower parsing those long error tracebacks. Your Gen AI assistant can explain it to you.</p><ul><li>Gen AI interprets errors within your code’s context, simplifying debugging.</li><li>Providing Gen AI with code context allows for easier identification of issues.</li><li>Collaborating with Gen AI in debugging enhances your own skills and understanding of common pitfalls and best practices.</li></ul><p>Example prompt:</p><blockquote>“I need assistance in pinpointing the source of errors in my code. By providing context, can you help me identify where the issues are and offer solutions? <br>&lt;insert error traceback here&gt;”</blockquote><h4>10. Testing your code</h4><p>Testing is a crucial component of data science, and Gen AI significantly streamlines this process, boosting both efficiency and accuracy.</p><ul><li><strong>Sample data generation:</strong> Quickly create tailored sample data, bypassing the laborious manual process of dataset creation.</li><li><strong>Creating testing functions:</strong> Gen AI can also assist in crafting functions that rigorously check your code’s correctness, leading to more robust and error-free results.</li><li><strong>Efficiency gains: </strong>Automating these aspects of testing accelerates the entire verification process, freeing you to focus more on enhancing and refining your data science projects.</li></ul><p>Example Prompts:</p><blockquote>“I need to generate sample data for testing purposes. Can you quickly create customised sample data with columns X, Y, Z to streamline the testing process?”</blockquote><blockquote>“I’m conducting data quality checks, and one aspect is identifying duplicate records in my dataset. Create a testing function that checks for and highlights duplicate entries.”</blockquote><h4>11. Explaining concepts</h4><p>Use Gen AI to demystify unfamiliar concepts. This is an effective way to broaden your knowledge base. Treat the explanations as a ‘jumping off point’ for further research rather than taking them at face value.</p><ul><li>Quickly get a high-level understanding of an unfamiliar topic.</li><li>Use the explanations as a foundation upon which you can build a more comprehensive understanding</li><li>It can also help you explain tricky concepts in simpler terms. It’s super handy for sharing ideas without getting tangled up in jargon.</li></ul><p>Example prompts:</p><blockquote>“I want to understand the basics of reinforcement learning in AI. Can you provide a clear explanation and guide me towards areas of research that can enhance my knowledge?”</blockquote><blockquote>“Imagine you’re a seasoned data scientist addressing a group of beginners. Explain the concept of overfitting in machine learning in simple terms, and suggest practical methods to avoid it.”</blockquote><blockquote>“Imagine you’re a machine learning researcher discussing reinforcement learning with fellow researchers. Elaborate on the challenges of exploration vs. exploitation and propose strategies to address them.”</blockquote><h4>12. Swift proof-of-concepts</h4><p>Proof-of-concepts (POCs) serve as a preliminary step, offering a glimpse into the viability of your projects before committing substantial resources. You can accelerate the creation of POCs with Gen AI, enabling you to assess ideas’ feasibility with minimal time investment.</p><p>Always exercise caution with generated code. It’s imperative to thoroughly understand it before integrating it into decision-making processes. While Gen AI is excellent for initiating POCs, transforming them into fully-fledged projects requires expert judgement and understanding.</p><p>Example prompts:</p><blockquote>“I’m exploring the feasibility of a new recommendation system for e-commerce. Generate code for a quick proof-of-concept that demonstrates how collaborative filtering works in this context.”</blockquote><blockquote>“As a data scientist working on churn prediction, create Python code for a proof-of-concept churn prediction model using XGBoost. Your task is to demonstrate the feasibility of this approach. Include data loading, feature engineering, model training, and evaluation steps. Please add comments to explain each part of the code for clarity.”</blockquote><blockquote>“Imagine you’re a data scientist working on text classification for customer support tickets. Create Python code for a proof-of-concept text classification model using NLP techniques. Your goal is to demonstrate the value of this approach. The POC should involve data preprocessing, feature extraction, model training, and evaluation. Ensure you provide comments to clarify each code segment.”</blockquote><h3>Step Into the Future</h3><p>Ready to supercharge your data science workflow with Gen AI? There’s no better time than now to dive in, experiment, and push the boundaries of what’s possible. The future is here, and it’s in your hands.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a18ddef4298" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Feature Selection: Elevate your Machine Learning Game]]></title>
            <link>https://medium.com/@honzj/mastering-feature-selection-elevate-your-machine-learning-game-a70a52b6f243?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a70a52b6f243</guid>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 08:12:34 GMT</pubDate>
            <atom:updated>2023-04-02T08:15:13.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeOOtIj8CwCueNEwUZ55YQ.png" /></figure><h3>What is feature selection, and why do it?</h3><p>Building an accurate and efficient machine learning model is no small feat, and we can take many approaches to improve our models&#39; accuracy and efficiency. Selecting the most relevant and informative features from your dataset is one such way. Much like a chef will select the right ingredients for the dish, we must select the right features for our model. Enter the world of feature selection.</p><p>Alongside feature engineering, hyperparameter tuning, algorithm selection and regularisation, an essential tool in your <a href="https://medium.com/@h.jurza/chaos-to-order-data-pre-processing-for-machine-learning-mastery-9921345ba7d0">data pre-processing</a> toolkit.</p><blockquote>As the old saying goes, “garbage in, garbage out” — if your dataset contains irrelevant or noisy features, your model’s performance will suffer, no matter how good your algorithm is.</blockquote><p>In this article, we’ll take a closer look at the world of feature selection and explore the three main types of methods:</p><ol><li><strong>Filter methods</strong></li><li><strong>Wrapper methods</strong></li><li><strong>Embedded methods</strong></li></ol><p>We’ll cover how each method works and provide practical examples in Python to help you implement them in your own projects. The examples explore classification and regression examples, using the breast cancer dataset, and automobile datasets respectively. Let’s get started!</p><p>For the full notebooks, visit here:</p><ul><li><a href="https://github.com/J-Jurza/tutorial_feature_selection/blob/main/feature_selection_classification.ipynb">Notebook — Feature selection (Classification example)</a></li><li><a href="https://github.com/J-Jurza/tutorial_feature_selection/blob/main/feature_selection_regression.ipynb">Notebook — Feature selection (Regression example)</a></li></ul><h3>Filter Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Evxi4xmbXitL40lsdxGqqw.png" /></figure><p>Filter methods are a type of feature selection that evaluate the relevance of each feature in a dataset based on statistical measures such as correlation, chi-squared or ANOVA tests. They select the top K features that have a high correlation with the target variable, reducing dimensionality and improving model performance.</p><p>While filter methods are computationally efficient and can handle large datasets, they do not consider the interactions between features, or the model being used. Nonetheless, filter methods are a popular choice in the data science community due to their simplicity and effectiveness in reducing dimensionality and improving model performance. Some common filter methods include Pearson’s correlation coefficient, chi-squared test, ANOVA and mutual information.</p><p><strong>Pros:</strong></p><ol><li>Computationally efficient and scalable.</li><li>Independent of the learning algorithm.</li><li>Simple to understand, implement, and interpret.</li></ol><p><strong>Cons:</strong></p><ol><li>Limited performance compared to wrapper or embedded methods.</li><li>Ignores potential feature interactions.</li><li>Sensitive to data pre-processing.</li><li>Unable to capture complex relationships between features and target.</li></ol><p><strong>Regression</strong></p><ul><li><strong>Pearson correlation:</strong> Measures the strength and direction of a linear relationship between two continuous variables.</li><li><strong>Spearman correlation:</strong> Assesses the monotonic relationship between two continuous or ordinal variables, based on their ranks.</li><li><strong>Kendall correlation: </strong>Evaluates the ordinal association between two variables by comparing the number of concordant and discordant pairs.</li></ul><p><strong>Classification</strong></p><ul><li><strong>Chi-squared test:</strong> A statistical test that checks the independence between categorical variables in a contingency table.</li><li><strong>Fisher score:</strong> Computes the ratio of between-class variance to within-class variance for each feature, helping to understand how well a feature separates different groups or classes.</li></ul><p><strong>Regression or classification</strong></p><ul><li><strong>ANOVA F-test:</strong> Compares the means of two or more groups to determine if there is a significant difference among them. (Applicable when the target variable is numeric and features are categorical)</li><li><strong>Mutual information:</strong> Quantifies the reduction in uncertainty about one variable, given the knowledge of another.</li></ul><h4>Filter Method Implementation in Python</h4><p>Here we can apply correlation feature selection to the automobile dataset.</p><p>First, we will do some data pre-processing and build a baseline model using linear regression (see <a href="https://github.com/J-Jurza/tutorial_feature_selection/blob/main/feature_selection_regression.ipynb">notebook </a>for more details)</p><p>Then we can select the top features. Here we will select the best 15 features based on using f_regression. We begin by employing the SelectKBest class from the sklearn.feature_selection module, which allows us to select the top k features based on a specified scoring function. In our case, we choose f_regression as the scoring function setk=n_features, which represents the number of top features we want to select.</p><p>Next, we obtain the indices of the selected features using the get_support() method. With this information, we create new DataFrames X_train_corr and X_test_corr that contain the filtered training and testing sets, respectively.</p><pre>from sklearn.feature_selection import SelectKBest, f_regression<br><br>n_features = 15<br><br># Apply Pearson correlation feature selection to select the top features<br>selector = SelectKBest(f_regression, k=n_features)<br>X_filter = selector.fit_transform(X, y)<br><br># Get the indices of the selected features<br>mask = selector.get_support()<br><br># Make dataframe with new features<br>X_train_corr = X_train.loc[:,mask]<br>X_test_corr = X_test.loc[:,mask]<br>new_features = X_train.loc[:,mask].columns.tolist()<br><br># Print the selected features<br>print(&quot;Selected features:&quot;, new_features)<br><br># Preview filtered dataset<br>X_train_corr.head()</pre><p>The method is the same for chi-squared and ANOVA, you simply change the scoring function to <strong>f_classif </strong>or <strong>ch,i-2</strong> respectively.</p><p>If we wish to see the features ranked in importance, We can make a data frame of the feature importances using the below code:</p><pre># Get the feature importances<br>scores = selector.scores_<br>feature_importances = {feature_name: score for feature_name, score in zip(X_train.columns, scores)}<br><br># Create a dataframe and sort<br>feature_importances = pd.DataFrame(feature_importances.items(), columns=[&#39;Feature&#39;, &#39;Importance&#39;])\<br>    .sort_values(&#39;Importance&#39;, ascending=True)</pre><p>We can then plot the output using the below function. We can pass the importance from any of our selectors. For example, using reason correlation:</p><pre>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br>def plot_importances(df_in, title):<br>  &quot;&quot;&quot;make a horizontal bar chart of feature importances&quot;&quot;&quot;<br><br>    # Plot the feature importances in sorted order<br>    # Set plot style<br>    plt.style.use(&#39;seaborn-darkgrid&#39;)<br><br>    # Create horizontal bar plot<br>    sns.set_style(&#39;whitegrid&#39;)<br>    sns.set_palette(&#39;magma&#39;)<br>    fig, ax = plt.subplots(figsize=(8, 6))<br>    sns.barplot(x=&#39;Importance&#39;, y=&#39;Feature&#39;, data=df, orient=&#39;h&#39;)<br>    ax.set_title(title, fontsize=16)<br>    ax.set_xlabel(&#39;Importance Scores&#39;, fontsize=12)<br>    ax.set_ylabel(&#39;Features&#39;, fontsize=12)<br>    ax.tick_params(axis=&#39;both&#39;, which=&#39;major&#39;, labelsize=12)<br>    ax.invert_yaxis()<br>    plt.show()<br><br># Get the feature importances and plot<br>scores = selector.scores_<br>feature_importances = {feature_name: score for feature_name, score in zip(X_train.columns, scores)}<br>feature_importances = pd.DataFrame(feature_importances.items(), columns=[&#39;Feature&#39;, &#39;Importance&#39;])\<br>    .sort_values(&#39;Importance&#39;, ascending=True)<br><br># Plot feature imporances<br>plot_importances(feature_importances, &#39;Feature Importances based on Pearson Correlation&#39;)<br></pre><p>This will produce the following plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*X66zwt4_kJFE780NygQP6Q.png" /></figure><p>We can then fit the model using our selected features, and evaluate it using RMSE and MAE. In our case, it slightly improved performance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*bbavWHCi8zklfXygBEyh0Q.png" /></figure><h3>Wrapper Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UszpuSESJeHcjF3SXmiRw.png" /></figure><p>Wrapper methods are a class of feature selection techniques that select subsets of features by evaluating the performance of a machine learning model with different subsets. They allow us to use our own algorithm and ‘wrap’ it with a technique for finding the best set of features for that model. Wrapper methods use a search algorithm to explore the space of possible feature subsets and select the subset that yields the best performance. This technique can handle complex feature interactions and non-linear relationships between features and the target variable. However, wrapper methods can be computationally expensive and may suffer from overfitting if the search space is too large. Additionally, the performance of the selected subset may depend on the specific machine learning algorithm and hyperparameters used.</p><h4>Recursive Feature Elimination</h4><p>Recursive Feature Elimination (RFE) is a wrapper feature selection technique that recursively removes the least important features until a desired number of features is reached. RFE uses a machine learning algorithm to evaluate the performance of different feature subsets and selects the subset that yields the best performance.</p><p><strong>Pros:</strong></p><ul><li>Can handle complex feature interactions and non-linear relationships.</li><li>Considers the performance of different feature subsets.</li><li>Can improve the accuracy and interpretability of the model.</li><li>Can handle datasets with a large number of features.</li></ul><p><strong>Cons:</strong></p><ul><li>Can be computationally expensive.</li><li>May suffer from overfitting if the search space is too large.</li><li>The performance of the selected subset may depend on the specific machine learning algorithm and hyperparameters used.</li></ul><p>Example using the automobile dataset:</p><pre>import pandas as pd<br>from sklearn.feature_selection import RFE<br>from sklearn.linear_model import LinearRegression<br><br># Create a model object <br>model = LinearRegression()<br><br># Create a Recursive Feature Elimination object<br>rfe = RFE(estimator=model, n_features_to_select=n_features, step=1)<br><br># Fit the RFE object to the data<br>rfe.fit(X_train, y_train.values.ravel())<br><br># Filter the dataset for the selected features<br>X_train_rfe = X_train.iloc[:,rfe.support_]<br>X_test_rfe = X_test.iloc[:,rfe.support_]<br>selected_features = X_train_rfe.columns<br><br># Print the selected features<br>print(&#39;Selected features:&#39;)<br>print(selected_features)<br><br># Get the feature importances and plot<br>df_importance = pd.DataFrame({&#39;Feature&#39;: X_train.columns, &#39;Importance&#39;: rfe.ranking_})<br>df_importance = df_importance.sort_values(by=&#39;Importance&#39;, ascending=True)<br>plot_importances(df_importance, &#39;Feature Imporances based on RFE&#39;)<br><br># Show the filtered dataset<br>X_train_rfe</pre><h4>Sequential Feature Selection (SFS)</h4><p>Sequential Feature Selection (SFS) is another wrapper feature selection technique that searches through the feature space by adding (or removing) features one at a time until a desired number of features is reached. SFS will use our machine learning algorithm to evaluate the performance of different feature subsets and selects the subset that yields the best performance. This technique can be more computationally efficient than RFE and can handle both classification and regression problems. However, SFS can also suffer from overfitting if the search space is too large or if the evaluation metric is inappropriate for the specific problem.</p><p><strong>Pros:</strong></p><ul><li>Can be more computationally efficient than RFE.</li><li>Can handle both classification and regression problems.</li><li>Considers the performance of different feature subsets.</li><li>Can improve the accuracy and interpretability of the model.</li></ul><p><strong>Cons:</strong></p><ul><li>May suffer from overfitting if the search space is too large, or if an inappropriate evaluation metric is used.</li><li>The performance of the selected subset may depend on the specific machine learning algorithm and hyperparameters used.</li><li>Can be sensitive to irrelevant or redundant features.</li><li>May not work well for highly correlated or interdependent features.</li></ul><p>Here are our results on the automobile dataset. In this case, SFS yielded an improvement over our base model with all features input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*oMrziWOsZ_voIUt-VrQ4Hw.png" /></figure><h3>Embedded Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXtvfPMF9RqdpiUZMH962Q.png" /></figure><p>Embedded methods are feature selection techniques that involve incorporating feature selection into the model training process. These methods select the most relevant features during model training by assigning weights to each feature based on its importance to the model’s performance. Some examples of embedded methods include Lasso regression, Ridge regression, and Elastic Net regression.</p><p>The advantage of embedded methods is that they can select features that are not necessarily important on their own but are important when combined with other features. Embedded methods can also handle high-dimensional datasets and can be more computationally efficient than wrapper methods. Embedded methods may also be limited by the choice of machine learning algorithm, and the selected features may depend on the specific hyperparameters used for the algorithm.</p><h4>Lasso Regression:</h4><p>Lasso regression is a linear regression model that includes a penalty term to shrink the coefficients of less important features towards zero.</p><p>Implementation in Python:</p><pre>from sklearn.linear_model import LassoCV<br><br># Create a LassoCV object<br>lasso = LassoCV(cv=5)<br><br># Fit the LassoCV object to the data<br>lasso.fit(X_train, y_train.ravel())<br><br># Create a boolean mask of the selected features<br>mask = lasso.coef_ != 0<br><br># Get the names of the selected features<br>selected_features = X_train.columns[mask]<br><br># Create a dataframe with the selected features<br>df_selected = pd.DataFrame(X_train[selected_features], columns=selected_features)<br><br># Print the selected features<br>print(&#39;Selected features:&#39;)<br>print(selected_features.tolist())<br><br># Show the filtered dataframe<br>df_selected.head()</pre><h4>Ridge Regression:</h4><p>Similar to Lasso regression, but with a different type of penalty term that shrinks the coefficients of all features towards zero by a constant factor.</p><p>Implementation in Python:</p><pre>from sklearn.linear_model import RidgeCV<br><br># Create a RidgeCV object<br>ridge = RidgeCV(cv=5)<br><br># Fit the RidgeCV object to the data<br>ridge.fit(X_train, y_train.ravel())<br><br># Create a boolean mask of the selected features<br>mask = ridge.coef_ != 0<br><br># Get the names of the selected features<br>selected_features = X_train.columns[mask]<br><br># Create a dataframe with the selected features<br>df_selected = pd.DataFrame(X_train[selected_features], columns=selected_features)<br><br># Print the selected features<br>print(&#39;Selected features:&#39;)<br>print(selected_features.tolist())<br><br># Show the filtered dataframe<br>df_selected.head()</pre><h4>Decision Tree-Based Methods:</h4><p>Decision tree algorithms such as Random Forest and Gradient Boosted Trees can select features based on their importance in the model. We can then select the most important features based on the output importance. This can also be used with other algorithms such as Regression Trees, Random Forest, Gradient Boosted Trees, XGBoost, LightGMB or any others that output feature importance.</p><p>Since decision tree algorithms prioritise the most important features when determining the first splits, this can also be achieved by ‘pruning’ your decision tree or limiting the tree depth. This removes the splits at the bottom of the tree, where the features are less important.</p><p>For this example, we will use the breast cancer dataset with a decision tree model.</p><pre># Initiate model<br>clf = DecisionTreeClassifier(random_state=42)<br><br># Train the model on the training data<br>clf.fit(X_train, y_train)<br><br># Make predictions on the test data<br>y_pred = clf.predict(X_test)<br><br># Compute the performance metrics<br>accuracy = accuracy_score(y_test, y_pred)<br>precision = precision_score(y_test, y_pred)<br>recall = recall_score(y_test, y_pred)<br>f1 = f1_score(y_test, y_pred)<br><br># Print the performance metrics<br>print(&#39;Precision:&#39;, round(precision, 3), &#39;Recall:&#39;, round(recall, 3), &#39;F1-score:&#39;, round(f1, 3))<br><br># Extract the feature importances and create a dataframe<br>importances = pd.DataFrame({&#39;Feature&#39;: X_train.columns, &#39;Importance&#39;: clf.feature_importances_})<br><br># Sort the features by importance<br>importances = importances.sort_values(&#39;Importance&#39;, ascending=True)<br><br>plot_importances(importances, &#39;Feature Importances from XGBoost model&#39;)</pre><p>Then we can select the top features like so:</p><pre># Select most important features<br>new_importances = importances[0:n_features]<br>selected_features = new_importances.Feature.to_list()<br><br>print(selected_features)<br><br># Filter X for selected features<br>X_train_dt = X_train[selected_features]<br>X_test_dt = X_test[selected_features]<br><br>new_importances</pre><h3>Comparison of our results</h3><p>The results from the examples that were explored for the two datasets are below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*ttvwcgyVigQ9j9x3mzYo6Q.png" /><figcaption>Feature selection results on classification example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*17JWDnhsWIndcvtWepOkXg.png" /><figcaption>Feature selection results on regression example</figcaption></figure><p>For classification using the breast cancer dataset, ANOVA and Correlation yielded the best performance.</p><p>For regression using the automobile dataset, Ridge regression gave the best performance, followed by correlation. Note that ridge regression is not a feature selection method per see, but rather scales the coefficients of the features, so it technically uses all the features.</p><p>In both cases, using a filter method yielded great results, despite being a simpler method.</p><h3>Choosing the Right Feature Selection Method</h3><p>Each method has its own strengths and weaknesses, and choosing the right one depends on the nature of the data and the problem being solved. When choosing a feature selection method, there are several factors to consider. Here are some key factors to keep in mind:</p><ol><li><strong>Dataset characteristics: </strong>The number of features and their distribution can influence the performance of different feature selection methods. For instance, filter methods are well-suited for high-dimensional datasets with many features, while wrapper methods may be better for smaller datasets with fewer features.</li><li><strong>Correlation among features:</strong> If features are highly correlated, filter methods may not be effective as they may overlook important information captured by correlated features. Wrapper and embedded methods can capture feature interactions and correlations and may be more effective in such scenarios.</li><li><strong>Nature of the target variable: </strong>Different feature selection methods may be more appropriate for different types of target variables. For instance, Pearson correlation may be well-suited for continuous target variables, while chi-squared and ANOVA may be better for categorical target variables.</li><li><strong>Computational resources:</strong> Wrapper and embedded methods can be computationally expensive, and may not be suitable for large datasets or limited computing resources. Filter methods are generally faster and more efficient, making them a good choice for large datasets.</li><li><strong>Performance evaluation:</strong> It’s important to evaluate the performance of the selected features using cross-validation or hold-out validation, as some methods may overfit the training data. It’s also important to compare the performance of different feature selection methods to ensure that the selected features are truly improving model performance.</li></ol><h3>Conclusion</h3><p>We’ve seen that feature selection is an important step in improving the accuracy and efficiency of machine learning models by selecting the most relevant features from a large pool of data. Ultimately, the feature selection method best for you will depend on your data and algorithm, and you will need to experiment with different techniques and pre-processing methods to determine the best fit for your model.</p><p>There are many resources available for further learning. Some good places to start include the scikit-learn documentation, Kaggle competitions, and academic papers on the subject. With the right methods, we can ensure we are using only the finest ingredients for our models.</p><p>Happy feature selecting!</p><h4>Links:</h4><ul><li>GitHub Repository — <a href="https://github.com/J-Jurza/tutorial_feature_selection/blob/main/feature_selection_techniques.ipynb">https://github.com/J-Jurza/tutorial_feature_selection/blob/main/feature_selection_techniques.ipynb</a></li><li>Scikit-learn documentation on feature selection: <a href="https://scikit-learn.org/stable/modules/feature_selection.html">https://scikit-learn.org/stable/modules/feature_selection.html</a></li><li>Kaggle feature selection tutorials: <a href="https://www.kaggle.com/learn/feature-selection">https://www.kaggle.com/learn/feature-selection</a></li><li><a href="https://machinelearningmastery.com/feature-selection-with-real-and-categorical-data/">https://machinelearningmastery.com/feature-selection-with-real-and-categorical-data/</a></li><li>An Introduction to Variable and Feature Selection: <a href="https://jmlr.csail.mit.edu/papers/volume3/guyon03a/guyon03a.pdf">https://jmlr.csail.mit.edu/papers/volume3/guyon03a/guyon03a.pdf</a></li><li>Feature Selection for Machine Learning: <a href="https://machinelearningmastery.com/feature-selection-machine-learning-python/">https://machinelearningmastery.com/feature-selection-machine-learning-python/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a70a52b6f243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Validation Metrics: Evaluate your Models like a Pro]]></title>
            <link>https://medium.com/@honzj/mastering-validation-metrics-evaluate-your-models-like-a-pro-4fda25abe3cb?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fda25abe3cb</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Thu, 16 Mar 2023 12:02:10 GMT</pubDate>
            <atom:updated>2023-03-18T02:04:35.977Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Choosing the right validation metric is like selecting the perfect pair of glasses: it allows us to see the performance of our models with crystal-clear vision.</blockquote><p>A critical step in <a href="https://medium.com/@h.jurza/how-to-build-a-machine-learning-model-ab8baf9e5dd8">building a machine learning model</a> is checking how well it performs. This is done with the use of validation metrics. In this guide, we’ll explore essential metrics for classification and regression, equipping you with the knowledge to assess your models effectively. Join me in learning when to use each metric, the pros and cons and how to implement them in Python. Let’s get into it!</p><h3>Section 1: Classification Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h98QloeXiNXr2y7nF2B4TA.png" /></figure><h4>1.1 Classification outcomes</h4><p>Before we dive into classification metrics, we must understand the following concepts:</p><ul><li><strong>True Positives (TP): </strong>Cases where the model correctly predicted the positive class.</li><li><strong>False Positives (FP):</strong> Cases where the model predicted the positive class, but the actual class was negative.</li><li><strong>True Negatives (TN):</strong> Cases where the model correctly predicted the negative class.</li><li><strong>False Negatives (FN):</strong> Cases where the model predicted the negative class, but the actual class was positive.</li></ul><p>In summary, <strong>TP</strong> and <strong>TN </strong>are the correct predictions, while<strong> FP</strong> and <strong>FN</strong> are the incorrect predictions made by a classification model.</p><h4><strong>1.2 Accuracy</strong></h4><p>Accuracy is the most straightforward classification metric, measuring the proportion of <strong>correct predictions</strong> out of the <strong>total number of predictions</strong>. The formula for accuracy is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*aI9n5LbpM81PGMzyRi3igQ.png" /></figure><p>While accuracy is simple to understand and calculate, it’s <strong>not always the best choice</strong>. In cases of class imbalance, where one class significantly outnumbers the other, accuracy can be misleading. It’s essential to consider other metrics for a more comprehensive evaluation.</p><p><strong>Summary:</strong></p><ul><li>Easy to understand and communicate and provides a simple evaluation of a model’s performance.</li><li>Not suitable for imbalanced classes, as it may favour the majority class.</li><li>Cannot differentiate between false positives and false negatives.</li><li>Should be used in combination with other metrics.</li></ul><p>Here’s a way to calculate the accuracy score in Python. We can compare the values predicted by our model (<strong>y_pred</strong>) with the true values (<strong>y_test</strong>) using the following code:</p><pre>from sklearn.metrics import accuracy_score<br><br># Calculate the accuracy score of the model<br>accuracy = accuracy_score(y_test, y_pred)<br>print(&quot;Accuracy:&quot;, accuracy)</pre><h4>1.2 Confusion Matrix</h4><p>A confusion matrix is a table that summarises the performance of a classification model by comparing its predictions with actual values. It displays all four of our classification outcomes. The confusion matrix offers a visual representation of a model’s performance and helps identify where the model is making mistakes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdL1wryQB1DluW_mBu22sA.png" /><figcaption><a href="https://medium.com/@dtuk81/confusion-matrix-visualization-fc31e3f30fea">Example of a confusion matrix</a></figcaption></figure><p><strong>Summary:</strong></p><ul><li>Provides a detailed breakdown of true positives, false positives, true negatives, and false negatives.</li><li>Offers insights into model performance for each class, helpful for identifying weaknesses and biases.</li><li>Serves as a foundation for calculating various metrics, such as precision, recall, F1-score, and accuracy.</li><li>Can be harder to interpret and communicate as it doesn’t provide a single value for overall model performance (which may be desired for comparison purposes).</li></ul><p>An easy way to plot the confusion matrix in Python is:</p><pre>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay<br><br># Calculate confusion matrix<br>conf_matrix = confusion_matrix(y_test, y_pred)<br><br># Plot confusion matrix<br>disp = ConfusionMatrixDisplay(confusion_matrix=conf_matrix, display_labels=model.classes_)<br>disp.plot()</pre><p>If you want more information on your confusion matrix, like counts and percentages, check out this <a href="https://medium.com/@dtuk81/confusion-matrix-visualization-fc31e3f30fea">article</a>.</p><h4><strong>1.3 Precision</strong></h4><p>Precision measures the proportion of true positive predictions out of all positive predictions made by the model. The formula for precision is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*VbRbQnFtB49XbHC9tIWi8Q.png" /></figure><p>Precision is particularly useful when the <strong>cost of a false positive is high</strong>, such as in spam detection or medical diagnosis. However, precision alone doesn’t account for false negatives, so it’s often used in conjunction with recall.</p><p><strong>Summary:</strong></p><ul><li>Precision is useful when false positives have higher consequences.</li><li>Easy to understand and communicate.</li><li>Does not consider the number of false negatives.</li><li>Suitable for imbalanced data. However, it should be used in combination with other metrics, as high precision can come at the expense of recall on imbalanced datasets</li></ul><h4><strong>1.4 Recall (Sensitivity)</strong></h4><p>Recall, also known as sensitivity, measures the proportion of true positive predictions out of all actual positive instances. The formula for recall is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*kEM2TlLKjS6iO7ofaIs8Hg.png" /></figure><p>Recall is vital when the <strong>cost of false negatives is high</strong>, such as in cancer detection or credit fraud detection or when dealing with imbalanced datasets where the positive class is the minority. Like precision, recall should be considered alongside other metrics for a balanced evaluation.</p><p><strong>Summary:</strong></p><ul><li>Recall is useful when false negatives have higher consequences.</li><li>Easy to understand and communicate.</li><li>Does not consider the number of false positives.</li><li>Suitable for imbalanced data. However, it should be combined with other metrics, as high recall can come at the expense of precision on imbalanced datasets.</li></ul><h4><strong>1.5 F1-Score</strong></h4><p>The F1-score is the harmonic mean of precision and recall, providing a single metric that balances both. The formula for the F1-score is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*XTsYKUrA8tHlj95Mg39vbA.png" /></figure><p>F1-score is useful when both false positives and false negatives are equally important and you seek a balance between precision and recall.</p><p><strong>Summary:</strong></p><ul><li>F1-Score Balances precision and recall: Useful when both false positives and false negatives are important.</li><li>Particularly useful with imbalanced data, where there are trade-offs between precision and recall.</li><li>Biased towards models with similar precision and recall, which may not always be desirable.</li><li>May not be enough to compare the performance of different models, especially when models have different trade-offs between false positives and false negatives.</li></ul><p>The easiest way to get precision, recall and F1 score in one shot is to use scikit-learn’s classification report:</p><pre>from sklearn.metrics import classification_report<br><br># Print the evaluation metrics<br>class_report = classification_report(y_test, y_pred)<br>print(class_report)</pre><p>This gives us precision, recall and F1-score for both classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*i4Fvsh_mZbLt0C5rc2AJIg.png" /><figcaption>Example of sklearn’s classification report</figcaption></figure><h4><strong>1.6 Area Under the Receiver Operating Characteristic Curve (AUC)</strong></h4><p>AUC is a performance measurement that illustrates the trade-off between true positive rate (sensitivity) and false positive rate (1 — specificity) at various classification thresholds. An AUC value of 1 represents a perfect classifier, while 0.5 indicates a random classifier. It’s useful when comparing different models but should be used alongside other metrics for more specific insights into class performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9gjPUDxRZWT7Rcl9t-PEg.png" /><figcaption>Example of ROC curve</figcaption></figure><p><strong>Summary:</strong></p><ul><li>Evaluates model performance across various classification thresholds.</li><li>Suitable for imbalanced datasets.</li><li>Can be used to compare the performance of different models.</li><li>Assumes false positives and false negatives have equal costs.</li><li>Less interpretable to non-technical stakeholders, as it requires understanding the ROC curve.</li><li>May not be appropriate for datasets with a small number of observations or for models with a high number of classes.</li></ul><p>We can calculate the AUC score and plot the ROC curve using the following code:</p><pre>from sklearn.metrics import roc_auc_score, roc_curve<br>import matplotlib.pyplot as plt<br><br># Make predictions on the testing set<br>y_pred_proba = my_model.predict_proba(X_test)[:, 1]<br><br># Calculate the AUC score<br>auc_score = roc_auc_score(y_test, y_pred_proba)<br><br># Calculate the ROC curve<br>fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)<br><br># Plot the ROC curve<br>plt.plot(fpr, tpr, label=&#39;My Model (AUC = %0.2f)&#39; % auc_score)<br>plt.plot([0, 1], [0, 1], &#39;k--&#39;)<br>plt.xlim([0.0, 1.0])<br>plt.ylim([0.0, 1.05])<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.title(&#39;Receiver Operating Characteristic&#39;)<br>plt.legend(loc=&quot;lower right&quot;)<br>plt.show()</pre><h4><strong>1.7 Log-Loss (Cross-Entropy Loss)</strong></h4><p>Log-loss is a metric that measures the uncertainty of a model’s probability estimates. It penalises incorrect classifications and rewards correct classifications. Lower log-loss values indicate better performance, with a value of 0 representing a perfect classifier. The equation for log-loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*d6811VDoi66fmvQjW39DBw.png" /></figure><ul><li><strong>N</strong> is the number of observations.</li><li><strong>y_test </strong>is the true label (0 or 1) for a binary classification problem.</li><li><strong>y_prob</strong> is the predicted probability that the label is 1.</li></ul><p>Log-loss is helpful when you need to evaluate probabilistic predictions (such as when using logistic regression or neural networks). It should be used alongside other metrics for a more comprehensive understanding of class-specific performance.</p><p><strong>Summary:</strong></p><ul><li>Probabilistic predictions: Measures the performance of models that output probability estimates, encouraging well-calibrated predictions.</li><li>Log loss can be used to compare the performance of different models or to optimise the performance of a single model.</li><li>Suitable for imbalanced data.</li><li>Highly sensitive to extreme probability predictions, which can result in large penalty values for misclassified instances.</li><li>Can be difficult to interpret and communicate to non-technical stakeholders.</li></ul><h3><strong>Section 2: Regression Metrics</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlfpbCGtyfFIww-GsV5QAA.png" /></figure><h4><strong>2.1 Mean Absolute Error (MAE)</strong></h4><p>Mean Absolute Error (MAE) measures the average of the absolute differences between predicted and actual values. The formula for MAE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*6mgCyrUqDBYZfWzezPUd-g.png" /></figure><ul><li><strong>N</strong> is the number of data points.</li><li><strong>y_pred</strong> is the predicted value.</li><li><strong>y_test </strong>is the actual value.</li></ul><p><strong>Summary</strong></p><ul><li>Easy to interpret: Represents average error magnitude.</li><li>Less sensitive to outliers than Mean Squared Error (MSE).</li><li>No error direction: Doesn’t indicate overestimation or underestimation.</li><li>May not capture extreme errors’ impact in some contexts.</li></ul><p>In Python, using scikit-learn:</p><pre>from sklearn.metrics import mean_absolute_error<br><br># Mean Absolute Error (MAE)<br>mae = mean_absolute_error(y_true, y_pred)<br>print(&quot;MAE:&quot;, mae)</pre><h4><strong>2.2 Mean Squared Error (MSE)</strong></h4><p>Mean Squared Error (MSE) measures the average of the squared differences between predicted and actual values. The formula for MSE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*u5Jc_IsCiCbvSOZZbnrJ-w.png" /></figure><p>MSE is sensitive to outliers, as it <strong>penalises large errors more heavily than small errors</strong>. This can be both an advantage and a disadvantage, depending on the problem context.</p><p><strong>Summary:</strong></p><ul><li>More sensitive to extreme errors.</li><li>Squared error values can be less intuitive than absolute errors.</li><li>More influenced by outliers compared to Mean Absolute Error (MAE).</li></ul><h4><strong>2.3 Root Mean Squared Error (RMSE)</strong></h4><p>Root Mean Squared Error (RMSE) is the square root of the mean squared error. The formula for RMSE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*VNhT6OT7nJQciO4UX8uFkw.png" /></figure><p>RMSE is also sensitive to outliers, and like MSE, it <strong>penalises large errors more heavily</strong>. The advantage of RMSE over MSE is that its <strong>unit is the same as the target variable</strong>, making it easier to interpret.</p><p><strong>Summary:</strong></p><ul><li>More sensitive to extreme errors.</li><li>Same unit as target variable:</li><li>More influenced by outliers compared to Mean Absolute Error (MAE).</li></ul><p>In Python, using scikit-learn:</p><pre>from sklearn.metrics import mean_squared_error<br><br># Make predictions using the model<br>y_pred = model.predict(X)<br><br># Calculate the mean squared error<br>mse = mean_squared_error(y, y_pred)<br><br># Calculate the root mean squared error<br>rmse = np.sqrt(mse)<br><br># Print the root mean squared error<br>print(&#39;Root Mean Squared Error:&#39;, rmse)</pre><h4>2.4 Mean Absolute Percentage Error (MAPE)</h4><p>Mean Absolute Percentage Error (MAPE) measures the average of the absolute percentage differences between predicted and actual values. The formula for MAPE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*ktPEhfZvXkTSINbog2Jrgw.png" /></figure><p>MAPE is useful when <strong>comparing the performance of different models</strong> or when <strong>assessing the relative importance of errors</strong>. However, MAPE can be problematic when dealing with values close to zero, as the percentage error can become extremely large.</p><p><strong>Summary:</strong></p><ul><li>Relative error metric: Useful for comparing model performance across different scales.</li><li>Easy to interpret: Expressed as a percentage.</li><li>Undefined for zero values, which may occur in some applications.</li><li>Asymmetric: Overestimates errors for small actual values and underestimates for large ones.</li></ul><p>Scikit learn doesn’t have a MAPE function, but we can calculate it ourselves using the following:</p><pre># Mean Absolute Percentage Error (MAPE)<br>def mape(y_true, y_pred):<br>    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100<br><br>mape = mape(y_true, y_pred)<br>print(&quot;MAPE:&quot;, mape)</pre><h4><strong>2.5 R-Squared (Coefficient of Determination)</strong></h4><p>R-Squared measures the proportion of variance in the target variable that can be explained by the model’s predictions. The formula for R-Squared is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*nKcoL8joumb9NwHm2nVq6A.png" /></figure><ul><li><strong>y_mean</strong> is the mean of the actual values.</li><li><strong>y_pred</strong> is the predicted value.</li><li><strong>y_test </strong>is the actual value.</li></ul><p>R-Squared ranges from 0 to 1, with higher values indicating better model performance. However, R-Squared has limitations, such as the possibility of <strong>increasing with the addition of irrelevant features</strong>.</p><p><strong>Summary:</strong></p><ul><li>Represents the proportion of explained variance, making it easy to understand and communicate.</li><li>Less sensitive to the scale of the target variable, which makes it more suitable for comparing the performance of different models.</li><li>Biased towards models with many features, which may not always be desirable.</li><li>Not appropriate for evaluating models that do not have a linear relationship between the predictors and the target variable.</li><li>May be affected by outliers in the data.</li></ul><p>In Python, using scikit-learn:</p><pre>from sklearn.metrics import r2_score<br><br># R-squared<br>r_squared = r2_score(y_true, y_pred)<br>print(&quot;R-squared:&quot;, r_squared)</pre><h4><strong>2.6 Adjusted R-Squared</strong></h4><p>Adjusted R-Squared is a modified version of R-Squared that considers the number of features in the model. The formula for Adjusted R-Squared is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*jh_1-q4utxqEgjRsZxHo8Q.png" /></figure><ul><li><strong>N </strong>is the number of data points.</li><li><strong>k</strong> is the number of features.</li></ul><p>Adjusted R-Squared can help prevent overfitting by <strong>penalising models with excessive features</strong>.</p><p><strong>Summary:</strong></p><ul><li>Modification of R-squared that adjusts for the number of predictors in the model, which makes it a more appropriate metric for comparing the performance of models with different numbers of predictors.</li><li>Less sensitive to the scale of the target variable, which makes it more suitable for comparing the performance of different models.</li><li>Penalises extra variables: Reduces overfitting risk compared to R-squared.</li><li>Not appropriate for evaluating models that do not have a linear relationship between the predictors and the target variable.</li><li>May be affected by outliers in the data.</li></ul><p>In Python, we can calculate it from our R-squared score:</p><pre>from sklearn.metrics import r2_score<br><br># R-squared<br>r_squared = r2_score(y, y_pred)<br><br># Adjusted R-squared<br>n = len(y) # number of observations<br>p = X.shape[1]  # number of predictors<br>adj_r_squared = 1 - ((1 - r_squared) * (n - 1)) / (n - p - 1)<br><br>print(&quot;Adjusted R-squared:&quot;, adj_r_squared)</pre><h3><strong>3. Selecting the appropriate metric</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HrjBf-lkCGTg5JXafd9VcA.png" /></figure><p>Your choice of metric depends on the problem context, the model type, and the project’s specific objectives. In this section, we’ll discuss factors to consider when selecting an appropriate metric and provide guidelines to help you make an informed decision.</p><h4><strong>3.1 Understand the Problem Context</strong></h4><p>Before selecting a metric, it’s crucial to understand the context of the problem you’re trying to solve. Consider factors such as:</p><ul><li>The type of machine learning task: Different metrics are suited for different tasks, such as classification, regression, or multi-label classification.</li><li>The distribution of the data: Imbalanced data may require metrics that are less sensitive to class imbalance, like F1-score, precision, recall, or the area under the ROC curve for classification tasks.</li><li>The importance of various types of errors: Depending on the application, false positives and false negatives may have different consequences. Select a metric that appropriately reflects the importance of these errors in the context of your problem.</li></ul><h4>4.2 Consider Model Objectives</h4><p>The specific objectives of your machine learning model will also influence the choice of validation metric. For example:</p><ul><li>If you need a model that produces accurate probability estimates, log-loss might be an appropriate metric.</li><li>If your goal is to maximise the true positive rate while minimising false positives, the area under the ROC curve could be suitable.</li></ul><h4>4.3 Evaluate Multiple Metrics</h4><p>It’s often helpful to evaluate multiple metrics simultaneously to gain a comprehensive understanding of a model’s performance. This approach can help you identify strengths and weaknesses in your model and inform further improvements. For example:</p><ul><li>In classification tasks, you might evaluate precision, recall, and F1-score together to balance the trade-offs between false positives and false negatives.</li><li>In regression tasks, you could consider using both absolute error metrics like MAE and relative error metrics like MAPE to assess the model’s performance in different aspects.</li></ul><h3>Conclusion</h3><p>We’ve learned about some of the most common validation metrics and why choosing the correct metric is crucial for assessing and optimising your model. By understanding various metrics and aligning them with your project’s context and goals, you can effectively evaluate your models on your path towards model optimisation and success. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fda25abe3cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build a Machine Learning Model]]></title>
            <link>https://medium.com/@honzj/how-to-build-a-machine-learning-model-ab8baf9e5dd8?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab8baf9e5dd8</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 14:01:37 GMT</pubDate>
            <atom:updated>2023-03-15T14:01:37.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning Made Simple: Building your First Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbBYpBLiJ3rQPZqwJ_RY_A.png" /></figure><h3>Introduction</h3><p>Behind every successful machine learning application lies a robust model building process. In this article, we’ll guide you through the key steps of model selection, training, and evaluation so that you can build effective machine learning models. We’ll cover various algorithm types, methods for training models, and evaluation metrics, applying these in the context of a churn model. Additionally, we’ll explore common challenges in the model building process and best practices for overcoming them. Whether you’re a seasoned data scientist or just starting out, this article will equip you with the knowledge you need to take your machine learning skills to the next level.</p><h3>The model building process</h3><blockquote>Building a machine learning model is like raising a child — you teach it, you feed it data, and you hope it turns out smarter than you.</blockquote><p>Whichever model we choose, the basic process for supervised learning is relatively similar. Model building is an iterative process that follows the following basic steps:</p><ol><li><strong>Train the model: </strong>Train the model on the training set using an appropriate algorithm. During training, the model learns to make predictions by adjusting its internal parameters based on the input data.</li><li><strong>Evaluate the model:</strong> Evaluate the model’s performance on the testing set using appropriate evaluation metrics, such as precision, recall, F1 score, or mean squared error.</li><li><strong>Improve the model</strong>: If the model performance is unsatisfactory, you can improve it by changing the model architecture, hyperparameters, or optimisation algorithm. You may also consider collecting more data or doing some feature engineering.</li></ol><p>You will likely repeat this process many times before you arrive at your final model. Let’s look at the process of doing this with a simple classification model to predict churn.</p><h3>Model building example</h3><p>In this example, we will build a churn model using the telco dataset. Let’s define our business problem first, then translate it into a machine learning problem:</p><p><strong>Business problem: </strong>Our objective is to predict which customers are likely to churn, given a set of their attributes. This will allow the business to develop retention strategies to encourage customers to stay.</p><p><strong>Machine learning problem: </strong>A <strong>supervised learning</strong> problem (as we have labelled data) and a <strong>binary classification</strong> problem (predicting a category of two possible outcomes). Our <strong>target variable</strong> is <strong>churn </strong>with possible values [yes, no]</p><h4>Select an algorithm</h4><p>Selecting a suitable algorithm is a crucial step in the model building process. Different algorithms are suited to different types of problems, and selecting the wrong one can result in poor performance. Here are some techniques for selecting the best model:</p><ul><li><strong>Consider the type of problem you’re trying to solve:</strong> Is it a regression problem (predicting a continuous value), a classification problem (predicting a categorical value), or a clustering problem (grouping similar data points together)?</li><li><strong>Assess the complexity of the problem: </strong>Does the problem require a simple model, or can it handle a more complex one?</li><li><strong>Evaluate the size and quality of the data:</strong> Do you have enough data to train a complex model? Is the data noisy or incomplete?</li></ul><h4>Commonly used supervised learning algorithms</h4><ul><li><strong>Classification problems: </strong>Logistic Regression, Decision Trees, Support Vector Machines, Neural Networks</li><li><strong>Regression problems: </strong>Linear Regression, Regression Trees, Support Vector Regression, Neural Networks</li><li><strong>Time Series problems: </strong>Autoregressive Integrated Moving Average (ARIMA), Exponential Smoothing (ETS), Long Short-Term Memory (LSTM)</li></ul><h4><strong>Selected algorithm:</strong></h4><p>For this example, we<strong> </strong>will start simple and use <strong>logistic regression</strong>.</p><p>Let’s start by importing the required packages. For this model, we will be using modules from scikit-learn</p><pre># Import necessary libraries<br>import pandas as pd<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import precision_score, recall_score, f1_score<br>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay<br>import seaborn as sns</pre><p>Next, we can download our dataset</p><pre># load the telco churn dataset<br>url = &#39;https://raw.githubusercontent.com/IBM/telco-customer-churn-on-icp4d/master/data/Telco-Customer-Churn.csv&#39;<br>df = pd.read_csv(url)</pre><h4><strong>Data pre-processing</strong></h4><p>Then we can do some basic data <a href="https://medium.com/me/stats/post/9921345ba7d0">pre-processing</a>:</p><ul><li>Drop our primary key column (irrelevant features can lead to overfitting, and privacy concerns may arise in a real-life setting.)</li><li>Binary (one-hot) encode the categorical variables</li><li>Split our data into feature matrix <strong>X</strong> and target vector <strong>y</strong>. Our target, in this case, is ‘<strong>churn_yes</strong>’</li><li>Split into train and test sets</li></ul><pre># Pre-processing<br><br># Binary encode categorical variables<br>df.drop(&#39;customerID&#39;, axis=1, inplace=True)<br>df = pd.get_dummies(df, drop_first=True)<br><br># Prepare feature matrix and target vector<br>X = df.drop(&#39;Churn_Yes&#39;, axis=1)<br>y = df[&#39;Churn_Yes&#39;]<br><br># split the data into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>We now have four sets to work with.</p><h4>Model training</h4><p>The next step is to train it on the data. Training aims to adjust the model’s parameters to minimise the difference between its predictions and the actual values.</p><p>We can create a logistic regression model instance and train it on our training set. We do this by passing in our training features and training target. The model will learn the parameters based on these.</p><pre># Create a logistic regression object<br>model = LogisticRegression()<br><br># Train the model on the training set<br>model.fit(X_train, y_train)</pre><h4>Model Evaluation</h4><p>Once we’ve trained our model, we must evaluate it on the test set. This will tell us how well it generalises to unseen data.</p><p>We can use a number of evaluation metrics. For this example, we will begin by looking at the confusion matrix, as well as precision, recall and F1 score.</p><pre># Make predictions on the testing set<br>y_pred = model.predict(X_test)<br><br># Evaluate the performance of the model<br>conf_matrix = confusion_matrix(y_test, y_pred)<br>precision = precision_score(y_test, y_pred)<br>recall = recall_score(y_test, y_pred)<br>f1 = f1_score(y_test, y_pred)<br><br># Plot confusion matrix<br>disp = ConfusionMatrixDisplay(confusion_matrix=conf_matrix, display_labels=model.classes_)<br>disp.plot()<br><br># Print the evaluation metrics and plot the confusion matrix<br>print(&quot;Precision:&quot;, precision)<br>print(&quot;Recall:&quot;, recall)<br>print(&quot;F1 Score:&quot;, f1)</pre><h4>Confusion matrix</h4><p>A confusion matrix is a table used to evaluate the performance of a classification model by comparing the predicted labels to the true labels of a set of data. The matrix displays the number of true positives (TP), false positives (FP), true negatives (TN), and false negatives (FN) for each class.</p><p>The columns represent the predicted labels, while the rows represent the true labels. The diagonal of the matrix represents the correct predictions, while the off-diagonal elements represent the incorrect predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*lE0IUPA7zGpW6k6kgyb2pw.png" /><figcaption>Confusion matrix for the logistic regression model</figcaption></figure><p>Note that the true negative rate is much higher than the true positive rate. This means our model is much better at predicting if a customer<strong> will not churn</strong> than if they <strong>will churn.</strong></p><h4>Precision and recall</h4><p>A confusion matrix can then be used to calculate various metrics such as accuracy, precision, recall, and F1 score, which provide a more comprehensive evaluation of the model’s performance.</p><p><strong>Precision </strong>is the fraction of true positives (TP) among the total number of positive predictions (TP + FP). It represents the proportion of predicted positive instances that are actually positive.</p><ul><li><strong>Precision = TP / (TP + FP)</strong></li></ul><p><strong>Recall</strong> is the fraction of true positives (TP) among the total number of actual positive instances (TP + FN). It represents the proportion of positive instances that are correctly predicted and is also known as sensitivity or true positive rate.</p><ul><li><strong>Recall = TP / (TP + FN)</strong></li></ul><p><strong>F1 score</strong> is a metric that combines precision and recall into a single score that reflects the balance between them. It is calculated as follows:</p><ul><li><strong>F1 Score = 2 * (Precision * Recall) / (Precision + Recall)</strong></li></ul><h4>Evaluation in the context of our business problem</h4><p>In the context of our churn model problem, we might be interested in either precision or recall.</p><p>If the company aims to reduce customer churn, recall may be a more important metric. This is because the cost of false negatives (predicting a customer will not churn when they actually do) may be high, as losing a customer can have significant financial consequences for the company. In this case, the goal would be to identify as many potentially churning customers as possible, even if it means some false positives (i.e., predicting a customer will churn when they actually do not).</p><p>On the other hand, if the cost of false positives (predicting a customer will churn when they actually do not) is high, then precision may be a more important metric. This could be the case if the company’s retention strategies are expensive or time-consuming.</p><h4>Is our model any good?</h4><p>Let’s look at our metrics. In our case, our metrics are not very impressive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*qGwRKc3ddvzOCo5TYnWLqw.png" /><figcaption>Precision, recall and F1 score for the logistic regression model</figcaption></figure><h4>Imbalanced data</h4><p>An important note is that our dataset is skewed towards no churn, so even a useless model will predict correctly most of the time.</p><ul><li>The ‘churn = yes’ outcome only represents 26.5% of our dataset</li><li>This means that if we make a model that just predicts ‘churn = no’ all the time, it would lead to an accuracy of 73.4%.</li></ul><blockquote>If a broken clock is correct twice a day, then a broken churn model is correct 73.4% of the time</blockquote><p>This highlights the importance of using precision and recall rather than accuracy as a classification metric.</p><h3>Wash, rinse, repeat</h3><p>If we’re not happy with our metrics, try again! Don’t worry, this is a very common part of the model building process, and you will almost certainly not get your final model on the first try. This is where the experimentation comes in.</p><p>We can either improve the data or the model to improve model performance.</p><h4>Improving the data</h4><p>One of the best things we can do is to go back to our <a href="https://medium.com/p/9921345ba7d0">pre-processing </a>steps and experiment with the data we’re feeding into our model. Things to try are:</p><ul><li><strong>Feature selection: </strong>adding or removing features and seeing how this affects our performance metrics</li><li><strong>Feature engineering: </strong>This involves creating new features from the existing ones to improve the quality and relevance of the data. This can include transforming or scaling the data, combining features, or adding new features based on domain knowledge.</li><li><strong>Feature scaling: </strong>Scaling can also help improve the performance of some algorithms. The scaling technique applied (or whether we use one at all) will depend on the algorithm we choose.</li><li><strong>Different imputation strategies: </strong>If you have <a href="https://medium.com/p/2a1e48118445">missing values</a>, you can change the way you handle these.</li></ul><h4>Improving the model</h4><p>We can also change things about the model. We can try the following:</p><ol><li><strong>Algorithm selection: </strong>Sometimes, the choice of algorithm itself can impact the performance of our model. It is important to explore different types and choose the one that performs well and is suited to the problem at hand. It’s also important to consider what level of explainability you’ll need. A black-box model might perform the best, but you might need to explain how it’s arrived at its decisions.</li><li><strong>Ensemble methods:</strong> Using the ‘wisdom of the crowd’, we can combine multiple models to improve the model’s overall performance. This can be done using techniques such as bagging, boosting, or stacking. This is built into certain models such as random forests, gradient-boosted machines etc.</li><li><strong>Regularisation:</strong> This aims to control the complexity of the model and prevent it from overfitting by adding a penalty term to the loss function during training. This improves the model’s generalisation ability. This can include techniques such as L1/L2 regularisation, dropout, or early stopping.</li><li><strong>Hyperparameter tuning:</strong> Many machine learning models have hyperparameters that control the model’s behaviour and performance. Hyperparameter tuning involves finding the best values for these hyperparameters to improve the model’s performance.</li></ol><p>Now that we have a baseline model, we can iterate on it and build a better model (coming in a future article)</p><h3>Summary of common challenges and best practices</h3><p>While building machine learning models, you may encounter various challenges that can impact the performance of your models. Here are some common challenges and best practices for overcoming them:</p><ul><li><strong>Data quality: </strong>Poor data quality can result in inaccurate models. It’s important to clean and pre-process the data before training the models. This includes handling missing values, dealing with outliers, and transforming the data into a suitable format.</li><li><strong>Overfitting:</strong> Occurs when the model fits the training data too closely and performs poorly on new data. To prevent overfitting, use regularisation techniques, collect more data, or use a simpler model.</li><li><strong>Underfitting:</strong> Occurs when the model is too simple to capture the complexity of the problem. To overcome underfitting, use a more complex model, collect more data, or tune the hyperparameters.</li><li><strong>Imbalanced data: </strong>Imbalanced data occurs when one class in a classification problem has significantly fewer samples than the other class. Try techniques such as oversampling, undersampling, or synthetic data generation to handle imbalanced data.</li><li><strong>Generalisation: </strong>Ensuring your model can generalise well to new, unseen data is crucial. Use techniques such as cross-validation, regularisation, or ensemble learning to improve the generalisation of your model.</li></ul><h3>Conclusion</h3><p>We have built a simple model to outline the model building process. While our model did not perform too well, we now have a baseline model we can iterate on and improve (coming in a future article)</p><p>Following the best practices outlined and addressing common challenges, you can build effective models that generalise well and make accurate predictions on real-world data. Remember always to be mindful of the data quality, perform thorough pre-processing and evaluate with respect to your business problem. By following the steps in this article, you’ll be building models like a pro in no time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab8baf9e5dd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Missing Data, No Problem: Techniques for Handling Incomplete Datasets]]></title>
            <link>https://medium.com/@honzj/missing-data-no-problem-techniques-for-handling-incomplete-datasets-2a1e48118445?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a1e48118445</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[missing-values]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 03:58:18 GMT</pubDate>
            <atom:updated>2023-03-14T03:58:18.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQRBvLCQ0LB4HGRT9FGLcA.png" /></figure><h3>Handling missing values</h3><p>Missing values are a common problem in real-world datasets, and handling them is a crucial step in data <a href="https://medium.com/@h.jurza/chaos-to-order-data-pre-processing-for-machine-learning-mastery-9921345ba7d0">pre-processing</a>. They can occur due to various reasons, such as the structure and quality of the data, data entry errors, data loss during transmission, or incomplete data collection. These missing values can impact the accuracy and reliability of machine learning models, as they can introduce bias and skew your results. Some models don’t work at all with missing values. Therefore, handling missing values appropriately is essential before you build your model.</p><h4>Techniques covered in this article</h4><p>This article will show how to handle these missing values in <strong>three difficulty levels</strong> and covers the following techniques:</p><ul><li><strong>Level 1: </strong>Deletion, Mean/Median/Mode imputation, Estimate using domain knowledge</li><li><strong>Level 2: </strong>Regression imputation, K-Nearest Neighbours (KNN) imputation</li><li><strong>Level 3: </strong>Multivariate imputation by chained equations (MICE), MICEforest</li></ul><p>Let’s begin!</p><h4>Check for missing values</h4><p>First, we must check how many missing values we have in each feature. You may have already done this as part of your <a href="https://medium.com/@h.jurza/unveiling-hidden-insights-a-quick-start-guide-to-exploratory-data-analysis-eda-c843dd710726">exploratory data analysis</a>, but if not, we can do this with the following code:</p><p>Let’s import pandas and read them in our dataset. For the following examples, we will be using the wine quality dataset.</p><pre>import pandas as pd<br><br># Read in dataframe<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)</pre><p>We can then check for missing values with the following line of code.</p><pre># Check for missing values<br>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*oQb1WkwuxgEbZTqVGRclsQ.png" /><figcaption>Missing values for each feature</figcaption></figure><p>It’s that simple!</p><p>We can view rows containing missing values in any feature using the following:</p><pre># Filter for any rows containing missing values in any column<br>df_filtered = df[df.isnull().any(axis=1)]<br><br># Print the filtered dataframe<br>df_filtered.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKdaLRMEn6ib3qO0Jcptrg.png" /><figcaption>Dataframe rows containing nulls in any feature</figcaption></figure><p>Now we can begin handling these missing values. There are several techniques for handling missing values.</p><h3>Level 1: Beginner</h3><h4><strong>Deletion</strong></h4><p>The simplest approach is deletion. This involves removing the rows or columns (features) with missing values. This is usually done when the percentage of missing values is very small or when the missing values do not significantly impact the analysis or results.</p><p>To delete a row with missing values:</p><pre># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Drop rows with null values<br>df_droprows = df.dropna()<br><br># View nulls<br>df_droprows.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*wOGU4aiz8GSP6QmqcznhIA.png" /></figure><p>We can also drop columns or features using the following:</p><pre># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Drop all features with null values<br>df_dropcols = df.drop(columns=[&#39;type&#39;, &#39;fixed acidity&#39;, &#39;citric acid&#39;, &#39;volatile acidity&#39;, &#39;residual sugar&#39;, &#39;chlorides&#39;, &#39;pH&#39;, &#39;sulphates&#39;])<br><br># View nulls<br>df_dropcols.isnull().sum()</pre><p>Note that by dropping rows, we end up with a shorter dataset. When dropping features, we end up with a full-length dataset however lose features.</p><pre># Compare shape of resulting dataframes when dropping rows vs dropping features<br>print(&quot;Shape when dropping rows: &quot;, df_droprows.shape)<br>print(&quot;Shape when dropping features: &quot;, df_dropcols.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*MjPj22eODWwkwbiRwNgQWw.png" /><figcaption>Comparison of shape when dropping rows or features</figcaption></figure><p>The method you choose depends on what features you need to use in your dataset and how many observations you’ll need. Neither of these methods is particularly sophisticated, and both lead to losing valuable data — so let’s explore some other options.</p><h4><strong>Mean/Median Imputation</strong></h4><p>The next possible method is replacing the missing values with the mean or median of the feature. In this case, we do not lose features or rows. This should only be used for <strong>numerical </strong>features (and if using mean, we should ensure the dataset is not skewed or contains significant outliers).</p><p>To impute the missing value with <strong>mean</strong>:</p><pre># fill missing values with the mean of each column<br>df = df.fillna(df.mean())</pre><p>Now let’s check one of the imputed values. Here is a row we know to have had a missing value for volatile acidity:</p><pre># Let&#39;s check a row with an imputed value for &#39;volatile acidity&#39;<br>df[df.index==86]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejCiF7KoVD4cFtSdpNC9vg.png" /><figcaption>Mean imputed value for ‘volatile acidity.’</figcaption></figure><p>To impute with <strong>median, </strong>we can use:</p><pre># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Fill missing values with the median of each column<br>df = df.fillna(df.median())</pre><pre># Let&#39;s check a row with an imputed value for &#39;volatile acidity&#39;<br>df[df.index==86]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z8r1VRxnXOpg3gjnrojfqw.png" /><figcaption>Median imputed value for ‘volatile acidity.’</figcaption></figure><p>We can see that there is a different value when using mean and median imputation.</p><h4><strong>Mode Imputation</strong></h4><p>Like the above, this method replaces the missing values with the feature’s mode or most commonly occurring value. This should only be used for categorical features where one category is dominant.</p><p>Let’s apply this to our categorical feature — type. First, let’s check if one category is dominant. We can achieve this with the value_counts method:</p><pre># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br>df[&#39;type&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*v__A5rzF2jxnVhbcD7nN0g.png" /><figcaption>Value counts for wine type</figcaption></figure><p>We can see that there is a dominant category (white). Therefore we can impute with mode with the following:</p><pre># Fill missing values with the mode of each column<br>df[&#39;type&#39;] = df[&#39;type&#39;].fillna(df[&#39;type&#39;].mode())</pre><h4>Using Scikit-Learn’s SimpleImputer class</h4><p>Mean, median and mode imputation can also be performed using Scikit-learn’s SimpleImputer class. Set the strategy to either ‘mean’, ‘median’, or ‘most_frequent’.</p><pre>from sklearn.impute import SimpleImputer<br><br># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Make sub dataframe with only numeric features<br>df_numeric = df.drop(columns=&#39;type&#39;)<br><br># Create an instance of the SimpleImputer class<br>imputer_median = SimpleImputer(strategy=&#39;median&#39;)<br><br># Fit the imputer to the data<br>imputer_median.fit(df_numeric)<br><br># Transform the data <br>df_imputed_median = pd.DataFrame(imputer_median.transform(df_numeric), columns=df_numeric.columns)<br><br># print the first 5 rows of the imputed data<br>df_imputed_median.head()</pre><p>You can also set the strategy to ‘constant’ and specify a ‘fill_value’ to fill with a constant value:</p><p><strong>Advantages of mean/median/mode imputation</strong>:</p><ul><li>Simple and fast to implement</li><li>It preserves the sample size and reduces the risk of bias in downstream analyses, such as machine learning models.</li><li>It is less computationally expensive than more complex imputation methods.</li></ul><p><strong>Disadvantages of mean/median/mode imputation</strong>:</p><ul><li>It does not account for the variability or distribution of the data, potentially resulting in imputed values that are not representative of the true values.</li><li>It can underestimate or overestimate missing values, particularly in datasets with extreme values or outliers.</li><li>It can lead to reduced variance and artificially inflated correlation coefficients in the imputed dataset.</li><li>It assumes that the missing values are Missing Completely at Random (MCAR), which may not always be the case (see level 2).</li></ul><h4><strong>Estimate using domain knowledge</strong></h4><p>Another possible approach to dealing with missing data is to replace the missing values with estimates based on domain knowledge or business rules.</p><p>For example, let’s say you are analysing customer data for a retail company and notice that some of the customer records are missing their income information. You could replace these missing values with estimates based on the customer’s demographic information.</p><p>To do this, you could consult with subject matter experts, such as marketing analysts, who could provide insights into the typical income range for customers in each demographic category, allowing you to impute missing income values that are reasonable and plausible.</p><p>When replacing missing data with informed estimates, it is crucial to consult with subject matter experts who possess a deep understanding of the domain and the data to ensure it yields accurate and reliable imputations.</p><h3>Level 2: Intermediate</h3><p>In this level, we will dive into some slightly more advanced techniques to fill in those missing values. Instead of relying on basic measures like the mean, median, or mode, we will take it up a notch and use a predictive model to tackle the issue. But before we can do that, we need to understand the nature of the missing values better.</p><h4>Types of missingness</h4><p>Before we proceed with more advanced techniques, let’s consider the types of missingness we can encounter in our dataset. There are different types of missingness in a dataset, and understanding the type of missingness can help determine the appropriate imputation method. Here are some common types of missingness:</p><ol><li><strong>Missing Completely at Random (MCAR)</strong>: In this type of missingness, the missing values are completely random, meaning that the probability of a value being missing does not depend on any variable, observed or unobserved. For example, if a survey respondent accidentally skips a question on a survey, this is MCAR.</li><li><strong>Missing at Random (MAR)</strong>: In this type of missingness, the probability of a value being missing depends on observed variables but not on the missing values themselves. For example, if a survey respondent is less likely to answer a sensitive question, but the propensity to not answer the question is dependent on observable variables (such as age, gender, and education), then this is MAR.</li><li><strong>Missing Not at Random (MNAR)</strong>: In this type of missingness, the probability of a value being missing depends on unobserved variables, including the missing values themselves. For example, if individuals with higher levels of depression are less likely to report their depression levels, and the propensity to not report is not observable in the data, then this is MNAR.</li></ol><h4><strong>Regression Imputation</strong></h4><p>Here we will use a regression model to make an educated guess about those missing values. How? By analysing the other features in our dataset and using their correlation to fill in the gaps.</p><p>Regression imputation is particularly useful when dealing with cases of missing data that follow a pattern, also known as Missing at Random (MAR) or Missing Completely at Random (MCAR). This method works well when there is a strong correlation between features.</p><p>Let’s give it a go. Since we will only be imputing numeric features, we’ll create a version of the datagram that excludes our categorical feature. Then we can fit a linear regression model for each column with a missing value. For this, we will need Scikit-learn’s <strong>LinearRegression </strong>module.</p><pre>import pandas as pd<br>from sklearn.linear_model import LinearRegression<br><br># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Make sub dataframe with only numeric features<br>df = df.drop(columns=&#39;type&#39;)<br><br># Separate the columns with missing values<br>missing_cols = df.columns[df.isna().any()].tolist()<br>non_missing_cols = list(set(df.columns) - set(missing_cols))<br><br>print(missing_cols)<br><br># loop over each column with missing values<br>for col in missing_cols:<br>    # Create a copy of the dataframe without missing values in the current column<br>    df_temp = df.dropna(subset=[col] + non_missing_cols)<br>    <br>    # Split the dataframe into features (X) and target variable (y)<br>    X = df_temp[non_missing_cols]<br>    y = df_temp[col]<br>    <br>    # Create and fit a linear regression model<br>    lr = LinearRegression()<br>    lr.fit(X, y)<br>    <br>    # Impute missing values in the current column using the fitted model<br>    df.loc[df[col].isna(), col] = lr.predict(df.loc[df[col].isna(), non_missing_cols])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArGYtIsdGf3f61zq58N8FA.png" /><figcaption>Regression imputation on ‘volatile acidity.’</figcaption></figure><p><strong>Advantages of regression imputation</strong>:</p><ul><li>It can handle a large number of missing values.</li><li>It can preserve the statistical properties of the dataset, such as the mean, variance, and correlation coefficients.</li><li>It can improve the accuracy of downstream analyses, such as machine learning models, by reducing bias and increasing sample size.</li></ul><p><strong>Disadvantages of regression imputation</strong>:</p><ul><li>It assumes a linear relationship between the missing variable and the observed variables.</li><li>It may introduce bias if the missing values are not Missing at Random (MAR) or Missing Completely at Random (MCAR).</li><li>It may not work well with categorical or ordinal variables.</li><li>It can be computationally expensive and time-consuming, especially with large datasets.</li></ul><h4>K-Nearest Neighbours (KNN)<strong> imputation</strong></h4><p>Another approach is to bring in a machine learning model like K-Nearest Neighbours (KNN) to help us estimate those missing values. This works similarly to regression imputation, simply with a different algorithm to predict the missing values.</p><p>Here we use <strong>Scikit-learn</strong>:</p><pre>import pandas as pd<br>from sklearn.impute import KNNImputer<br><br># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Make sub dataframe with only numeric features<br>df = df.drop(columns=&#39;type&#39;)<br><br># create a KNN imputer object<br>imputer = KNNImputer(n_neighbors=5)<br><br># impute missing values using KNN<br>df = pd.DataFrame(imputer.fit_transform(df), columns=df.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzfOyTcqbiR3gID0DHyonQ.png" /></figure><p>We can also do this using the <strong>fancyimpute </strong>package:</p><pre>pip install fancyimpute</pre><pre># Import the necessary libraries<br>import numpy as np<br>import pandas as pd<br>from fancyimpute import KNN<br><br># Load the dataset<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Drop non-numeric features<br>df = df.drop(columns=&#39;type&#39;)<br><br># Get list of columns with missing values<br>missing_cols = df.columns[df.isna().any()].tolist()<br><br># Create an instance of the KNN imputer<br>imputer = KNN()<br><br># Fit and transform the imputer to the dataset<br>imputed_array = imputer.fit_transform(df[missing_cols])<br><br># Replace the missing values in the original dataset<br>df[missing_cols] = imputed_array<br><br># View the imputed dataset<br>df</pre><p><strong>Advantages of KNN imputation</strong>:</p><ul><li>It can capture complex non-linear relationships between variables.</li><li>It does not make assumptions about the distribution of the data or the correlation between variables.</li><li>It can be more accurate than simpler imputation methods, such as mean or median imputation, especially with small to medium-sized datasets.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>It can be computationally expensive, especially with large datasets or high-dimensional data.</li><li>It can be sensitive to the choice of distance metric and the number of nearest neighbours selected, which can affect the accuracy.</li><li>It may perform poorly with highly skewed or sparse data.</li></ul><h3>Level 3: Advanced</h3><h4>Multivariate imputation by chained equations (MICE)</h4><p>MICE is a commonly used method for imputing missing data. It works by replacing each missing value with a set of plausible values based on a model that takes into account the relationships between variables in the dataset.</p><p>The algorithm starts by creating a predictive model for each variable in the dataset, based on the other variables that are complete. The missing values for each variable are then imputed using the corresponding predictive model. This process is repeated multiple times, with each round of imputation using the previous round’s imputed values as if they were true, until convergence is reached.</p><p>The multiple imputed datasets are then combined to create a final dataset with imputed values for all missing data. MICE is a powerful and flexible method that can handle datasets with many missing values and complex relationships between variables. It has become a popular choice for imputing missing data in many fields, including social science, health research, and environmental science.</p><p>We can implement it using the <strong>fancyimpute </strong>package</p><pre>import numpy as np<br>import pandas as pd<br>from fancyimpute import IterativeImputer<br><br># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Convert type column to category (so that miceforest can handle as a categorical attribute rather than string)<br>df= df.drop(columns=&#39;type&#39;)<br><br># Get list of columns with missing values<br>missing_cols = df.columns[df.isna().any()].tolist()<br><br># Create an instance of the MICE algorithm<br>imputer = IterativeImputer()<br><br># Fit the imputer to the dataset<br>imputed_array = imputer.fit_transform(df[missing_cols])<br><br># Replace the missing values in the original dataset<br>df[missing_cols] = imputed_array<br><br># View the imputed dataset<br>df</pre><p>Note that this implementation does not touch categorical variables</p><h4>MICEforest imputation</h4><p>Just as fun as it sounds… MICEforest is a variation of MICE (Multiple Imputation by Chained Equations) that uses a lightGBM algorithm to impute missing values in a dataset, rather than regression.</p><p>We can implement it using the <strong>miceforest </strong>package</p><pre>pip install miceforest --no-cache-dir<br><br>conda install -c conda-forge miceforest</pre><pre>import pandas as pd<br>import miceforest as mf<br><br># Read data<br>df = pd.read_csv(&#39;Wine_Quality.csv&#39;)<br><br># Convert type column to category (so that miceforest can handle as a categorical attribute rather than string)<br>df[&#39;type&#39;] = df[&#39;type&#39;].astype(&#39;category&#39;)<br><br># Create an instance of the MICE algorithm<br>imputer = mf.ImputationKernel(data=df, <br>                              save_all_iterations=True, <br>                              random_state=42)<br><br># Fit the imputer to the dataset. Set number of iterations to 3<br>imputer.mice(3, verbose=True)<br><br># Generate the imputed dataset<br>imputed_df = imputer.complete_data()<br><br># View the imputed dataset<br>imputed_df</pre><h3>Conclusion</h3><p>We have explored some (but not all) of the common methods available to help us handle the problem of missing data. Ultimately, the choice of method will depend on the dataset, the amount of missing data, and the analysis goals. It is essential to carefully consider the potential impact of imputing missing data on the final results. Seeking input from subject matter experts and evaluating the quality of imputed data can help ensure the validity of subsequent analyses.</p><p>Dealing with missing data is a critical step in data analysis, and using the suitable imputation method can help us unlock the insights hidden within our data.</p><h4>Links:</h4><ul><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html">Scikit-learn SimpleImputer documentation</a></li><li><a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.KNNImputer.html">Scikit-learn KNNImputer documentation</a></li><li><a href="https://scikit-learn.org/stable/modules/impute.html">Scikit-learn imputation guide</a></li><li><a href="https://pypi.org/project/fancyimpute/">Fancyimpute documentation</a></li><li><a href="https://pypi.org/project/miceforest/">Miceforest documentation</a></li><li><a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3074241/">Multiple imputations by chained equations: what is it, and how does it work?</a></li><li><a href="https://www.jstatsoft.org/article/view/v045i03">Mice: Multivariate Imputation by Chained Equations in R</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a1e48118445" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chaos to Order: Data Pre-processing for Machine Learning Mastery]]></title>
            <link>https://medium.com/@honzj/chaos-to-order-data-pre-processing-for-machine-learning-mastery-9921345ba7d0?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9921345ba7d0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 13:12:19 GMT</pubDate>
            <atom:updated>2023-03-10T13:12:19.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0qcDuE8XLWgwJiEasf88A.jpeg" /></figure><blockquote>Data pre-processing is like preparing a dish — if you don’t clean, peel and chop your ingredients, you won’t end up with a very nice dish.</blockquote><p>Continuing with the culinary analogy, we’ve gathered our ingredients in our <a href="https://medium.com/@h.jurza/unveiling-hidden-insights-a-quick-start-guide-to-exploratory-data-analysis-eda-c843dd710726">exploratory data analysis</a>, and now it’s time to start preparing them for our dish. In this article, we’ll learn how to turn that mess of raw data into a well-organised and refined dataset that’s ready to power your models.</p><p>Data pre-processing is an essential step in machine learning that involves transforming raw data into a clean, structured dataset that machine learning algorithms can easily analyse. The goals of pre-processing are to remove noise, correct errors, and ensure that the data is accurate and complete. Without proper pre-processing, models may suffer from overfitting, underfitting, or other issues that can lead to inaccurate or unreliable results. When carried out well, data pre-processing can significantly improve the quality and reliability of your models.</p><h3>Data cleaning</h3><h4>Checking data types</h4><p>When it comes to data pre-processing, checking and verifying the data types of your features is crucial. This step ensures that each feature is correctly interpreted by your machine learning algorithms and can help you identify potential issues such as incorrect encoding or mixed data types. For example, you might have a column of data that is supposed to contain numeric values but instead has string values due to formatting errors or missing values. This will be important for pre-processing as different data types will be handled differently.</p><h4>Removing duplicate values</h4><p>Duplicate values can occur for various reasons, such as data entry errors, merging data from multiple sources, or technical issues with data collection. If not addressed, duplicate values can lead to biased models, incorrect estimates of variability, and other issues that can impact the accuracy of your results. Therefore, it’s important to identify and remove these from your dataset. This can be done using various techniques, such as sorting the dataset and removing the duplicates or using specific functions in your code to identify and remove duplicates.</p><h4>Removing outliers and anomalies</h4><p>Outliers are data points that lie far outside the expected range of values for a particular feature, while anomalies are values that are completely unexpected and likely represent errors or inaccuracies in data collection or entry. These data points can lead to biased models and incorrect predictions, which can be detrimental in critical applications such as healthcare, finance, and transportation. Depending on your application, you may need to remove these from your dataset before building your models. This can be done using various statistical techniques such as the Z-score, Interquartile Range (IQR) or using visualisation tools such as scatterplots and boxplots to identify extreme values.</p><h4>Handling missing values</h4><p>Missing values are a common problem in real-world datasets. They can occur due to various reasons, such as the structure and quality of the data, data entry errors, data loss during transmission, or incomplete data collection. These missing values can impact the accuracy and reliability of machine learning models, as they can introduce bias and skew your results. Some models don’t work at all with missing values. Therefore, handling missing values appropriately is essential before you build your model.</p><p>There are several techniques for handling missing values. The following are a few common examples:</p><ol><li><strong>Deletion:</strong> This involves removing the rows or columns with missing values. This is usually done when the percentage of missing values is very small or when the missing values do not significantly impact the analysis or results.</li><li><strong>Mean/Median Imputation</strong>: Replacing the missing values with the mean or median, or mode of the feature. This should only be used for <strong>numerical </strong>features (and mean only for a normal distribution).</li><li><strong>Mode Imputation</strong>: Replacing the missing values with the mode, or most commonly occurring value of the feature. This should only be used for categorical features where one category is dominant.</li><li><strong>Forward/Backward Fill</strong>: Filling the missing values with the value from the previous or next observation in the dataset. This method is used for time-series data or when the missing values occur in a pattern.</li><li><strong>Regression Imputation</strong>: Using a regression model to estimate the missing values based on other features in the dataset. This method works well when there is a strong correlation between features.</li><li><strong>Machine learning imputation: </strong>Using a machine learning model such as K-Nearest Neighbours (KNN) or a neural network to estimate the missing value.</li><li><strong>Best guess based on domain knowledge: </strong>Missing values can also be replaced with an estimate informed by domain knowledge and business understanding. This should be done with a subject matter expert who understands the domain and the data.</li></ol><h3>Feature engineering</h3><p>Feature engineering is a powerful step in the pre-processing pipeline, which involves transforming raw data into useful features that can help improve the performance of a model. Feature engineering is important because the performance of machine learning algorithms largely depends on the quality and relevance of the features used as inputs. This process requires a deep understanding of the data, its underlying patterns, and the problem domain.</p><h4>Feature transformation</h4><p>Many machine learning algorithms cannot directly handle categorical data in their original form. Instead, they require numerical data to operate properly. One popular encoding technique is <strong>one-hot encoding</strong>, which transforms each categorical feature into a set of binary features that represent each of the possible values.</p><p>Similarly, we can do the reverse and turn numerical features into categorical ones through <strong>bucketisation</strong> or <strong>binning</strong>. This aims to simplify the data and reduce the noise by grouping similar values together. This can make the data more manageable and easier to analyse and help identify patterns and relationships that may not be apparent in the raw data. There are two main types of binning: equal-width binning (fixed number of equally sized bins) and equal-frequency binning (the number of observations in each bin is equal).</p><h4>Feature construction</h4><p>This involves combining or transforming existing features to create new ones that capture more complex relationships between the input features and our target. Our domain knowledge will help in this component.</p><p>Suppose we are working on a classification problem to predict whether a bank loan will default based on various demographic and financial variables. One of the variables is the borrower’s total income. We could use feature construction to create a new feature that captures the borrower’s debt-to-income ratio, which may better predict loan default risk than total income alone. To do this, we would divide the borrower’s total debt by their total income, creating a new feature that represents their level of debt relative to their income.</p><h4>Feature scaling</h4><p>Feature scaling is a step where we bring all the features to a common scale. In short, feature scaling helps models achieve better performance and accuracy. It ensures that all features have the same level of importance and prevents certain features from dominating others. Scaling can also help improve the convergence rate of some algorithms, such as gradient descent. The scaling technique applied (or whether we use one at all) will depend on the algorithm we choose, as some algorithms only benefit from specific scaling techniques.</p><ul><li><strong>Standardisation</strong>: Scales the features to have a mean of 0 and a standard deviation of 1 by subtracting the mean and dividing by the standard deviation. This is useful for neural networks and other gradient-descent-based algorithms.</li><li><strong>Normalisation: </strong>Scales the features to a range between 0 and 1 by subtracting the minimum value and dividing by the range. Helpful for algorithms that rely on similarity or distance measures such as clustering algorithms, k-Nearest Neighbours (KNN), support vector machines or principal component analysis (PCA)</li><li><strong>Robust scaling:</strong> Similar to normalisation, it is designed to be more robust to outliers than other scaling methods. It scales the features using the interquartile range (IQR) instead of the range or standard deviation.</li><li><strong>Max-abs scale: </strong>Scales the features between -1 and 1 by dividing each feature by its maximum absolute value. Some examples of algorithms that can benefit from max-abs scaling are neural networks and algorithms used for image processing.</li></ul><h3>Feature selection</h3><p>Feature selection techniques involve selecting the most relevant features for the problem at hand based on their importance, correlation, or other statistical measures.</p><h4>Filter methods</h4><p>Features are selected based on their relationship to the target. These methods evaluate each feature independently based on statistical measures such as correlation and then select the top-ranked features. Here we can go back to our EDA and check which features were the most correlated with our target. Examples of filter methods include Pearson correlation coefficient, Chi-square test, and Information gain.</p><h4>Wrapper methods</h4><p>These methods use a model to evaluate the performance of subsets of features and select the subset that yields the best performance (as per a defined performance metric). It evaluates all possible combinations of features on the specific machine learning algorithm we are planning to fit and selects the one with the best result.</p><h4>Embedded methods</h4><p>These methods perform feature selection as part of the learning algorithm and combine both filter and wrapper methods. In this case, the algorithm will perform feature selection and learning simultaneously. Examples of embedded methods include Lasso and Ridge regression, Decision Trees, and Random Forests.</p><h4>Dimensionality reduction techniques</h4><p>These reduce the number of features by projecting them onto a lower-dimensional space while retaining the most important information. Examples of dimensionality reduction techniques include Principal Component Analysis (PCA), Singular Value Decomposition (SVD), and t-distributed Stochastic Neighbor Embedding (t-SNE).</p><h3>Splitting data for modelling</h3><p>When we’re happy with our features, the final step is to split our data into training and testing sets (for supervised learning). Think of it like studying for a test — you wouldn’t just memorise the answers and assume you’re prepared for the whole exam. Similarly, you can’t just train your model on all of your data and hope it performs well on unseen data. By splitting the data into training and testing sets, you can train your model on one set and evaluate its performance on the other. This helps avoid overfitting and ensures your model generalises well to new, unseen data.</p><h4>Holdout method</h4><p>The simplest and most common method is to randomly divide the data into two non-overlapping sets — a training set and a testing set. The size of the testing set can be specified, and the remaining data is used for training the model. Commonly a split of 80% training and 20% testing is used. However, other ratios can be used.</p><h4><strong>Time-based splitting</strong></h4><p>This method is used when the data is time-series data. In this method, the data is split into training and testing sets based on time, where the earlier data is used for training, and the later data is used for testing. This ensures that the model is trained on historical data and tested on future data, simulating real-world scenarios where the model is expected to make predictions on future data.</p><p>When using time-based splitting, the data must be sorted by time before splitting, preventing data leakage (where information from the future is inadvertently used to train the model).</p><h4><strong>Splitting into three sets</strong></h4><p>There are situations where it can be helpful to split the data into three sets. The third set is known as the validation set and is used to evaluate the model&#39;s performance during hyperparameter tuning or model selection. In this scenario, the data is first split into a training set and a testing set. The training set is then used to train the model, and the testing set is used to evaluate the final performance of the model.</p><p>However, before the final evaluation, hyperparameters may need to be adjusted, or multiple models may need to be trained and compared. The validation set is used to make these decisions. This process is repeated with different hyperparameters or models until the best-performing model is selected. Once the best model is selected, it is evaluated on the testing set to estimate its performance on unseen data.</p><h3>Conclusion</h3><p>Data pre-processing and feature selection are critical steps in machine learning that can significantly impact the accuracy and reliability of your models. By following best practices and using proven techniques, you can transform your raw data into high-quality features that unlock the true potential of your models. Remember to carefully analyse your data, identify and remove outliers, and select the most relevant features to ensure that your models are accurate and efficient. With these skills in your toolkit, you’ll be well on your way to becoming a data pre-processing pro and unleashing the full power of your machine learning models.</p><p>Once we’ve finished pre-processing our data, we can start building our models and get cooking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9921345ba7d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Hidden Insights: A Quick Start Guide to Exploratory Data Analysis (EDA)]]></title>
            <link>https://medium.com/@honzj/unveiling-hidden-insights-a-quick-start-guide-to-exploratory-data-analysis-eda-c843dd710726?source=rss-19877de6126c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c843dd710726</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Honzik J]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 00:20:54 GMT</pubDate>
            <atom:updated>2023-03-09T01:31:39.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIyxtvt213ubdeZTwuIHTw.png" /><figcaption>The three-stage exploratory data analysis</figcaption></figure><blockquote>Exploratory Data Analysis is like rummaging through your fridge to see what ingredients you have to work with. Sometimes you find something unexpected and end up making a masterpiece, and other times you just make a sandwich. — Unknown</blockquote><p>If you’re an aspiring data chef, you know how crucial it is to know your ingredients before you start cooking. Exploratory data analysis (EDA) is the secret sauce in the <a href="https://medium.com/@h.jurza/an-overview-of-the-data-science-lifecycle-72b3e082296">data science lifecycle </a>that helps uncover hidden patterns, anomalies, and relationships that could be the difference between success and failure in any data analysis project. But where do you start? What questions should you ask? Fear not, in this article, we will explore the world of EDA, unveiling the key steps to follow and the crucial questions to ask. So let’s dive into the world of data exploration!</p><h3><strong>The Three-Stage EDA:</strong></h3><p>There is no single correct way to carry out an EDA, as it is as much of an art as a science. However, with practice, you can develop and refine your own methodology. To simplify this process, I have summarised the broad goals of EDA into the following stages:</p><ol><li><strong>Understanding your Data Structure and Quality</strong></li><li><strong>Understanding the shape of your data</strong></li><li><strong>Uncovering patterns and relationships in your data</strong></li></ol><p>Let’s dive into these in a little more detail.</p><h3><strong>Understand your Data Structure and Quality</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFZVqRWrLO6np5UsZc89ww.png" /></figure><p>EDA provides an opportunity to get familiar with the dataset you’ll be working with. This includes identifying the different features, checking for missing values, and assessing the overall quality of the data. Note that throughout this article, I will use the term ‘features’ rather than ‘variables’ but consider them interchangeable in the context of this article and use whichever you are more comfortable with.</p><h4><strong>Understand the data structure</strong></h4><p>First, we observe the structure of our data from a high level, including the number of observations and features, their types, and how they are organised.</p><h4>Categorise features</h4><p>Next, let’s categorise our features. This will inform us how we visualise and process them. We can define each feature as:</p><ul><li><strong>Categorical</strong>: These represent a set number of categories and can be either nominal or ordinal.</li><li><strong>Continuous</strong>: Numeric data that can take an infinite range of values.</li><li><strong>Other</strong>: You may have features such as free text. While these are technically categorical data, you may treat as individual values, rather than as members of a category.</li></ul><p>This is also an excellent time to look at data types. If you have a categorical feature that is ordinal and represented by numbers, you’ll want to represent it with an integer rather than a float. Another example is numeric data in a string or character field.</p><h4><strong>Identify key features</strong></h4><p>Once we know the types of features we have, let’s identify the key features. <br>We can return to our problem formulation and business problem to assist with this.</p><p>With a supervised machine learning method, we will look into what we will use as our ‘target’. This feature represents the outcome we are trying to predict (also known as the ‘label’, ‘dependent variable’ or ‘response variable’). For example, if we are building a model to predict house prices, our target will be the price.</p><p>With an unsupervised method such as clustering, we can think about what features we’ll use as input to the clustering.</p><h4><strong>Assess data quality</strong></h4><p>Next, we identify missing values in each field and think about how we may handle them before analysis. Many machine learning models do not work with missing values, so we’ll need to deal with these in data pre-processing. It’s also a good idea to consider why they are missing, as this might be avoidable in the data collection step.</p><h3>Understanding individual features — Univariate Analysis</h3><p>Once we understand what features we have in the data and have an idea of how we might deal with them, we can start looking at the shape of the data they contain.</p><p>One of the primary tools we will be using is visualisation. EDA often involves creating visualisations of the data to help identify patterns and relationships that may not be immediately apparent. Visualisations can help identify correlations between variables, trends over time and help identify potential outliers.</p><h4>Summary statistics</h4><p>First, we will summarise the characteristics of individual features. We can create summary tables of the following descriptive statistics.</p><ul><li><strong>Central Tendency </strong>(mean, median, mode)</li><li><strong>Variability</strong> (standard deviation, variance, range, interquartile range)</li></ul><p>Here are some code examples of summary statistics in Python and R respectively:</p><pre>import pandas as pd<br><br># Load data from a CSV file<br>data = pd.read_csv(&quot;data.csv&quot;)<br><br># Get summary statistics<br>summary = data[&quot;column_name&quot;].describe()<br><br># Print summary statistics<br>print(summary)</pre><pre># Load data from a CSV file<br>data &lt;- read.csv(&quot;data.csv&quot;)<br><br># Get summary statistics<br>summary &lt;- summary(data$column_name)<br><br># Print summary statistics<br>print(summary)</pre><h4>Plots</h4><p>We can also produce plots of the distributions to get a visual feel for the features and understand:</p><ul><li><strong>Distribution type</strong></li><li><strong>Skewness</strong></li></ul><p>For categorical features, you can produce frequency bar charts. For continuous, you can plot a histogram.</p><p>Here are examples in Python and R:</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Load data into a pandas DataFrame<br>data = pd.read_csv(&#39;data.csv&#39;)<br><br># Plot a histogram with a KDE<br>sns.histplot(data, x=&#39;column_name&#39;, kde=True)<br>plt.title(&#39;Distribution of Data&#39;)<br>plt.xlabel(&#39;Column Name&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br><br># Show the plot<br>plt.show()</pre><pre># Load data from a CSV file<br>data &lt;- read.csv(&quot;data.csv&quot;)<br><br># Plot a histogram with a KDE<br>library(ggplot2)<br>ggplot(data, aes(x=column_name)) +<br>  geom_histogram(aes(y=..density..), binwidth=0.5, color=&quot;black&quot;, fill=&quot;white&quot;) +<br>  geom_density(alpha=.2, fill=&quot;#FF6666&quot;) +<br>  ggtitle(&quot;Distribution of Data&quot;) +<br>  xlab(&quot;Column Name&quot;) +<br>  ylab(&quot;Density&quot;)</pre><h4><strong>Identify outliers and anomalies.</strong></h4><p>Outliers and anomalies in the data may require further investigation or correction. By understanding the distributions, we can more easily identify any anomalies.</p><p>Repeat this for each of your features one by one, and note any anomalies or noteworthy observations that may be useful in your analysis.</p><h3><strong>Uncovering relationships in your data — </strong>Bivariate Analysis</h3><p>After we have looked at our features in isolation, we can start looking at the relationships between <strong>pairs </strong>of features. This will help uncover relationships between the variables. This is a part that will give you a chance to generate hypotheses for further analysis.</p><h4>Correlations between features and target</h4><p>This will help us understand the relationship between the features and the outcome we are testing for. This will inform which features are of importance to include in our model (feature selection). An excellent way to do this is to calculate the correlation coefficient between your target and every other feature and plot a bar chart of the correlation.</p><p>Examples:</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Load data from a CSV file<br>data = pd.read_csv(&quot;data.csv&quot;)<br><br># Calculate correlations between all pairs of variables in the dataset<br>corr = data.corr()<br><br># Get correlations fo target and sort by descending order<br>corr = corr[&#39;target&#39;].sort_values(ascending=False)<br><br># Create barplot using the Seaborn library.<br>sns.barplot(x=corr.index, y=corr)<br><br># Rotate x-axis labels for readability<br>plt.xticks(rotation=90)<br><br># Show the plot<br>plt.show()</pre><pre># Load data from a CSV file<br>data &lt;- read.csv(&quot;data.csv&quot;)<br><br># Calculate correlations<br>corr &lt;- cor(data)<br><br># Get correlations for target variable<br>target_corr &lt;- corr[&quot;target&quot;, ]<br><br># Sort correlations by descending order<br>target_corr &lt;- sort(target_corr, decreasing=TRUE)<br><br># Create barplot<br>library(ggplot2)<br>ggplot(data.frame(variable=names(target_corr), correlation=target_corr), aes(x=variable, y=correlation)) +<br>  geom_bar(stat=&quot;identity&quot;, fill=&quot;blue&quot;) +<br>  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +<br>  labs(title=&quot;Correlations with target variable&quot;)</pre><h4>Correlations between other variables</h4><p>Correlated or redundant features in our data can adversely affect our models, and we typically want to reduce redundancy. The best way to visualise this is a correlation heatmap. Another useful type of plot is a ‘pair plot’ which summarises the relationships between pairs of features and plots them in one command.</p><p>Examples:</p><pre>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br># Load data from a CSV file<br>data = pd.read_csv(&quot;data.csv&quot;)<br><br># Calculate correlations between all pairs of variables in the dataset<br>corr = data.corr()<br><br># Create heatmap of the correlations using the Seaborn library. <br># The annot=True parameter adds numeric annotations to the heatmap,<br>sns.heatmap(corr, annot=True, cmap=&quot;coolwarm&quot;)<br><br># Show the plot<br>plt.show()</pre><pre># Load data from a CSV file<br>data &lt;- read.csv(&quot;data.csv&quot;)<br><br># Calculate correlations between all pairs of variables in the dataset<br>corr &lt;- cor(data)<br><br># Create heatmap using the corrplot library. <br># The type=&quot;upper&quot; parameter displays only the upper triangle of the heatmap<br># (since the correlations matrix is symmetric)<br>library(corrplot)<br>corrplot(corr, type=&quot;upper&quot;, method=&quot;circle&quot;, tl.col=&quot;black&quot;, tl.srt=45)<br><br># Show the plot</pre><p>We should take note of any groups of features that exhibit a correlation with each other and revisit this when we are building our model. Removing redundant features can often improve model performance.</p><h4>Formulating Hypotheses</h4><p>EDA involves formulating hypotheses and testing them against the data. This process involves asking questions about the data and testing whether the data supports or refutes these hypotheses. We can also check for assumptions of statistical models or methods, such as normality or independence.</p><h4>A useful tool</h4><p>For Python users, a valuable tool called Pandas Profiling is a quick and efficient way to profile your data. It does many of the above tasks in one shot and can be a huge time-saver. Once you have generated the report, you can open the HTML file in your web browser to view it. The report includes interactive visualizations and tables that allow you to explore your data in more detail.</p><p>Example in python:</p><pre>import pandas as pd<br>import pandas_profiling as pp<br><br># Load data from a CSV file<br>data = pd.read_csv(&quot;data.csv&quot;)<br><br># Generate the report<br>report = pp.ProfileReport(data)<br><br># Save the report as an HTML file<br>report.to_file(&quot;report.html&quot;)</pre><p>You can also render the report within your Jupyter notebook using the following code:</p><pre># Render the report as a Jupyter notebook widget<br>display(report)</pre><h3>Going deeper</h3><p>If we want to go deeper, we can do multivariate analysis. While it is difficult for the human brain to conceptualise a relationship between more than two features, we can think of it as a deeper pattern or interaction.</p><p>Multivariate analysis is a powerful tool for exploratory data analysis (EDA) as it allows data scientists to examine the relationships between multiple variables simultaneously. Here are some common types of multivariate analysis that can be used in EDA:</p><ul><li><strong>Cluster Analysis: </strong>Cluster analysis is a technique that groups similar observations or variables into clusters based on their similarity or distance. It can help identify patterns and relationships in the data and segment it into meaningful groups.</li><li><strong>Factor Analysis:</strong> Factor analysis is a statistical method that identifies underlying factors or constructs that are not directly observable in the data. It can help to identify common patterns and relationships between variables and reduce the number of variables in the analysis.</li><li><strong>Principal Component Analysis (PCA)</strong>: PCA is a technique that reduces the dimensionality of the dataset by transforming it into a set of uncorrelated variables called principal components. This can help to identify patterns and relationships in the data and simplify complex datasets.</li></ul><h3><strong>Conclusion</strong></h3><p>By conducting thorough EDA, we can unlock the full potential of our data and ensure we end up with a meaningful analysis or model.</p><p>Once we know what’s in the refrigerator, we can cook up a masterpiece…or just make a sandwich.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c843dd710726" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>