Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Read by thought-leaders and decision-makers around the world. Phone Number: +1-650-246-9381 Email: pub@towardsai.net
228 Park Avenue South New York, NY 10003 United States
Website: Publisher: https://towardsai.net/#publisher Diversity Policy: https://towardsai.net/about Ethics Policy: https://towardsai.net/about Masthead: https://towardsai.net/about
Name: Towards AI Legal Name: Towards AI, Inc. Description: Towards AI is the world's leading artificial intelligence (AI) and technology publication. Founders: Roberto Iriondo, , Job Title: Co-founder and Advisor Works for: Towards AI, Inc. Follow Roberto: X, LinkedIn, GitHub, Google Scholar, Towards AI Profile, Medium, ML@CMU, FreeCodeCamp, Crunchbase, Bloomberg, Roberto Iriondo, Generative AI Lab, Generative AI Lab Denis Piffaretti, Job Title: Co-founder Works for: Towards AI, Inc. Louie Peters, Job Title: Co-founder Works for: Towards AI, Inc. Louis-François Bouchard, Job Title: Co-founder Works for: Towards AI, Inc. Cover:
Towards AI Cover
Logo:
Towards AI Logo
Areas Served: Worldwide Alternate Name: Towards AI, Inc. Alternate Name: Towards AI Co. Alternate Name: towards ai Alternate Name: towardsai Alternate Name: towards.ai Alternate Name: tai Alternate Name: toward ai Alternate Name: toward.ai Alternate Name: Towards AI, Inc. Alternate Name: towardsai.net Alternate Name: pub.towardsai.net
5 stars – based on 497 reviews

Frequently Used, Contextual References

TODO: Remember to copy unique IDs whenever it needs used. i.e., URL: 304b2e42315e

Resources

Take our 85+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

Publication

Chest X-Ray Based Pneumonia Classification
Latest   Machine Learning

Chest X-Ray Based Pneumonia Classification

Last Updated on July 24, 2023 by Editorial Team

Author(s): Akula Hemanth Kumar

Originally published on Towards AI.

Making computer vision easy with Monk, low code Deep Learning tool and a unified wrapper for Computer Vision.

Monk Library

U+1F4CCMonk is an opensource low-code tool for computer vision and deep learning.

Monk features

U+1F4CC Low-code.

U+1F4CC Unified wrapper over major deep learning framework-Keras, PyTorch, Gluoncv.

U+1F4CC Syntax invariant wrapper.

Enables

U+1F4CC Users to create, manage and version control deep learning experiments.

U+1F4CC Users to compare experiments across training metrics.

U+1F4CC Users to quickly find the best hyperparameters.

Table of Contents

U+2611 Installation

U+2611 Download dataset

U+2611 Details on dataset

U+2611 Quick Prototyping-Training, Validation, and Inference

U+2611 Train a classifier using Resnet50

U+2611 Train a classifier using Densenet121

U+2611 Compare Experiments

Installation

$ !git clone https://github.com/Tessellate-Imaging/monk_v1.git# If using Colab install using the commands below
$ !cd monk_v1/installation/Misc && pip install -r requirements_colab.txt

Download dataset

Dataset — Chest X-Ray Images (Pneumonia)

$ ! wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1li6ctqAvGFgIGMSt-mYrLoM_tbYkzqdO' -O- U+007C sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1li6ctqAvGFgIGMSt-mYrLoM_tbYkzqdO" -O chest_xray.zip && rm -rf /tmp/cookies.txt

Unzip the data

$ ! unzip -qq chest_xray.zip

Details on the dataset

What is Pneumonia?

  • It is an infection in one or both lungs.
  • It is caused by bacteria, viruses, and fungi.
  • Pneumonia is an infection, which causes inflammation in the air sacs in your lungs, called alveoli.

General Symptoms

  • Fever
  • Chills
  • Cough
  • Shortness of breath
  • Fatigue

What are the different types of Bacterial pneumonia?

  • Bacteria cause most cases of community-acquired pneumonia in adults.
  • A person can catch pneumonia when someone who is infected coughs or sneezes.
  • The bacteria-filled droplets get into the air, where you can breathe them into your nose or mouth.
  • It typically exhibits a focal lobar consolidation.

Bacterial Pneumonia as seen on a chest X-ray.

Normal chest X-ray
Abnormal chest X-ray with consolidation from pneumonia in the right lung, middle or inferior lobe (white area, left side of image)

What are the different types of Viral pneumonia

  • Viruses are the second most common cause of pneumonia.
  • Many different ones cause the disease, including some of the same viruses that bring on colds and flu.
  • Fever, Chills, Dry cough, which may get worse and make mucus, Stuffy nose.
  • Viral pneumonia (right) manifests with a more diffuse “interstitial” pattern in both lungs.

Viral Pneumonia as seen on chest X-ray

Viral Pneumonia

What are the different types of Walking pneumonia

  • A less severe form of bacterial pneumonia. Sometimes doctors call it “atypical” pneumonia.
  • Symptoms can be so mild that you don’t know you have it. You may feel well enough that you’re able to go about your regular activities, which is where the “walking” in the name comes from.

What are the different types of Fungal pneumonia

  • Fungi are a less common cause of pneumonia. You’re not likely to get fungal pneumonia if you’re healthy.
  • But you have a higher chance of catching it if your immune system is weakened from a major operation, organ transplant, HIV.
  • You get fungal pneumonia by breathing in tiny particles called fungal spores.

Need for such an application

  • Bacterial pneumonia requires an urgent referral for immediate antibiotic treatment.
  • Viral pneumonia is treated with supportive care. Therefore, an accurate and timely diagnosis is imperative.
  • Rapid radiologic interpretation of images is not always available, particularly in the low-resource settings where childhood pneumonia has the highest incidence and highest rates of mortality.
  • Thus using transfer learning in classifying pediatric chest X-rays.

Dataset

  • Labeled a total of 5,232 chest X-ray images from children.
  • Training set includes 3,883 characterized as depicting pneumonia (2,538 bacterial and 1,345 viral) and 1,349 normal, from a total of 5,856 patients.
  • The test set includes 234 normal images and 390 pneumonia images (242 bacterial and 148 viral) from 624 patients.

Labels

  • Normal x-ray
  • Pneumonia x-ray

Quick Prototyping — Training, Validation, and Inferencing

Transfer Learning

Base Network

  • A convolutional neural network is first trained on large datasets such as coco or Imagenet.
  • These datasets have many classes, like around 1000, 1500 classes.
  • Thus the final layer in the neural network has a similar number of neurons.

Finetuning on custom dataset

  • A custom dataset usually has a different number of classes.
  • You take the network and load the pre-trained weights on the network.
  • Then remove the final layer that has the extra(or less) number of neurons.
  • You add a new layer with a number of neurons = number of classes in your custom dataset.
  • Optionally you can add more layers in between this newly added final layer and the old network.

What is quick prototyping?

  • Every image classification projects start with the basic step of trying out a transfer learning.

In transfer learning, you take a deep learning model trained on a very large dataset

  • Then train it further on your custom dataset.

While doing this you need to select a lot of hyper-parameters

  • First the model itself, like ResNet or DenseNet, you can never be sure what to use.
  • Then dataset parameters such as batch size, input shape, etc.
  • Then model parameters such as freezing layers, not using pre-trained models, etc.
  • Then setting up which optimizer, loss function, a learning rate scheduler, etc to select.
  • And finally, the number of epochs to train on.

Note: Not everything can be done at the very first step, thus the quick prototyping mode.

Which allows you to

  • Set the model.
  • Whether to use a pre-trained network or train from scratch.
  • The number of epochs.

All the other parameters are set to default as per their original research papers.

  • Then can be changed in Monk’s intermediate and expert modes.

Creating and managing experiments

  • Provide a project name.
  • Provide an experiment name.
  • For specific data create a single project.
  • In each project, multiple experiments can be created.
  • Every experiment can we have different hyper-parameters attached to it.
$ gtf = prototype(verbose=1);
$ gtf.Prototype("Pneumonia_Classification", "Quick_Prototype");

Output

Mxnet Version: 1.5.0

Experiment Details
Project: Pneumonia_Classification
Experiment: Quick_Prototype
Dir: /home/abhi/Downloads/webinar_2/workspace/Pneumonia_Classification/Quick_Prototype/

This creates files and directories as per the following structure

workspace
U+007C
U+007C----Pneumonia_Classification
U+007C
U+007C
U+007C---Quick_Prototype
U+007C
U+007C--experiment-state.json
U+007C
U+007C--output
U+007C
U+007C------logs
U+007C
U+007C------models

Quick mode training

- Using Default Function
- dataset_path
- model_name
- num_epochs

Dataset folder structure

parent_directory
U+007C
U+007C
U+007C
U+007C----training
U+007C------Infected
U+007C
U+007C------img1.jpg
U+007C------img2.jpg
U+007C------.... (and so on)
U+007C------Normal
U+007C
U+007C------img1.jpg
U+007C------img2.jpg
U+007C------.... (and so on)
U+007C
U+007C
U+007C----validation
U+007C------Infected
U+007C
U+007C------img1.jpg
U+007C------img2.jpg
U+007C------.... (and so on)
U+007C------Normal
U+007C
U+007C------img1.jpg
U+007C------img2.jpg
U+007C------.... (and so on)

Modifiable params

  • dataset_path: the path to data
  • model_name: which pre-trained model to use
  • freeze_base_network: Retrain already trained network or not
  • num_epochs: Number of epochs to train for
$ gtf.Default(dataset_path="chest_xray/train",
model_name="resnet18_v1",
num_epochs=5)
#Start Training
$ gtf.Train();

Train vs Val vs Test Dataset

Train

  • The model sees and learns from this data.
  • 80% of the original training data in our case.

Validation

  • The sample of data used to provide an unbiased evaluation of a model fit on the training dataset while tuning model hyperparameters.
  • 20% of the original training data in our case.

Test

  • The test dataset is a dataset used to provide an unbiased evaluation of a final model fit on the training dataset.
  • External set.

Running inference on test images

Load the experiment in inference mode

  • Set flag eval_infer as True.
$ gtf = prototype(verbose=1);
$ gtf.Prototype("Pneumonia_Classification", "Quick_Prototype", eval_infer=True);

Output

Mxnet Version: 1.5.0

Model Details
Loading model - workspace/Pneumonia_Classification/Quick_Prototype/output/models/final-symbol.json
Model loaded!

Experiment Details
Project: Pneumonia_Classification
Experiment: Quick_Prototype
Dir: /home/abhi/Downloads/webinar_2/workspace/Pneumonia_Classification/Quick_Prototype/

Select image and Run inference

$ img_name = "chest_xray/infer/normal-1.jpeg";
$ predictions = gtf.Infer(img_name=img_name);

#Display
$ from IPython.display import Image
$ Image(filename=img_name)

Output

Prediction
Image name: chest_xray/infer/normal-1.jpeg
Predicted class: NORMAL
Predicted score: 7.098179340362549
NORMAL
$ img_name = "chest_xray/infer/pneumonia-1.jpeg";
$ predictions = gtf.Infer(img_name=img_name);

#Display
$ from IPython.display import Image
$ Image(filename=img_name)

Output

Prediction
Image name: chest_xray/infer/pneumonia-1.jpeg Predicted class: PNEUMONIA
Predicted score: 3.6506881713867188
PNEUMONIA

Train a classifier using Resnet50

ResNet Block

Readings on ResNet

Points from Towards Data Science

  • The core idea of ResNet is introducing a so-called “identity shortcut connection” that skips one or more layers.
  • The deeper model should not produce a training error higher than its shallower counterparts.
  • Solves the problem of vanishing gradients as network depth increased.

Points from Medium

  • Won 1st place in the ILSVRC 2015 classification competition with a top-5 error rate of 3.57% (An ensemble model).
  • Efficiently trained networks with 100 layers and 1000 layers also.
  • Replacing VGG-16 layers in Faster R-CNN with ResNet-101. They observed relative improvements of 28%.

Read more here

ResNet Block — 1

Properties

This block has 2 branches

  • The first branch is the identity branch, it takes the input and pushes it as the output, the Residual.
  • The second branch has these layers
  • batchnorm -> relu -> conv_1x1 -> batchnorm -> relu -> conv_3x3 -> batchnorm -> relu -> conv_1x1.

The branches are added elementwise, so both the branches need to have same sized output.

The final layer of this block is Relu.

The bottleneck

  • The num features in first and middle convolutions are input_features/4
  • The final convolution has features = input_features.

ResNet Block — 2

Properties

The block has two starting elements

  • batchnorm -> Relu

Post the starting elements this block has 2 branches

The first branch has these layers

  • conv_1x1

Second branch has these layers

  • conv_1x1 -> batchnorm -> Relu -> conv_3x3 -> batchnorm -> Relu -> conv_1x1.

The branches are added elementwise, so both the branches need to have same sized output.

#Set project and experiment
$ gtf = prototype(verbose=1)
$ gtf.Prototype("Pneumonia_Classification", "Experiment_1")
#Load data and model
$ gtf.Default(dataset_path="chest_xray/train", model_name="resnet50_v2",freeze_base_network=False, num_epochs=5)
# Train
$ gtf.Train()

Train a classifier using Densenet121

Dense Block

Readings on Densenet

Points from Medium

  • “This architecture resulted from the desire to improve higher layer architectures that were being developed. Specifically, improving the problem that many of the layers in high-layer networks were in a sense redundant.”

Points from Towards Data Science

  • Each layer is receiving a “collective knowledge” from all preceding layers. (See image above).
#Set project and experiment
$ gtf = prototype(verbose=1)
$ gtf.Prototype("Pneumonia_Classification", "Experiment_2")
#Load data and model
$ gtf.Default(dataset_path="chest_xray/train", model_name="densenet121",freeze_base_network=False, num_epochs=5)
# Train
$ gtf.Train()

Compare Experiments

# Invoke the comparison class
$ from compare_prototype import compare

Creating and managing comparison experiments

  • Provide a project name
# Create a project 
$ gtf = compare(verbose=1);
$ gtf.Comparison("Exp_1_vs_2")

Output

Comparison: - Exp_1_vs_2

Add the experiments

  • First argument — Project name
  • Second argument — Experiment name
$ gtf.Add_Experiment("Pneumonia_Classification", "Experiment_1")
$ gtf.Add_Experiment("Pneumonia_Classification", "Experiment_2")

Output

Project - Pneumonia_Classification, Experiment - Experiment_1 added Project - Pneumonia_Classification, Experiment - Experiment_2 added

Run Analysis

$ gtf.Generate_Statistics()

This creates files and directories as per the following structure

workspace
U+007C
U+007C--------comparison
U+007C
U+007C
U+007C-----Exp_1_vs_2
U+007C
U+007C------stats_best_val_acc.png
U+007C------stats_max_gpu_usage.png
U+007C------stats_training_time.png
U+007C------train_accuracy.png
U+007C------train_loss.png
U+007C------val_accuracy.png
U+007C------val_loss.png
U+007C
U+007C-----comparison.csv (Contains necessary details of all experiments)

Training Accuracy Curves

Training Accuracy Curves

Training Loss Curves

Training Loss Curves

Validation Accuracy Curves

Validation Accuracy Curves

Validation loss curves

Validation loss curves

Training time curves

Training time curves

Max GPU usages

Max GPU usages

Best Validation accuracies

Best Validation accuracies

Both worked equally well on the validation data

Let’s check the performance on the test set

ResNet

gtf = prototype(verbose=1);
gtf.Prototype("Pneumonia_Classification", "Experiment_1", eval_infer=True);


# Load test data
gtf.Dataset_Params(dataset_path="chest_xray/test");
gtf.Dataset();


# Test for accuracy
accuracy, class_based_accuracy = gtf.Evaluate();

Output

Mxnet Version: 1.5.0

Model Details
Loading model - workspace/Pneumonia_Classification/Experiment_1/output/models/final-symbol.json
Model loaded!

Experiment Details
Project: Pneumonia_Classification
Experiment: Experiment_1
Dir: /home/abhi/Downloads/webinar_2/workspace/Pneumonia_Classification/Experiment_1/

Dataset Details
Test path: chest_xray/test
CSV test path: None

Dataset Params
Input Size: 224
Processors: 4

Pre-Composed Test Transforms
[{'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]

Dataset Numbers
Num test images: 624
Num classes: 2

Testing
HBox(children=(IntProgress(value=0, max=624), HTML(value='')))Result
class based accuracies
0. NORMAL - 55.55555555555556 %
1. PNEUMONIA - 98.2051282051282 %
total images: 624
num correct predictions: 513
Average accuracy (%): 82.21153846153845

DenseNet

$ gtf = prototype(verbose=1);
$ gtf.Prototype("Pneumonia_Classification", "Experiment_2", eval_infer=True);


# Load test data
$ gtf.Dataset_Params(dataset_path="chest_xray/test");
$ gtf.Dataset();


# Test for accuracy
$ accuracy, class_based_accuracy = gtf.Evaluate()

Output

Mxnet Version: 1.5.0

Model Details
Loading model - workspace/Pneumonia_Classification/Experiment_2/output/models/final-symbol.json
Model loaded!

Experiment Details
Project: Pneumonia_Classification
Experiment: Experiment_2
Dir: /home/abhi/Downloads/webinar_2/workspace/Pneumonia_Classification/Experiment_2/

Dataset Details
Test path: chest_xray/test
CSV test path: None

Dataset Params
Input Size: 224
Processors: 4

Pre-Composed Test Transforms
[{'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]

Dataset Numbers
Num test images: 624
Num classes: 2

Testing
HBox(children=(IntProgress(value=0, max=624), HTML(value='')))Result
class based accuracies
0. NORMAL - 62.39316239316239 %
1. PNEUMONIA - 98.71794871794873 %
total images: 624
num correct predictions: 531
Average accuracy (%): 85.09615384615384

Densenet performed better in this case on test set

You can find the complete jupyter notebook on Github. Give us ⭐️ on our GitHub repo if you like Monk.

If you have any questions, you can reach Abhishek and Akash. Feel free to reach out to them.

I am extremely passionate about computer vision and deep learning in general. I am an open-source contributor to Monk Libraries.

You can also see my other writings at:

Akula Hemanth Kumar – Medium

Read writing from Akula Hemanth Kumar on Medium. Computer vision enthusiast U+007CLinkedin…

medium.com

Photo by Annie Spratt on Unsplash

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI

Feedback ↓

Sign Up for the Course
`; } else { console.error('Element with id="subscribe" not found within the page with class "home".'); } } }); // Remove duplicate text from articles /* Backup: 09/11/24 function removeDuplicateText() { const elements = document.querySelectorAll('h1, h2, h3, h4, h5, strong'); // Select the desired elements const seenTexts = new Set(); // A set to keep track of seen texts const tagCounters = {}; // Object to track instances of each tag elements.forEach(el => { const tagName = el.tagName.toLowerCase(); // Get the tag name (e.g., 'h1', 'h2', etc.) // Initialize a counter for each tag if not already done if (!tagCounters[tagName]) { tagCounters[tagName] = 0; } // Only process the first 10 elements of each tag type if (tagCounters[tagName] >= 2) { return; // Skip if the number of elements exceeds 10 } const text = el.textContent.trim(); // Get the text content const words = text.split(/\s+/); // Split the text into words if (words.length >= 4) { // Ensure at least 4 words const significantPart = words.slice(0, 5).join(' '); // Get first 5 words for matching // Check if the text (not the tag) has been seen before if (seenTexts.has(significantPart)) { // console.log('Duplicate found, removing:', el); // Log duplicate el.remove(); // Remove duplicate element } else { seenTexts.add(significantPart); // Add the text to the set } } tagCounters[tagName]++; // Increment the counter for this tag }); } removeDuplicateText(); */ // Remove duplicate text from articles function removeDuplicateText() { const elements = document.querySelectorAll('h1, h2, h3, h4, h5, strong'); // Select the desired elements const seenTexts = new Set(); // A set to keep track of seen texts const tagCounters = {}; // Object to track instances of each tag // List of classes to be excluded const excludedClasses = ['medium-author', 'post-widget-title']; elements.forEach(el => { // Skip elements with any of the excluded classes if (excludedClasses.some(cls => el.classList.contains(cls))) { return; // Skip this element if it has any of the excluded classes } const tagName = el.tagName.toLowerCase(); // Get the tag name (e.g., 'h1', 'h2', etc.) // Initialize a counter for each tag if not already done if (!tagCounters[tagName]) { tagCounters[tagName] = 0; } // Only process the first 10 elements of each tag type if (tagCounters[tagName] >= 10) { return; // Skip if the number of elements exceeds 10 } const text = el.textContent.trim(); // Get the text content const words = text.split(/\s+/); // Split the text into words if (words.length >= 4) { // Ensure at least 4 words const significantPart = words.slice(0, 5).join(' '); // Get first 5 words for matching // Check if the text (not the tag) has been seen before if (seenTexts.has(significantPart)) { // console.log('Duplicate found, removing:', el); // Log duplicate el.remove(); // Remove duplicate element } else { seenTexts.add(significantPart); // Add the text to the set } } tagCounters[tagName]++; // Increment the counter for this tag }); } removeDuplicateText(); //Remove unnecessary text in blog excerpts document.querySelectorAll('.blog p').forEach(function(paragraph) { // Replace the unwanted text pattern for each paragraph paragraph.innerHTML = paragraph.innerHTML .replace(/Author\(s\): [\w\s]+ Originally published on Towards AI\.?/g, '') // Removes 'Author(s): XYZ Originally published on Towards AI' .replace(/This member-only story is on us\. Upgrade to access all of Medium\./g, ''); // Removes 'This member-only story...' }); //Load ionic icons and cache them if ('localStorage' in window && window['localStorage'] !== null) { const cssLink = 'https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css'; const storedCss = localStorage.getItem('ionicons'); if (storedCss) { loadCSS(storedCss); } else { fetch(cssLink).then(response => response.text()).then(css => { localStorage.setItem('ionicons', css); loadCSS(css); }); } } function loadCSS(css) { const style = document.createElement('style'); style.innerHTML = css; document.head.appendChild(style); } //Remove elements from imported content automatically function removeStrongFromHeadings() { const elements = document.querySelectorAll('h1, h2, h3, h4, h5, h6, span'); elements.forEach(el => { const strongTags = el.querySelectorAll('strong'); strongTags.forEach(strongTag => { while (strongTag.firstChild) { strongTag.parentNode.insertBefore(strongTag.firstChild, strongTag); } strongTag.remove(); }); }); } removeStrongFromHeadings(); "use strict"; window.onload = () => { /* //This is an object for each category of subjects and in that there are kewords and link to the keywods let keywordsAndLinks = { //you can add more categories and define their keywords and add a link ds: { keywords: [ //you can add more keywords here they are detected and replaced with achor tag automatically 'data science', 'Data science', 'Data Science', 'data Science', 'DATA SCIENCE', ], //we will replace the linktext with the keyword later on in the code //you can easily change links for each category here //(include class="ml-link" and linktext) link: 'linktext', }, ml: { keywords: [ //Add more keywords 'machine learning', 'Machine learning', 'Machine Learning', 'machine Learning', 'MACHINE LEARNING', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, ai: { keywords: [ 'artificial intelligence', 'Artificial intelligence', 'Artificial Intelligence', 'artificial Intelligence', 'ARTIFICIAL INTELLIGENCE', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, nl: { keywords: [ 'NLP', 'nlp', 'natural language processing', 'Natural Language Processing', 'NATURAL LANGUAGE PROCESSING', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, des: { keywords: [ 'data engineering services', 'Data Engineering Services', 'DATA ENGINEERING SERVICES', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, td: { keywords: [ 'training data', 'Training Data', 'training Data', 'TRAINING DATA', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, ias: { keywords: [ 'image annotation services', 'Image annotation services', 'image Annotation services', 'image annotation Services', 'Image Annotation Services', 'IMAGE ANNOTATION SERVICES', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, l: { keywords: [ 'labeling', 'labelling', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, pbp: { keywords: [ 'previous blog posts', 'previous blog post', 'latest', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, mlc: { keywords: [ 'machine learning course', 'machine learning class', ], //Change your article link (include class="ml-link" and linktext) link: 'linktext', }, }; //Articles to skip let articleIdsToSkip = ['post-2651', 'post-3414', 'post-3540']; //keyword with its related achortag is recieved here along with article id function searchAndReplace(keyword, anchorTag, articleId) { //selects the h3 h4 and p tags that are inside of the article let content = document.querySelector(`#${articleId} .entry-content`); //replaces the "linktext" in achor tag with the keyword that will be searched and replaced let newLink = anchorTag.replace('linktext', keyword); //regular expression to search keyword var re = new RegExp('(' + keyword + ')', 'g'); //this replaces the keywords in h3 h4 and p tags content with achor tag content.innerHTML = content.innerHTML.replace(re, newLink); } function articleFilter(keyword, anchorTag) { //gets all the articles var articles = document.querySelectorAll('article'); //if its zero or less then there are no articles if (articles.length > 0) { for (let x = 0; x < articles.length; x++) { //articles to skip is an array in which there are ids of articles which should not get effected //if the current article's id is also in that array then do not call search and replace with its data if (!articleIdsToSkip.includes(articles[x].id)) { //search and replace is called on articles which should get effected searchAndReplace(keyword, anchorTag, articles[x].id, key); } else { console.log( `Cannot replace the keywords in article with id ${articles[x].id}` ); } } } else { console.log('No articles found.'); } } let key; //not part of script, added for (key in keywordsAndLinks) { //key is the object in keywords and links object i.e ds, ml, ai for (let i = 0; i < keywordsAndLinks[key].keywords.length; i++) { //keywordsAndLinks[key].keywords is the array of keywords for key (ds, ml, ai) //keywordsAndLinks[key].keywords[i] is the keyword and keywordsAndLinks[key].link is the link //keyword and link is sent to searchreplace where it is then replaced using regular expression and replace function articleFilter( keywordsAndLinks[key].keywords[i], keywordsAndLinks[key].link ); } } function cleanLinks() { // (making smal functions is for DRY) this function gets the links and only keeps the first 2 and from the rest removes the anchor tag and replaces it with its text function removeLinks(links) { if (links.length > 1) { for (let i = 2; i < links.length; i++) { links[i].outerHTML = links[i].textContent; } } } //arrays which will contain all the achor tags found with the class (ds-link, ml-link, ailink) in each article inserted using search and replace let dslinks; let mllinks; let ailinks; let nllinks; let deslinks; let tdlinks; let iaslinks; let llinks; let pbplinks; let mlclinks; const content = document.querySelectorAll('article'); //all articles content.forEach((c) => { //to skip the articles with specific ids if (!articleIdsToSkip.includes(c.id)) { //getting all the anchor tags in each article one by one dslinks = document.querySelectorAll(`#${c.id} .entry-content a.ds-link`); mllinks = document.querySelectorAll(`#${c.id} .entry-content a.ml-link`); ailinks = document.querySelectorAll(`#${c.id} .entry-content a.ai-link`); nllinks = document.querySelectorAll(`#${c.id} .entry-content a.ntrl-link`); deslinks = document.querySelectorAll(`#${c.id} .entry-content a.des-link`); tdlinks = document.querySelectorAll(`#${c.id} .entry-content a.td-link`); iaslinks = document.querySelectorAll(`#${c.id} .entry-content a.ias-link`); mlclinks = document.querySelectorAll(`#${c.id} .entry-content a.mlc-link`); llinks = document.querySelectorAll(`#${c.id} .entry-content a.l-link`); pbplinks = document.querySelectorAll(`#${c.id} .entry-content a.pbp-link`); //sending the anchor tags list of each article one by one to remove extra anchor tags removeLinks(dslinks); removeLinks(mllinks); removeLinks(ailinks); removeLinks(nllinks); removeLinks(deslinks); removeLinks(tdlinks); removeLinks(iaslinks); removeLinks(mlclinks); removeLinks(llinks); removeLinks(pbplinks); } }); } //To remove extra achor tags of each category (ds, ml, ai) and only have 2 of each category per article cleanLinks(); */ //Recommended Articles var ctaLinks = [ /* ' ' + '

Subscribe to our AI newsletter!

' + */ '

Take our 85+ lesson From Beginner to Advanced LLM Developer Certification: From choosing a project to deploying a working product this is the most comprehensive and practical LLM course out there!

'+ '

Towards AI has published Building LLMs for Production—our 470+ page guide to mastering LLMs with practical projects and expert insights!

' + '
' + '' + '' + '

Note: Content contains the views of the contributing authors and not Towards AI.
Disclosure: This website may contain sponsored content and affiliate links.

' + 'Discover Your Dream AI Career at Towards AI Jobs' + '

Towards AI has built a jobs board tailored specifically to Machine Learning and Data Science Jobs and Skills. Our software searches for live AI jobs each hour, labels and categorises them and makes them easily searchable. Explore over 10,000 live jobs today with Towards AI Jobs!

' + '
' + '

🔥 Recommended Articles 🔥

' + 'Why Become an LLM Developer? Launching Towards AI’s New One-Stop Conversion Course'+ 'Testing Launchpad.sh: A Container-based GPU Cloud for Inference and Fine-tuning'+ 'The Top 13 AI-Powered CRM Platforms
' + 'Top 11 AI Call Center Software for 2024
' + 'Learn Prompting 101—Prompt Engineering Course
' + 'Explore Leading Cloud Providers for GPU-Powered LLM Training
' + 'Best AI Communities for Artificial Intelligence Enthusiasts
' + 'Best Workstations for Deep Learning
' + 'Best Laptops for Deep Learning
' + 'Best Machine Learning Books
' + 'Machine Learning Algorithms
' + 'Neural Networks Tutorial
' + 'Best Public Datasets for Machine Learning
' + 'Neural Network Types
' + 'NLP Tutorial
' + 'Best Data Science Books
' + 'Monte Carlo Simulation Tutorial
' + 'Recommender System Tutorial
' + 'Linear Algebra for Deep Learning Tutorial
' + 'Google Colab Introduction
' + 'Decision Trees in Machine Learning
' + 'Principal Component Analysis (PCA) Tutorial
' + 'Linear Regression from Zero to Hero
'+ '

', /* + '

Join thousands of data leaders on the AI newsletter. It’s free, we don’t spam, and we never share your email address. Keep up to date with the latest work in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

',*/ ]; var replaceText = { '': '', '': '', '
': '
' + ctaLinks + '
', }; Object.keys(replaceText).forEach((txtorig) => { //txtorig is the key in replacetext object const txtnew = replaceText[txtorig]; //txtnew is the value of the key in replacetext object let entryFooter = document.querySelector('article .entry-footer'); if (document.querySelectorAll('.single-post').length > 0) { //console.log('Article found.'); const text = entryFooter.innerHTML; entryFooter.innerHTML = text.replace(txtorig, txtnew); } else { // console.log('Article not found.'); //removing comment 09/04/24 } }); var css = document.createElement('style'); css.type = 'text/css'; css.innerHTML = '.post-tags { display:none !important } .article-cta a { font-size: 18px; }'; document.body.appendChild(css); //Extra //This function adds some accessibility needs to the site. function addAlly() { // In this function JQuery is replaced with vanilla javascript functions const imgCont = document.querySelector('.uw-imgcont'); imgCont.setAttribute('aria-label', 'AI news, latest developments'); imgCont.title = 'AI news, latest developments'; imgCont.rel = 'noopener'; document.querySelector('.page-mobile-menu-logo a').title = 'Towards AI Home'; document.querySelector('a.social-link').rel = 'noopener'; document.querySelector('a.uw-text').rel = 'noopener'; document.querySelector('a.uw-w-branding').rel = 'noopener'; document.querySelector('.blog h2.heading').innerHTML = 'Publication'; const popupSearch = document.querySelector$('a.btn-open-popup-search'); popupSearch.setAttribute('role', 'button'); popupSearch.title = 'Search'; const searchClose = document.querySelector('a.popup-search-close'); searchClose.setAttribute('role', 'button'); searchClose.title = 'Close search page'; // document // .querySelector('a.btn-open-popup-search') // .setAttribute( // 'href', // 'https://medium.com/towards-artificial-intelligence/search' // ); } // Add external attributes to 302 sticky and editorial links function extLink() { // Sticky 302 links, this fuction opens the link we send to Medium on a new tab and adds a "noopener" rel to them var stickyLinks = document.querySelectorAll('.grid-item.sticky a'); for (var i = 0; i < stickyLinks.length; i++) { /* stickyLinks[i].setAttribute('target', '_blank'); stickyLinks[i].setAttribute('rel', 'noopener'); */ } // Editorial 302 links, same here var editLinks = document.querySelectorAll( '.grid-item.category-editorial a' ); for (var i = 0; i < editLinks.length; i++) { editLinks[i].setAttribute('target', '_blank'); editLinks[i].setAttribute('rel', 'noopener'); } } // Add current year to copyright notices document.getElementById( 'js-current-year' ).textContent = new Date().getFullYear(); // Call functions after page load extLink(); //addAlly(); setTimeout(function() { //addAlly(); //ideally we should only need to run it once ↑ }, 5000); }; function closeCookieDialog (){ document.getElementById("cookie-consent").style.display = "none"; return false; } setTimeout ( function () { closeCookieDialog(); }, 15000); console.log(`%c 🚀🚀🚀 ███ █████ ███████ █████████ ███████████ █████████████ ███████████████ ███████ ███████ ███████ ┌───────────────────────────────────────────────────────────────────┐ │ │ │ Towards AI is looking for contributors! │ │ Join us in creating awesome AI content. │ │ Let's build the future of AI together → │ │ https://towardsai.net/contribute │ │ │ └───────────────────────────────────────────────────────────────────┘ `, `background: ; color: #00adff; font-size: large`); //Remove latest category across site document.querySelectorAll('a[rel="category tag"]').forEach(function(el) { if (el.textContent.trim() === 'Latest') { // Remove the two consecutive spaces (  ) if (el.nextSibling && el.nextSibling.nodeValue.includes('\u00A0\u00A0')) { el.nextSibling.nodeValue = ''; // Remove the spaces } el.style.display = 'none'; // Hide the element } }); // Add cross-domain measurement, anonymize IPs 'use strict'; //var ga = gtag; ga('config', 'G-9D3HKKFV1Q', 'auto', { /*'allowLinker': true,*/ 'anonymize_ip': true/*, 'linker': { 'domains': [ 'medium.com/towards-artificial-intelligence', 'datasets.towardsai.net', 'rss.towardsai.net', 'feed.towardsai.net', 'contribute.towardsai.net', 'members.towardsai.net', 'pub.towardsai.net', 'news.towardsai.net' ] } */ }); ga('send', 'pageview'); -->