Python Lesson 38: Building Your First Neural Network (AI pt. 2)

Advertisements

Hello everybody,

Michael here, and in today’s post-my last post of 2022-I will be showing you how to create your first neural network in Python. I know you haven’t seen stuff like this on my blog before, but I thought I’d end the year teaching you all something new.

Now, there are two possible ways you can create a neural network in Python-one of which involves creating the framework for your neural network by scratch with a combination of classes and functions (which, if you readers want, I’ll cover how to do this). The other way involves using two of Python’s built-in packages-Keras and TensorFlow-which I will discuss more in this post.

A little bit about Keras and Tensorflow

Tensorflow and Keras are two prominent Python neural network machine learning packages. However, Tensorflow is an entire open-source end-to-end neural network package while Keras is more like an interface within Tensorflow. If it helps, think of Keras like a package-within-a-package in Tensorflow; whenever you use Keras, you’re actually using the Tensorflow library. However, Keras is a more intutive version of the Tensorflow libary, albeit with some trade-offs (such as the lack of ability to access more complex functionalities).

Package installation

Before we get started with our neural network creation, let’s first install our packages. You’re going to need both Tensorflow and Keras for this tutorial, but you only need to run the pip install tensorflow command on the command prompt, as installing Tensorflow will usually install Keras too. However, on the off chance that Keras doesn’t get installed with Tensorflow, you could run the pip install keras command on the command prompt.

  • Just in case you forgot, if you want to check if you’ve already pip-installed a certain package, run the pip list command and run through the list of installed packages to find the package you’re looking for (all packages are listed in alphabetical order).

Setting up the neural network

For this lesson, we’re going to start off by building a simple neural network-one that works with the MNIST Keras dataset. For those who don’t know, the MNIST (Modified National Institute of Standards and Technology) dataset is a very, very large dataset of images containing the handwritten digits 0-9-the MNIST dataset is commonly used for training image processing systems (or if you’re just starting out with neural network machine learning). This dataset contains 70,000 28×28 pixel images-60,000 images for the training dataset and 10,000 images for the testing dataset.

  • The MNIST dataset is certainly larger than most of the other datasets we’ve worked with in earlier posts (if you recall, the datasets from my earlier machine learning posts had about a few thousand elements tops). The reason for this is because, unlike the other machine learning I’ve taught you (k-means clustering, Naive Bayes classifications), neural networks are really well-suited for large datasets-and by large, I mean at least 10,000 records.

To start creating our neural network, first include these three lines of code in your Jupyter notebook:

import tensorflow as tf
import keras as kr
import tensorflow_datasets as tfds

Pay attention to the highlighted import line-in addition to the Tensorflow and Keras packages, you’ll also need the tensorflow_datasets package for this lesson. The tensorflow_datasets package contains several Tensorflow datasets you can work with when developing neural networks (such as the MNIST dataset, which we will be working with in this lesson).

  • If you haven’t installed the tensorflow_datasets package yet, run the line pip install tensorflow_datasets on your command prompt or run the line !pip install tensorflow_datasets on your Jupyter notebook (or whichever IDE you’re using).

Loading the MNIST dataset (and a word of advice)

Now that we’ve imported the necessary packages into our Python IDE, the next thing we need to do is import the MNIST dataset into our IDE. Here’s the code to do so:

from keras.datasets import mnist

Unlike most of my other machine learning/data analytics posts, I won’t be attaching a dataset to this post because we’ll be using a built-in Python dataset for this post. If you’re familiar with some popular data analytics/machine learning datasets such as titanic (detailing survivors and victims of the Titanic disaster), iris (detailing petal and sepal widths of a sample of 50 irises), and mtcars (detailing various features about a bunch of old cars), you’ve probably seen them on A LOT of data analytics/machine learning tutorials. There’s a good reason for that-they’re freely available and built-in datasets on several programs (Python and R to name just two).

For those who’ve been following my blog for a while, you’ll notice that I try to stay away from overly cliche datasets (I mean, if you’re a data science/data anayltics machine learning student, you’re probably quite sick of the iris dataset). However, even though MNIST is a very commonly used (and a little cliche) dataset, I think it will be the most appropriate first dataset to introduce you all to neural network creation.

Also, final word of advice for you all-if you’re trying to build a data science/data analytics/machine learning portfolio to land yourself a tech job (as I did when I launched this blog in summer 2018), try to stay away from cliche datasets. Find datasets that stand out (and ideally interest you)-you’ll be sure to impress the recruiters!

Now back to the lesson! After importing the MNIST dataset into your IDE, run this line of code to split the MNIST dataset into training and testing datasets:

(trainX, trainY), (testX, testY) = mnist.load_data()

When loading the MNIST dataset into your IDE (or any large dataset for that matter), remember to split your dataset into training and testing datasets, each denoted by their own variables.

  • I know it’s been a while since I’ve done any machine learning posts, so as a refresher, when building a machine learning model, the training dataset trains the model to work while the testing dataset is used to test if the model works as intended. When working with machine learning datasets, don’t split the main dataset 50-50 into training and testing datasets. The training dataset should be the larger dataset; a split like 70% training/30% testing should work fine-though the MNIST dataset has a split of ~85% training/~15% testing, which will work for this dataset.

Why do we need X and Y training and testing datasets? The X datasets encompass the whole dimensions of the training and testing datasets-the size (60,000 for training and 10,000 for testing) along with the dimensions of each image (28×28 pixels). The Y datasets on the other hand just encompass the sizes of each dataset.

In case you’re wondering about the size of each X and Y dataset, run the .shape command for each like so-remember not to include a pair of parentheses after each .shape command, as you can’t call tuple objects:

trainX.shape
(60000, 28, 28)

testX.shape
(10000, 28, 28)

trainY.shape
(60000,)

testY.shape
(10000,)

And now…time to build the model!

Now that we’ve loaded our MNIST dataset into Python, split the data into training and testing datasets, and obtained the shapes of each dataset, it’s time to get our feet wet and build our first neural network!

However, before we dive into the neural network nitty-gritty, there’s something I want to show you. Take a look at the code and output below:

import matplotlib.pyplot as plt
imageNum = 1500
plt.imshow(trainX[imageNum], cmap='magma')

In this example, I imported the matplotlib.pyplot package (which you may recall from my MATPLOTLIB lessons) to plot the 1501st image in the MNIST training dataset in MATPLOTLIB’s magma color scheme (the cmap parameter refers to MATPLOTLIB’s color schemes). As you can see, this image of a handwritten 9 is displayed as a 28×28 pixel image-which makes sense, as all images in the MNIST dataset (both training and testing) have a 28×28 pixel size.

  • MATPLOTLIB has several different color schemes to choose from. For a list of all available color scheme choices, check out this link-https://matplotlib.org/stable/tutorials/colors/colormaps.html.
  • In order to plot any of the images in the MNIST dataset, you’ll need to use either of the X datasets (in this example, trainX and testX) since they encompass the image sizes and in turn, contain the actual images. The Y datasets simply encompass the images themselves, so you would be able to retrieve any element from the MNIST dataset from either of the Y datasets, but you won’t be able to plot the image itself.
  • Just like many of the other Python projects I’ve done throughout this blog involving lists, the MNIST dataset is basically a giant zero-indexed list of images. So for a parameter like imageNum, you can choose any value between 0 and 59,999 if you’re analyzing the 60,000 image training dataset. If you’re analyzing the 10,000 image testing dataset, you can choose any value between 0 and 9,999. In the example above, I chose the 1,501st image in the testing dataset (as the imageNum I chose was 1,500, which represents the element at index 1,500).

Just for fun, let’s also plot a random image from the testing dataset:

import matplotlib.pyplot as plt
imageNum = 3332
plt.imshow(testX[imageNum], cmap='magma')

In this example, I did the same thing as I did in the previous example, except I decided to plot the 3,333rd image from the MNIST testing dataset-which happens to be the number 4.

Now that we know how to plot each element in the MNIST dataset (for both the testing and training datasets) it’s time to create our model! Take a look at the code below to see how we can create our first Python neural network model:

firstNeuralNetwork = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28,28)),
    tf.keras.layers.Dense(150, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10)
])

Now, if you’ve never seen a Python neural network before, you’re probably wondering what all of this code means. But don’t worry-your friendly neighborhood coding blogger is here to break it all down for you!

First off, let’s start with the Sequential sub-module. We use this sub-module in order to create the outer part of the neural network; in this sub-module, we wrap all the functions for the neural network inside of a list wrapped inside of the Sequential object constructor (referrring to the pair of parentheses that enclose the list). Why do we need a sequential model for the neural network? In this example, using a sequential model for the neural network allows us to add the other four layers in this neural network-Flatten, Dense, Dropout, and Dense-in sequential order, which is important for neural networks.

Now what about the four layers wrapped in our sequential model-Flatten, Dropout and the two Dense layers? The Flatten layer, well, flattens the input from 2-dimensional to 1-dimensional-which is important as we’re dealing with thousands of 2-D images for this dataset. How does Flatten flatten the input data? The Flatten layer’s input_shape parameter takes in the dimensions of the object to flatten-in this case each 28×28 image in the MNIST dataset-and takes in the (28, 28) tuple as the value of the input_shape argument.

The Dropout layer removes some of the data from the model in order to prevent overfitting. In the context of machine learning, what is overfitting? Overfitting in machine learning is what happens when your model has excellent accuracy with training data but not with new and unfamiliar data.

Let me give you an example. Let’s say you want to create a model that predicts whether an employee at a very, very, very large company is going to get a promotion based off of their resume. Let’s also assume that you train a model containing 5,000 resumes and it predicts outcomes with 96% accuracy-pretty awesome, right! Now let’s say you feed the model a new set of 2,500 resumes and it predicts outcomes with only a 44% accuracy-what happened here? The model experienced overfitting, as it was able to predict outcomes with great accuracy for the training dataset but with less-than-stellar accuracy for the new and unfamiliar dataset.

In our neural network, the Dropout layer will ignore 10% of the data in the training dataset to avoid overfitting.

Last but not least, we have two Dense layers for our neural network. The first Dense layer activates the neural network using the ReLU, or rectified linear unit activation, function. For more on the algebra behind ReLU, check out this article-https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/ (if you’re into linear algebra and/or trigonometry, I think you’ll enjoy this article). In the most basic sense, ReLU is a linear activation function that is used in a lot of neural networks due to its easy-to-train and well-performance.

In the first Dense layer, you’ll notice a number right before the activation parameter-that number indicates how many neurons you want to have in the neural network upon activation; in this case, we have 150 neurons upon activation of our neural network. The second Dense layer also has a number too-10. What’s the difference between these two numbers? In the first Dense layer, you can have as many neurons as you’d like upon activation while in the second Dense layer, you must have 10 neurons as there are ten unique objects for classifcation (images of the numbers 0-9).

Fitting and Compiling the Model

The last two things we need to do before we deploy our model are to fit it and compile it. How can we do that? Take a look at the code below:

firstNeuralNetwork.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
firstNeuralNetwork.fit(x=trainX,y=trainY, epochs=25)

So, what does all of this code mean? First of all, the optimizer parameter and value set the neural network’s optimization alogrithm-in this case, we’re using Tensorflow’s adam optimizer (for a more in-depth explination on that optimizer, check out this link-https://www.educba.com/tensorflow-adam-optimizer/), though you can experiement with whatever Tensorflow optimizer you like.

The loss parameter and corresponding value set the neural network’s loss function, which is used to help optimize the model’s performance by measuring the discrepancies between the predicted values and the target values. In the context of the MNIST dataset, each element would be considered a target value and the value that the neural network predicts as part of its classification would be the target value. In this example, we’re using the sparse_categorical_crossentropy loss function, which measures the cross-entropy (or contrast or discrepancy) between the predicted values and the actual values.

The metrics parameter and corresponding value (or list in this case) set the metrics-or in this case, metric-that you’d like to use to measure the neural network’s accuracy. In this example, we’re going with the accuracy metric, as this is the easiest metric to understand. Accuracy is also often used as a baseline for other metrics such as precision and f1 score (which is similar to accuracy but it takes false positives and false negatives into account).

In the fit function, you’ll first need to pass in your training datasets for both the X and Y values. As for the epoch parameter and value, an epoch is essentially an iteration through all the training data that isn’t ignored by the Dropout layer. To train a neural network and optimize it for accuracy, iterating through all of the training data once won’t suffice-you’ll need at least 10 iterations through the training data to optimize your neural network (though more epochs couldn’t hurt). In this neural network, we’re using 25 epochs, meaning that we will iterate through the training data 25 times.

Now, let’s see how our neural network performs through each epoch (or iteration):

Epoch 1/25
1875/1875 [==============================] - 5s 2ms/step - loss: 2.3026 - accuracy: 0.1118
Epoch 2/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3028 - accuracy: 0.1137
Epoch 3/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1118
Epoch 4/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3032 - accuracy: 0.1124
Epoch 5/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1114
Epoch 6/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3032 - accuracy: 0.1118
Epoch 7/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1100
Epoch 8/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1125
Epoch 9/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3028 - accuracy: 0.1114
Epoch 10/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3027 - accuracy: 0.1107
Epoch 11/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3028 - accuracy: 0.1129
Epoch 12/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3026 - accuracy: 0.1113
Epoch 13/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3028 - accuracy: 0.1135
Epoch 14/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3032 - accuracy: 0.1124
Epoch 15/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1133
Epoch 16/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3026 - accuracy: 0.1121
Epoch 17/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1124
Epoch 18/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1133
Epoch 19/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1120
Epoch 20/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3028 - accuracy: 0.1134
Epoch 21/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3026 - accuracy: 0.1141
Epoch 22/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3026 - accuracy: 0.1129
Epoch 23/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1126
Epoch 24/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3030 - accuracy: 0.1127
Epoch 25/25
1875/1875 [==============================] - 4s 2ms/step - loss: 2.3037 - accuracy: 0.1117

In this epoch run log, we can see several different metrics for each epoch, such as loss and accuracy. However, the only metric you should focus on is each epoch’s accuracy, as that tells you the accuracy of the neural network throughout each training run. For instance, the first epoch (denoted as Epoch 1/25) had an accuracy of 11.18%. The final epoch (denoted as Epoch 25/25) had an accuracy of 11.17%-all in all, pretty abysmal accruacy for the neural network.

Neural network evaluation time!

Last but not least, it’s neural network evaluation time! To evaluate the accuracy of the overall model (as opposed to individual epochs), all you need is one line of code:

firstNeuralNetwork.evaluate(testX, testY)

313/313 [==============================] - 1s 1ms/step - loss: 2.3026 - accuracy: 0.1045

Just like you saw with the epochs, you’ll see the loss and accuracy metrics. Pay close attention to the accuracy metric, as this will tell you the model’s overall accuracy, which is still pretty bad at 10.45%.

  • I know this may seem confusing, but remember when you’re fitting & compiling the model to use the training dataset (for both the X and Y axes). When you’re evaluating the model’s accuracy, use the testing dataset (for both the X and Y axes).

Yes, I know the accuracy of this neural network sucked. However, the aim of this lesson was not to build the best neural network out there-rather, my aim was to teach you the basics of neural network creation so that you all knew the basic concepts of neural networks. A lot of the concepts we discussed in this post-activation algorithms, epochs, dropout rate-can be experimented with to your liking in order to optimize the neural network’s accuracy.

Final code and some parting words for 2022

So, I know we had A LOT of code for this lesson. In case you wanted to run the code in the order we discussed it, here’s the entire script below for your convinience (outputs not included):

import tensorflow as tf
import keras as kr
import tensorflow_datasets as tfds

(trainX, trainY), (testX, testY) = mnist.load_data()

trainX.shape
testX.shape
trainY.shape
testY.shape

import matplotlib.pyplot as plt
imageNum = 1500
plt.imshow(trainX[imageNum], cmap='magma')

import matplotlib.pyplot as plt
imageNum = 3332
plt.imshow(testX[imageNum], cmap='magma')

firstNeuralNetwork = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28,28)),
    tf.keras.layers.Dense(150, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10)
])

firstNeuralNetwork.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
firstNeuralNetwork.fit(x=trainX,y=trainY, epochs=25)

firstNeuralNetwork.evaluate(testX, testY)

Thanks for coming along on this coding journey in 2022! Hope you all sharpened your skills and/or learned something new along the way this year! Have a very happy holiday season and rest assured-I will be back in 2023 with brand new coding content (and a little something special for my blog’s 5th anniversary)!

Michael

Python Lesson 37: Intro to Neural Networks (AI pt. 1)

Advertisements

Hello everybody,

Michael here, and for today’s post, I’ll discuss something a little different-neural networks; this is the first post of my new AI (artificial intelligence) series. Granted, I’ll be using Python, which I’ve used quite a bit in this blog (this is my 37th Python lesson after all).

More specifically, in today’s post, I will be discussing the basics of neural networks and how to set up a simple neural network in Python. And in case you’re wondering (and/or really enjoy AI content), the remainder of my 2022 blog posts AND my first few 2023 posts will cover neural networks.

But first, a little bit about machine learning…

For those of you who’ve been following my blog for quite a while, you may recall that a lot of my earlier entries covered machine learning.

But what is machine learning exactly? It’s essentially a process where you are training a program to do something (like identifying a certain plant from a photo)-or in better terms, training a machine to learn something (hence the term machine learning). One of my early posts from February 2019-R Lesson 10: Intro to Machine Learning-Supervised and Unsupervised-does a good job of explaining some of the basics of machine learning. Granted, I wrote this post as part of a series of R lessons, but the gist of the post can be applied to any programming/automation tool.

Now onto neural networks

What is a neural network (in the context of programming)? To help explain this concept, think of the way all of the neurons in your brain process information. Neural networks operate in a similar manner, as they are meant to process information via a computer program that’s meant to mimic the way our brains process information.

Neural networks are a form of machine learning, and just like machine learning, you can utilize supervised and unsupervised machine learning with neural networks. Unsupervised machine learning with neural networks actually has a name of its own-deep learning, which is a process you use to allow the neural network to train itself rather than coding in any guidance for the neural network’s operation.

A neural network you’ve likely come across

A neural network you’ve most likely seen or heard of before is deepfakes. If you’ve ever seen a video where it appears someone’s face looks stitched onto someone else’s body-that’s deepfake AI at work.

A great example of deepfake AI at work was seen on season 17 (2022) of America’s Got Talenthttps://www.youtube.com/watch?v=Jr8yEgu7sHU&t=116s. The act in the linked video-Metaphysic-utilized deepfake AI to make it appear as if the king of rock’n’roll Elvis and judges Sofia Vergara and Heidi Klum were singing Elvis’s greatest hits. Take a closer look at the video, and you realize that “Elvis”, “Sofia”, and “Heidi” are being animated by three singers in real-time standing in front of projectors. Pretty neat stuff, right? Plus, Metaphysic finished the season in 4th place-not too shabby for AGT’s first deepfake/metaverse AI act.

Another brilliant, albeit controversial, example of deepfake AI at work can be found in Kendrick Lamar’s 2022 music video for The Heart Part 5https://www.youtube.com/watch?v=uAPUkgeiFVY (highly recommend listening to Mr. Morale & the Big Steppers). In this video, Kendrick Lamar uses deepfake AI to transform himself into six notable celebrities-OJ Simpson, Kanye West, Jussie Smollett, Will Smith, Kobe Bryant, and Nipsey Hussle-while rapping six different verses from the perspectives of these individuals.

Did I cover neural networks before?

Did I ever explicitly cover neural networks before? No.

However, several past posts did cover machine learning-both supervised and unsupervised. Here are a few of those posts:

Thanks for reading,

Michael

Bootstrap Lesson 5: Basic Bootstrap Helper Classes

Advertisements

Hello everybody,

Michael here, and today’s lesson is all about basic helper classes in Bootstrap. Well, in my previous lesson Bootstrap Lesson 4: Jumbotrons and Image Carousels I briefly mentioned Bootstrap helper classes when creating Jumbotrons. In this post, I want to spend some time explaining how the helper classes I mentioned in my previous post work.

What are Bootstrap helper classes exactly? Well, they’re the special classes in Bootstrap that allow you to set features such as color and padding, among other things. To better explain Bootstrap helper classes, I’ll use my examples from my previous post (the post linked above).

Padding and margin classes

Let’s start off by exploring Bootstrap padding classes. But before we do that, let’s take a look at this code from my previous post used to create a basic Bootstrap Jumbotron:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-black">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll</p>
    </div>
  </body>
</head>

Pay attention to the p-5 line. The p-5 line-or rather, any line that begins with a p, denotes padding for an element (in this example, the Jumbotron)-the p helper class allows you to change the element’s padding.

Bootstrap also has an m helper class, which allows you to change the element’s margins.

  • In case you forgot the difference between padding and margins, padding is the space between an element’s border (whether visible or not) and the element’s content-like this Jumbotron’s border and it’s content. On the other hands, margins are the space around an element’s border-like the space between the Jumbotron’s border(s) and the edge(s) of the webpage.

Now, two important things to know about padding and margin classes are the ability to set the size and locations of the padding and margins.

Bootstrap has seven options to set the location of the padding and margins:

  • t-set the margin or padding to the top side of the element
  • b-set the margin or padding to the bottom side of the element
  • l-set the margin or padding to the left side of the element
  • r-set the margin or padding to the right side of the element
  • x-set the margin or padding to both the left and right sides of the element
  • y-set the margin or padding to both the top and bottom sides of the element
  • blank-set the margin or padding to all four sides of the element

Bootstrap also has seven options to set the size of the padding and margins:

  • 0-include no margins or padding
  • 1-set the margins or padding of the element to 0.25 pixels (by default)
  • 2-set the margins or padding of the element to 0.5 pixels (by default)
  • 3-set the margins or padding of the element to 1 pixel (by default)
  • 4-set the margins or padding of the element to 1.5 pixels (by default)
  • 5-set the margins or padding of the element to 3 pixels (by default)
  • auto-auto-sets the padding of any element (only used if the element’s margins are set to auto)

To set the location and sizing of an element’s margins or padding, follow this syntax: [m/p][location]-[sizing]. The m or p will always come first to indicate whether you want to add margins or padding to the element, then the location of the margins/padding will be listed. If you want to specify a sizing for your margins/padding (other than the default sizing), the sizing of the margins/padding will be listed after the hyphen.

Pay attention to the lines mt-4 and p-5 from the above example. The line mt-4 sets the Jumbotron’s top margins to “4” (1.5 pixels). The line p-5 set’s the Jumbotron’s padding to “5” (3 pixels). Notice how there isn’t another letter in the p-5 line; because of this, the padding is set to 3 pixels across all corners of the element rather than just a single corner.

Background classes

Next, we’ll explore Bootstrap background helper classes, which are denoted with bg (for instance, bg-light in the above example).

The Bootstrap background helper classes serve as contextual classes that help give your background some more meaning. There are ELEVEN possible Bootstrap background helper classes, which include:

  • bg-primary-turns your background dark blue
  • bg-secondary-turns your background grey
  • bg-success-turns your background green
  • bg-danger-turns your background red
  • bg-warning-turns your background yellow
  • bg-info-turns your background light blue
  • bg-light-turns your background light grey
  • bg-dark-turns your background dark
  • bg-body and bg-white-turns your background white
  • bg-transparent-makes your background transparent

In the previous example, I used the bg-light helper class to give my Jumbotron a light background. Now, just for the heck of it, let’s see what the Jumbotron background would look like with a different style (pay attention to the highlighted line of code):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-info text-black">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll</p>
    </div>
  </body>
</head>

In order to give my Jumbotron the light blue color, all I did was change the bg class from bg-light to bg-info. Pretty neat stuff right?

Here’s another example of Bootstrap background helper classes in action, taken from my post Bootstrap Lesson 2: Typography and Tables:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

</head>
<body>

<div class="container">
  <h1>2021 AFC Standings</h1>
  <table class="table">
    <thead>
      <tr>
        <th>Team</th>
        <th>Record</th>
        <th>Seeding</th>
      </tr>
    </thead>
    <tbody>
      <tr class="success">
        <td>Tennessee Titans</td>
        <td>12-5</td>
        <td>1</td>
      </tr>
      <tr class="success">
        <td>Kansas City Chiefs</td>
        <td>12-5</td>
        <td>2</td>
      </tr>
      <tr class="success">
        <td>Buffalo Bills</td>
        <td>11-6</td>
        <td>3</td>
      </tr>
      <tr class="success">
        <td>Cincinnati Bengals</td>
        <td>10-7</td>
        <td>4</td>
      </tr>
      <tr class="warning">
        <td>Las Vegas Raider</td>
        <td>10-7</td>
        <td>5</td>
      </tr>
      <tr class="warning">
        <td>New England Patriots</td>
        <td>10-7</td>
        <td>6</td>
      </tr>
      <tr class="warning">
        <td>Pittsburgh Steelers</td>
        <td>9-7-1</td>
        <td>7</td>
      </tr>
      <tr class="danger">
        <td>Indianapolis Colts</td>
        <td>9-8</td>
        <td>8</td>
      </tr>
      <tr class="danger">
        <td>Miami Dolphins</td>
        <td>9-8</td>
        <td>9</td>
      </tr>
      <tr class="danger">
        <td>Los Angeles Chargers</td>
        <td>9-8</td>
        <td>10</td>
      </tr>
      <tr class="danger">
        <td>Cleveland Browns</td>
        <td>8-9</td>
        <td>11</td>
      </tr>
      <tr class="danger">
        <td>Baltimore Ravens</td>
        <td>8-9</td>
        <td>12</td>
      </tr>
      <tr class="danger">
        <td>Denver Broncos</td>
        <td>7-10</td>
        <td>13</td>
      </tr>
      <tr class="danger">
        <td>New York Jets</td>
        <td>4-13</td>
        <td>14</td>
      </tr>
      <tr class="danger">
        <td>Houston Texans</td>
        <td>4-13</td>
        <td>15</td>
      </tr>
      <tr class="danger">
        <td>Jacksonville Jaguars</td>
        <td>3-14</td>
        <td>16</td>
      </tr>
    </tbody>
  </table>
</div>

</body>
</html>

In this example, I used three Bootstrap background helper classes (success, warning, and danger) to color in each row according to each AFC team’s playoff standings in 2021 (division clinched, wildcard, did not qualify for playoffs). Granted, I didn’t explicitly use the bg-success, bg-danger, and bg-warning background classes, but the idea is still the same-to color in the table rows according to a certain context.

Text helper classes

Last but not least, I want to explain text helper classes (such as the one you’ll see in the line text-black).

In the Jumbotron example, I used the line text-black to set the color of the Jumbotron text to black. Seems pretty self-explanatory, right? Well, the text helper classes-unlike the padding, margin, and background helper classes-are quite versatile, as there are several ways to modify Bootstrap text.

  • If you want to change the color of text using Bootstrap helper classes, you can only do so by writing the name of the color (so no HEX/RGB/other colorscale codes here)

Text alignment

The first such way to modify Bootstrap text-aside from changing the color-is by changing the text’s alignment. Let’s see how that would work with the Jumbotron from the previous post (pay attention to the highlighted line of code):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll</p>
    </div>
  </body>
</head>

First of all, you’ll noticed I changed the Jumbotron’s background class back to bg-light, but that isn’t too important here.

What is important here is how I changed the alignment of the text-in this case, I center-aligned all text in the Jumbotron. All I had to do was add the line text-center to center the text.

  • In case you’re wondering how to center-align the text and keep its black color, you’ll need to add text-center and text-black as separate lines. Trying something like text-center-black or text-black-center won’t work-while these lines won’t give you any errors, the text won’t be centered in your Jumbotron.

There are two other ways to align your text in Bootstrap-text-start and text-end, which will left-align and right-align your text, respectively.

Text wrapping

Next, let’s explore how to utilize text wrapping in Bootstrap. First off, let’s see an example of text wrapping in the Jumbotron (pay attention to the highlighted line of code):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black text-wrap">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll. These are pretty awesome photos if you ask me. Just take a look at all the amazing scenery I managed to capture. Y'all should take a look. You won't believe what picture 3 looks like. I swear!</p>
</head>

To show you how text-wrapping works in Bootstrap, I added a bunch of rambling text to the <p> tag of the Jumbotron to ensure it was long enough to wrap. To wrap the text, I simply added the line text-wrap to the Jumbotron’s <div class-="..."> tag.

If you didn’t want the text-wrapping in the Jumbotron, replace the text-wrap class with the text-nowrap class. Here’s what the Jumbotron would look like with no text-wrapping:

Interestingly, Bootstrap doesn’t try to squeeze all the text into the Jumbotron. Rather, the text spills outside the Jumbtron, so you’ll need to scroll across the window to read the entire document. Pretty user-unfriendly, amirite?

Text transformation

Next up, let’s explore text transformation in Bootstrap. But first, a little demo (pay attention to the highlighted line of code):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black text-wrap text-capitalize">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll. These are pretty awesome photos if you ask me. Just take a look at all the amazing scenery I managed to capture. Y'all should take a look. You won't believe what picture 3 looks like. I swear!</p>
</head>

In this example, I used the line text-capitalize to capitalize the text. However, text-capitalize doesn’t do what you think it might do-capitalize the entire text. Rather, text-capitalize only captializes the first letter of each word in the Jumbotron and leaves all other letters lowercase.

If you’re looking to capitalize the entire text, replace text-capitalize with text-uppercase. Similarly, if you’re looking to lowercase the entire text, replace text-capitalize with text-lowercase.

Font sizes

The next way you can modify your text in Bootstrap is through modifying font sizes. Before we discuss this, here’s a little demo for y’all (pay attention to the highlighted line of code):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black text-wrap text-capitalize fs-1">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll. These are pretty awesome photos if you ask me. Just take a look at all the amazing scenery I managed to capture. Y'all should take a look. You won't believe what picture 3 looks like. I swear!</p>
</head>

Unlike most of the other text modifications we’ve discussed, the text modification for font looks a little different since it uses the fs (font size) helper class-and yet, it still works to change the text’s font size.

In this example, I used the fs-1 helper class to change the Jumbotron text’s font size and as you can see, the fs-1 helper class makes the text quite large! Why might that be?

Well, there are six possible values for the fs helper classes-ranging from 1 to 6. fs-1 creates the largest text, while fs-6 creates the smallest text. Does this concept sound familiar to you? If so, it’s because HTML headers also have six possible values-ranging from 1 to 6, with 1 creating the largest header and 6 creating the smallest header.

Font effects

Now that we’ve dicsussed modifying the font size, let’s turn our attention to font effects in Bootstrap-things like boldening and italicizing the text. Take a look at the example Jumbotron code below (and pay attention to the highlighted text):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black fw-bold">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll. These are pretty awesome photos if you ask me. Just take a look at all the amazing scenery I managed to capture. Y'all should take a look. You won't believe what picture 3 looks like. I swear!</p>
</head>

In this example, I made all of the text on the Jumbotron bold with the line fw-bold (granted, that doesn’t seem to affect the <h1> tag’s appearance all that much). Simple, but pretty neat right?

Some other text effects you could use on your Bootstrap text include:

  • fw-normal-no text effect (this seems quite redunant to include if you ask me)
  • fw-light-light text
  • fst-italic-italicized text
  • fst-normal-normal font style text (also quite redunant, but Bootstrap includes it anyway)
  • fw-bolder-this will make the text bolder than its parent element
  • fw-lighter-this will make the text lighter than its parent element

As you can see, we’ve got several different text effects to use with Bootstrap text. As you can also see, there are TWO different helper classes for text effects-fw (font weight) and fst (font styling). The fact that text effects have two different helper classes is unique, as all of the other text modifications we’ve discussed and will discuss only have one helper class.

Line spacings

Next up, we’ll discuss line spacings in text. But first, a little demo with our Jumbotron (which you should be quite familiar with by now, and as always, pay attention to the highlighted line of code):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black lh-lg">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll. These are pretty awesome photos if you ask me. Just take a look at all the amazing scenery I managed to capture. Y'all should take a look. You won't believe what picture 3 looks like. I swear!</p>
</head>

Just like the font size modification I previously discussed, the line spacing modifications don’t use the text helper class. Rather, the line spacing modifications use the lh (line height) helper class-as you can see from the above example, I use lh-lg to change the line spacing in my Jumbotron.

There are three other options to change the line spacing in Bootstrap text-lh-1 (which gives the smallest line spacing), lh-sm (which gives slightly bigger line spacing), and lh-base (which gives the default line spacing). lh-lg gives you the largest possible line spacing in Bootstrap.

Underline and strokethrough

Last but not least, let’s discuss how to add underlines and strokethrough effects to your Bootstrap text. Here are two demos on how to do just that, first with the underline effect (pay attention to the highlighted line of code):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black lh-lg text-decoration-underline">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll. These are pretty awesome photos if you ask me. Just take a look at all the amazing scenery I managed to capture. Y'all should take a look. You won't believe what picture 3 looks like. I swear!</p>
</head>

Now here’s what the same Jumbotron text would look like with a strokethrough effect:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-center text-black lh-lg text-decoration-line-through">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll. These are pretty awesome photos if you ask me. Just take a look at all the amazing scenery I managed to capture. Y'all should take a look. You won't believe what picture 3 looks like. I swear!</p>
</head>

In both examples, I use the text-decoration helper class to add some text decoration effects to the Jumbotron text. In this case, I added an underline effect with the line text-decoration-underline and added a strokethrough effect with the line text-decoration-line-through.

There’s also a third text decoration effect within the text-decoration helper class-text-decoration-none. However, this will only work with hyperlinks, as the text-decoration-none effect will only remove all text decorations within hyperlinks, so if you tried to use this effect on something like the Jumbotron from the above example, it won’t work.

Thanks for reading,

Michael

Bootstrap Lesson 4: Jumbotrons and Image Carousels

Advertisements

Hello everybody,

Michael here, and it looks like we’ve got quite a lesson today-we’ll be covering Jumbrotrons and carousels in Bootstrap!

Now, let’s begin with some Bootstrap Jumbotrons!

Bootstrap Jumbotrons

What is a Bootstrap Jumbotron? If you answer anything like a Jumbotron you’d see in sporting arenas, you are sort of right. While Bootstrap Jumbotrons aren’t as gigantic as their sporting arena counterparts, the general idea of both Jumbotrons is the same-to emphasize and call attention to specific content (whether it be a cheering crowd or webpage content).

Now, here’s a little quirk about Bootstrap Jumbotrons-there’s no longer a special class to create them in Bootstrap. See, Jumbotrons were introduced in Bootstrap 3-with their own Bootstrap class-as big padded boxes used to call attention to special webpage content. However, the Jumbotron class was phased out by Bootstrap 5 BUT even with that being said, you can still create Jumbotrons in Bootstrap through a clever combination of <div> tags and special Bootstrap classes. Let’s take a look at the code below to see how we can replicate a Jumbotron in Bootstrap 5:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-black">
      <h1>Michael's photos</h1>
      <p>Photos of me from my phone's camera roll</p>
    </div>
  </body>
</head>
  • The line mt-4 p-5 bg-primary text-white rounded is made up of a combination of several different Bootstrap helper classes, which I’ll cover in future Bootstrap posts.

As you can see, using several Bootstrap helper classes (along with an <h1> and <p> tag), I managed to replicate a Bootstrap Jumbotron. Pretty simple stuff right?

Now that Jumbotrons have been covered, let’s move on to our next topic for today-Bootstrap carousels.

Carousels

No, we’re not going to ride the state fair’s merry-go-round here today (though wouldn’t that be fun). Rather, we’re going to discuss the image carousel, which is a feature used in webpage design that serves as a slideshow (or “carousel”) of images.

How would we implement the carousel in Bootstrap? Pay attention to the highlighted section of code below:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <div class="mt-4 p-5 bg-light text-black">
      <h1>Michael's park photos</h1>
      <p>My favorite parks</p>
    </div>

<div id="demo" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-indicators">
    <button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active"></button>
    <button type="button" data-bs-target="#demo" data-bs-slide-to="1"></button>
    <button type="button" data-bs-target="#demo" data-bs-slide-to="2"></button>
<button type="button" data-bs-target="#demo" data-bs-slide-to="3"></button>
  </div>


  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="bicentennial.jpg" alt="Bicentennial Capitol Mall State Park" class="d-block w-100">
    </div>
    <div class="carousel-item">
      <img src="stafford.jpg" alt="Stafford Park" class="d-block w-100">
    </div>
    <div class="carousel-item">
      <img src="sevier.jpg" alt="Sevier Park" class="d-block w-100">
    </div>
    <div class="carousel-item">
      <img src="veterans.jpg" alt="Veterans Park" class="d-block w-100">
    </div>
  </div>

  <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev">
    <span class="carousel-control-prev-icon"></span>
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next">
    <span class="carousel-control-next-icon"></span>
  </button>
</div>
  </body>
</head>
  • Yes, I did change the Jumbotron message from the previous example, but that’s irrelevant here.

The carousel elements, explained

So, how was I able to create the carousel? First, pay attention to the <div id="demo" class="carousel slide" data-bs-ride="carousel"> line. This line creates the carousel by using the Bootstrap class carousel slide and initializes the carousel with the data-bs-ride="carousel" line; the purpose of including this line is to include the ability to jump from image to image in the carousel.

The four following lines of code create buttons that allow you to jump from image to image on the carousel. Pay attention to this chunk of code-data-bs-slide-to="0", as it’s repeated four times-one for each of the four images I’ve included in this carousel. The only difference in the four instances of this line is that “0” is replaced with “1”, “2”, and “3”, which allow you to naviagate to the second, third, and fourth images in the carousel, respectively. Also, in the line of code to create the first button (the line that contains data-bs-slide-to="0"), you’ll also see a chunk of code that says class="active"-this indicates the carousel’s default image (in other words, the first image you’ll see on the carousel when you open the webpage).

  • Why is the value of the first data-bs-slide-to set to 0 while the value of the last data-bs-slide-to set to 3, even though there are four images in the carousel? This is because, when building a Bootstrap carousel, 0 refers to the first image-thus, 3 would refer to the fourth image. Zero-indexing system at work, much like in Python!

After adding the buttons, you’ll need to add another div class-carousel-inner. This is the fun part of the carousel, as this section of code actually adds your images to the carousel. All images except for the default image must have the class carousel-item, though the default image must have the class carousel-item active; this way, Bootstrap knows which image to display upon a user’s arrival to the webpage.

As for the image source (or src), if you have your images in the same directory as your HTML/CSS code, all you need to do to include the image onto the carousel is write src="[image name].[image extension]". If your images are in a different directory than your HTML/CSS code, you’ll need to include the image’s whole file path in the src parameter.

After including the images, the last thing you’ll need to add to the carousel are the Back and Next buttons, which can be accomplished with the carousel-control-prev and carousel-control-next classes and their corresponding <span> tags. Why do each of these classes need their own <span> tags? All the carousel-control-prev and carousel-control-next classes do is add the functionality to go back and forth in the carousel. However, simply having the functionality to go back and forth isn’t enough on its own-after all, how can you expect the user to navigate back and forth in the carousel if they don’t want to use the tiny rectangular buttons on the bottom of the carousel? That’s where the <span> tags come in, as they link to the aforementioned functionalities to display two icons on the center-left and center-right hand sides of the carousel to allow the user to easily navigate back and forth through the carousel.

  • Honestly, you only need either the small rectangluar buttons or the Back and Next buttons in the carousel-you don’t absolutely need to include both elements. The only reason I did so is to teach you guys the basics of developing a Bootstrap carousel. Also, keep in mind that the differences between the small rectangular buttons and the Back/Next buttons is that the former option will allow you to jump all across the carousel (which can certainly help if you’ve got lots of images) while the latter option will only allow you to naviagate through the carousel one image at a time.

Re-sizing the carousel

Now, as you may have noticed from running the code, the carousel is looking a little big on the display. Let’s fix the sizing and fit the carousel to the screen with a little CSS magic:

html,body{
   height:100%;
}
.carousel,.item,.active{
   height:100%;
 }
.carousel-inner{
    height:100%;
}
  • By the way, this screen shot above is zoomed in at 100%.
  • Remember to save your CSS code in a CSS file and link it to your HTML/Bootstrap code-it would also be ideal to give your CSS file the same name as your corresponding HTML file.

Why would we need to set the height of all carousel elements (along with the larger HTML and body elements) to 100%? Doing so will ensure that all carousel elements fit within the entire screen without cutting off portions of the carousel.

Now, even though I said the carousel can now fit to screen once this CSS code has been added, you’ll notice that the CSS carousel doesn’t quite fit to screen. How do we fix this? Remove the Jumbotron!

Code to remove:

<div class="mt-4 p-5 bg-light text-black">
      <h1>Michael's park photos</h1>
      <p>My favorite parks</p>
</div> 

Now the carousel fits within the screen 100% with no need for scrolling!

Carousel captions

Last but not least, let’s discuss how to add captions to the carousel. Honestly, the carousel looks great so far, but what would really improve it (and in turn, improve the user experience) are captions for each image to give the user an idea of what they’re looking at.

How would we add captions to the carousel? Take a look at the highlighted sections of code below:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="BootstrapSite.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <!-- <div class="mt-4 p-5 bg-light text-black">
      <h1>Michael's park photos</h1>
      <p>My favorite parks</p>
    </div> -->


<div id="demo" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-indicators">
    <button type="button" data-bs-target="#demo" data-bs-slide-to="0" class="active"></button>
    <button type="button" data-bs-target="#demo" data-bs-slide-to="1"></button>
    <button type="button" data-bs-target="#demo" data-bs-slide-to="2"></button>
    <button type="button" data-bs-target="#demo" data-bs-slide-to="3"></button>
  </div>


  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="bicentennial.jpg" alt="Bicentennial Capitol Mall State Park" class="d-block w-100">
      <div class="carousel-caption">
        <h2>Bicentennial Capitol Mall State Park</h2>
        <p>Nashville, TN</p>
      </div>
    </div>
    <div class="carousel-item">
      <img src="stafford.jpg" alt="Stafford Park" class="d-block w-100">
      <div class="carousel-caption">
        <h2>Stafford Park</h2>
        <p>Miami Springs, FL</p>
      </div>
    </div>
    <div class="carousel-item">
      <img src="sevier.jpg" alt="Sevier Park" class="d-block w-100">
      <div class="carousel-caption">
        <h2>Sevier Park</h2>
        <p>Nashville, TN</p>
      </div>
    </div>
    <div class="carousel-item">
      <img src="veterans.jpg" alt="Veterans Park" class="d-block w-100">
      <div class="carousel-caption">
        <h2>Veterans Park</h2>
        <p>Mentor, OH</p>
      </div>
    </div>
  </div>

  <button class="carousel-control-prev" type="button" data-bs-target="#demo" data-bs-slide="prev">
    <span class="carousel-control-prev-icon"></span>
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#demo" data-bs-slide="next">
    <span class="carousel-control-next-icon"></span>
  </button>
</div>
  </body>
</head>

The carousel sure is looking much nicer, isn’t it? After all, now the users know exactly what they are looking at. Without the captions, the users would’ve assumed that the four pictures above were of random outdoor spaces.

How did I get the captions on each slide of the carousel? Easy-below the line where you insert the image (the line with the <img> tag), insert another <div> tag and set the class as carousel-caption, which indicates that you’d like to add some captions to a particular slide.

  • As you can see in the above example, I added a <div class="carousel-caption"> line four times. If you’ve got multiple images you’d like to add captions to, you’ll need to add the <div class="carousel-caption"> line for each image.

Inside the <div class="carousel-caption"> tag, you can add the caption by using as many standard HTML tags as you wish (I used the <h2> and <p> tags). Keep in mind that the more HTML tags you use, the more lines the image’s caption will have.

  • If you want to code-along with this tutorial, any four JPG images will work. If you wish to use the images I used, you’ll find the links to download each image below.

Thanks for reading,

Michael

Bootstrap Lesson 3: Images

Advertisements

Hello everybody,

Michael here, and today’s post will cover the use of images in Bootstrap.

Basics of Bootstrap Images

So, how do we work with images in Bootstrap? Honestly, the process is quite similar to working with regular HTML images. Let’s take a look at this code below, which uses one of the tables from my previous Bootstrap lesson:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <h1>Fall 2022 Movies</h1>
    <div class="container">
        <img src="cinema.jpg" class="rounded" alt="Stock photo of a cinema">
    </div>
    <div class="table">
      <table class="table">
        <tr>
          <th>Movie</th>
          <th>Release Date</th>
          <th>Genre</th>
        </tr>
        <tr>
          <td>Don't Worry Darling</td>
          <td>September 23</td>
          <td>Mystery</td>
        </tr>
        <tr>
          <td>Black Panther Wakanda Forever</td>
          <td>November 11</td>
          <td>Superhero</td>
        </tr>
        <tr>
          <td>Halloween Ends</td>
          <td>October 14</td>
          <td>Horror</td>
        </tr>
      </table>
    </div>
  </body>
</head>

Pay attention to the section of code highlighted in red, as that’s the section that adds the image onto the HTML site. In this example, I added a stock photo of a cinema below the Fall 2022 Movies header and above the table.

However, there’s something else that you’ll notice about the image-the corners are rounded. How did I do that? Well, in the image tag I specified a value for classrounded. Bootstrap 5 has seven different image classes you can utilize-rounded, rounded-top, rounded-end, rounded-bottom, rounded-start, rounded-circle and rounded-pill. Now, how do each of these image classes work? Let me explain:

  • rounded-all corners of the image are rounded
  • rounded-top-only the top corners of the image are rounded
  • rounded-end-only the right corners of the image are rounded
  • rounded-bottom-only the bottom corners of the image are rounded
  • rounded-start-only the left corners of the image are rounded
  • rounded-circle-the image turns into a circle
  • rounded-pill-the image turns into an oval
  • You don’t really need to wrap the image inside a <div class="container"> tag, but it helps if you want to center your image.
  • It helps to place your image in the same directory as your HTML code-otherwise, you’ll need to write the full file path in the src parameter.
  • In case you forgot or didn’t know, the alt parameter gives the user a description for an image incase the user can’t view the image itself for whatever reason (e.g. internet is down, the user is visually impaired and uses a screen reader)

Now, let’s see what happens when we give the image a new style-in this case, let’s go with a rounded-pill styling:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <h1>Fall 2022 Movies</h1>
    <div class="container">
        <img src="cinema.jpg" class="rounded-pill" alt="Stock photo of a cinema" height=100 width=300>
    </div>
    <div class="table">
      <table class="table">
        <tr>
          <th>Movie</th>
          <th>Release Date</th>
          <th>Genre</th>
        </tr>
        <tr>
          <td>Don't Worry Darling</td>
          <td>September 23</td>
          <td>Mystery</td>
        </tr>
        <tr>
          <td>Black Panther Wakanda Forever</td>
          <td>November 11</td>
          <td>Superhero</td>
        </tr>
        <tr>
          <td>Halloween Ends</td>
          <td>October 14</td>
          <td>Horror</td>
        </tr>
      </table>
    </div>
  </body>
</head>

In the example above, I gave the image a rounded pill styling to make it look like an oval. As for the size, I added the optional height and width parameters to the oval to change the image’s size.

  • Keep in mind that height and width are both measured in pixels.

Responsive Bootstrap Images

Now, aside from the seven different Bootstrap image classes I mentioned above, there are also two other image stylings in Bootstrap-responsive images and thumbnails.

Responsive images auto-size to match the width of their parent element. Let’s take a look at the code below (paying attention to the highlighted line) to see how responsive images work:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <h1>Fall 2022 Movies</h1>
    <div class="container">
        <img src="cinema.jpg" class="img-fluid" alt="Stock photo of a cinema">
    </div>
    <div class="table">
      <table class="table">
        <tr>
          <th>Movie</th>
          <th>Release Date</th>
          <th>Genre</th>
        </tr>
        <tr>
          <td>Don't Worry Darling</td>
          <td>September 23</td>
          <td>Mystery</td>
        </tr>
        <tr>
          <td>Black Panther Wakanda Forever</td>
          <td>November 11</td>
          <td>Superhero</td>
        </tr>
        <tr>
          <td>Halloween Ends</td>
          <td>October 14</td>
          <td>Horror</td>
        </tr>
      </table>
    </div>

To make the image responsive, I applied the img-fluid Bootstrap image class to the image. Doing so allows the image to match the width of its parent element-in this case, the Fall 2022 Movies header.

  • Look, I know the image doesn’t quite align with the Fall 2022 Movies header, but that’s beacuse I wrapped it inside a <div class="container"> tag, which moves the image away from the edge of the browser.

Thumbnail images

The other Bootstrap image styling I wanted to discuss is thumbnail images. In case you’re wondering what thumbnail images are, go to YouTube and type in anything in the search bar (like I did in the picture below):

The image I circled (along with all other images on this page) is a thumbnail, as it functions as a placeholder/hyperlink for other media-in this case the trailer for Black Panther 2.

How can we create a thumbnail image? It’s really quite simple-take a look at the highlighted line of code in the example below:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <h1>Fall 2022 Movies</h1>
    <div class="container">
        <img src="cinema.jpg" class="img-thumbnail" alt="Stock photo of a cinema">
    </div>
    <div class="table">
      <table class="table">
        <tr>
          <th>Movie</th>
          <th>Release Date</th>
          <th>Genre</th>
        </tr>
        <tr>
          <td>Don't Worry Darling</td>
          <td>September 23</td>
          <td>Mystery</td>
        </tr>
        <tr>
          <td>Black Panther Wakanda Forever</td>
          <td>November 11</td>
          <td>Superhero</td>
        </tr>
        <tr>
          <td>Halloween Ends</td>
          <td>October 14</td>
          <td>Horror</td>
        </tr>
      </table>
    </div>
  </body>
</head>

In this example, all I needed to do to give the image a thumbnail styling is to change the value of the class parameter to img-thumbnail and voila!-your image has a nice 1-pixel-thick rounded border.

  • As you might have noticed, the image kept the same size it had in the responsive images example-this is because applying the thumbnail styling to your image won’t change its previous size.
  • You might have also noticed that the thumbnail images in the YouTube screenshot I shared have no rounded border-the rounded border styling is a Bootstrap thing (many websites don’t use rounded borders for their thumbnail images).

Thanks for reading,

Michael

Bootstrap Lesson 2: Typography and Tables

Advertisements

Hello everybody,

Michael here, and today’s lesson will cover typography and tables in Bootstrap.

Bootstrap typography

Now, before I show you how to work with tables in Bootstrap, let’s first discuss Bootstrap typography, because it works a little different than your standard HTML/CSS typography.

Take a look at the font used on our first Bootstrap website (from the previous lesson):

Bootstrap uses a default Arial-like size-14 pixel font, as seen in the photo above. However, the size-14 pixel font is just a framework-wide default, as it’s applied to any element inside a <body> or <p> tag. The six main HTML headings <h1><h6> utilize the same Arial-like font, however the text sizes for each main HTML heading are as follows:

  • <h1>-size-36
  • <h2>-size-30
  • <h3>-size-24
  • <h4>-size-18
  • <h5>-size-14
  • <h6>-size-12

And if you don’t like the default Bootstrap typography, you can always change it with a little CSS, as shown below:

h1{
  font-family: "Times New Roman";
  font-size: 40px;
  color: "red"
}

And remember to link your CSS file to your HTML file (see line highlighted in red):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="BootstrapSite.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <h1>Here's your first Bootstrap site!!!</h1>
  </body>
</head>
  • To make things easier on yourself, give your CSS file the same name as your corresponding HTML file. For instance, since I named my HTML file BootstrapSite.html, I named my connected CSS file BootstrapSite.css.

And here’s the site with the changed font:

Tables

Now that we’ve discussed Bootstrap typography, let’s move on to Bootstrap tables. How do you create a table in Bootstrap? Take a look at the code below, which shows you an HTML table without any Bootstrap:

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="BootstrapSite.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <table>
      <tr>
        <th>Movie</th>
        <th>Release Date</th>
        <th>Genre</th>
      </tr>
      <tr>
        <td>Don't Worry Darling</td>
        <td>September 23</td>
        <td>Mystery</td>
      </tr>
      <tr>
        <td>Black Panther Wakanda Forever</td>
        <td>November 11</td>
        <td>Superhero</td>
      </tr>
      <tr>
        <td>Halloween Ends</td>
        <td>October 14</td>
        <td>Horror</td>
      </tr>
    </table>
  </body>
</head>

As you can see, I have created a simple table in HTML, but with no Bootstrap applied. As a result, the table displays just fine, but doesn’t look all that great. How can we fix this? Apply a little Bootstrap, of course (hey, this is a Bootstrap lesson after all)! Pay attention to the highlighted lines of code to see how you can apply a little Bootstrap magic to your HTML table (note-there is no CSS code attached here):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <h1>Fall 2022 Movies</h1>
    <div class="table">
      <table class="table">
        <tr>
          <th>Movie</th>
          <th>Release Date</th>
          <th>Genre</th>
        </tr>
        <tr>
          <td>Don't Worry Darling</td>
          <td>September 23</td>
          <td>Mystery</td>
        </tr>
        <tr>
          <td>Black Panther Wakanda Forever</td>
          <td>November 11</td>
          <td>Superhero</td>
        </tr>
        <tr>
          <td>Halloween Ends</td>
          <td>October 14</td>
          <td>Horror</td>
        </tr>
      </table>
    </div>
  </body>
</head>

In order to apply Bootstrap stylings to my HTML table, I wrapped the code for my HTML table inside a <div> tag and specified which one of Bootstrap’s table stylings I’d like to apply-in this case, I chose the basic table styling table and specified the styling in the line <div class="table">.

Oh, but here’s the fun part about Bootstrap table stylings! Bootstrap has 7 different ways you can style your table, six of which include:

  • table-Just a plain Bootstrap table (like the example above)
  • table-striped-Gives the table “zebra stripes” (alternating grey and white rows)
  • table-bordered-Adds a border around all sides of the table and around all cells
  • table-hover-Any rows that you hover over turn grey
  • table-condensed-Makes a table more compact by reducing cell padding by half
  • table-responsive-Allows you to scroll through the table horizontally on small devices (anything less than 768 pixels wide); for devices wider than 768 pixels, there is no difference in how the table is displayed

To give your HTML table any of these stylings, wrap the HTML table code inside a <div> tag and use this syntax to apply the Bootstrap styling-<div class="Bootstrap table styling">.

Now, notice how I said you can choose seven different Bootstrap table stylings for your HTML table, but I only mentioned six stylings above. That’s because the seventh styling doesn’t involve wrapping your HTML table code in a <div> tag. Rather, the seventh styling comes in the form of contextual classes, which are table stylings that you can apply to individual table rows (<tr> tag) or table cells (<td> tag).

Let’s see how the contextual classes work:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

</head>
<body>

<div class="container">
  <h1>2021 AFC Standings</h1>
  <table class="table">
    <thead>
      <tr>
        <th>Team</th>
        <th>Record</th>
        <th>Seeding</th>
      </tr>
    </thead>
    <tbody>
      <tr class="success">
        <td>Tennessee Titans</td>
        <td>12-5</td>
        <td>1</td>
      </tr>
      <tr class="success">
        <td>Kansas City Chiefs</td>
        <td>12-5</td>
        <td>2</td>
      </tr>
      <tr class="success">
        <td>Buffalo Bills</td>
        <td>11-6</td>
        <td>3</td>
      </tr>
      <tr class="success">
        <td>Cincinnati Bengals</td>
        <td>10-7</td>
        <td>4</td>
      </tr>
      <tr class="warning">
        <td>Las Vegas Raider</td>
        <td>10-7</td>
        <td>5</td>
      </tr>
      <tr class="warning">
        <td>New England Patriots</td>
        <td>10-7</td>
        <td>6</td>
      </tr>
      <tr class="warning">
        <td>Pittsburgh Steelers</td>
        <td>9-7-1</td>
        <td>7</td>
      </tr>
      <tr class="danger">
        <td>Indianapolis Colts</td>
        <td>9-8</td>
        <td>8</td>
      </tr>
      <tr class="danger">
        <td>Miami Dolphins</td>
        <td>9-8</td>
        <td>9</td>
      </tr>
      <tr class="danger">
        <td>Los Angeles Chargers</td>
        <td>9-8</td>
        <td>10</td>
      </tr>
      <tr class="danger">
        <td>Cleveland Browns</td>
        <td>8-9</td>
        <td>11</td>
      </tr>
      <tr class="danger">
        <td>Baltimore Ravens</td>
        <td>8-9</td>
        <td>12</td>
      </tr>
      <tr class="danger">
        <td>Denver Broncos</td>
        <td>7-10</td>
        <td>13</td>
      </tr>
      <tr class="danger">
        <td>New York Jets</td>
        <td>4-13</td>
        <td>14</td>
      </tr>
      <tr class="danger">
        <td>Houston Texans</td>
        <td>4-13</td>
        <td>15</td>
      </tr>
      <tr class="danger">
        <td>Jacksonville Jaguars</td>
        <td>3-14</td>
        <td>16</td>
      </tr>
    </tbody>
  </table>
</div>

</body>
</html>

As you can see, we have created a colorful table showing 2021 NFL AFC (American Football Conference for those unaware) standings for all 16 AFC teams using Bootstrap’s contextual table classes. How did we accomplish this?

In this example, I used the success class for the top 4 rows, which indicates the four AFC teams that won their divisions last year. To apply the success class styling to the first four rows of this table, I used the line <tr class="success"> before the table row code for each of these rows. I then applied the same logic to style the rows for the wildcard teams (seeds 5-7) and the teams that didn’t make playoffs last year (seeds 8-16), except I replaced the success class with the warning and danger classes, respectively.

  • Another thing I’d like to note-I’ve used Atom text editor for my HTML, CSS and Bootstrap lessons, however Atom text editor will be retired by GitHub on December 15, 2022. You’ll likely still be able to download it after that date, but it won’t be updated anymore. If you’re looking for a new IDE for your web development, Sublime Text Editor and Microsoft’s Visual Studio Code are great text editors.

Thanks for reading!

Michael

Bootstrap Lesson 1: The Basics of Bootstrap

Advertisements

Hello everybody,

Michael here, and in today’s lesson, I’ll introduce a new programming tool-Bootstrap (the eigth programming tool I’ll cover in this blog).

What is Bootstrap exactly? Well, to put it simply, Bootstrap is an HTML/CSS/JavaScript web development tool that allows you to create mobile-friendly, easily responsive websites.

Now, you may be wondering if this means you’re going to be learning a whole new language with all new syntax. The good thing about Bootstrap is that, while I will introduce some new syntax to you all, it is very easy to understand if you’ve got at least a working knowledge of HTML and CSS (so if you’ve followed my HTML and CSS lessons, you should be good to go here). If it helps, think of Bootstrap as a supplement to HTML and CSS.

Now, how do we get started with Bootstrap? First, we’re going to start by downloading the lastest version of Bootstrap (as of September 2022)-Bootstrap 5-from getbootstrap.com.

Did I say downloading Bootstrap? You could do that, but there’s a much more convinient workaround. In your HTML file, copy these two lines of code into your document:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>

These two lines of code will give you all the CSS and JavaScript scripts you’ll need to run Bootstrap (and yes, you’ll need both scripts to get the most out of Bootstrap).

  • About these two lines of code-you’ll need them every time you want to use Bootstrap for your website, as your websites won’t run on Bootstrap if you don’t include these two lines of code on top of your HTML file

Now, let’s create our first Bootstrap website! Take a look at the code below (and remember to include the two lines of code I just mentioned at the top of the file):

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<head>
  <body>
    <h1>Here's your first Bootstrap site!!!</h1>
  </body>
</head>

As you can see, we have created a simple Bootstrap site. Granted, there’s not much content or CSS stylings on the site but don’t worry-we’ll cover more cool Bootstrap features in the next few lessons!

Thanks for reading,

Michael

Python Lesson 36: Named Entity Recognition (NLP pt. 5)

Advertisements

Hello everybody,

Michael here, and today’s lesson will be on named entity recoginition in Python NLP.

Intro to named entity recognition

What is named entity recogintion exactly? Well, it’s NLP’s process of identifying named entities in text. Named entities are bascially anything that is a place, person, organization, time, object, or geographic entity-in other words, anything that can be denoted with a proper name.

Take a look at this headline from ABC News from July 21, 2022:

Former Minneapolis police officer sentenced in George Floyd killing

How many named entities can you find? If you answered two, you’d be correct-Minneapolis and George Floyd.

Python’s SPACY package

Before we begin any named-entity recognition analysis, we must first pip install the spacy package using this line of code-pip install spacy. Unlike the last four NLP lessons I’ve posted, this lesson won’t use the NLTK package (or any modules within) as Python’s spacy package is better suited for this task.

In case you need assistance with installing the spacy package, click on this link-https://spacy.io/usage#installation. This link will show you how to install spacy based on what operating system you have.

If you go to this link, you will see an interface like the one pictured above (picture current as of July 2022). Toggling the filters on this interface will show you the commands you’ll need to use to install not only the spacy module itself but also a trained spacy pipeline in whatever language you choose (and there are 23 options for languages here). The commands needed to install spacy will depend on things like the OS you’re using (whether Mac, Windows, or Linux), the package manage you’re using to install Python packages (whether pip, conda, or from source), among other things.

The Spacy pipeline

Similar to how we downloaded the punkt and stopwords modules in NTLK, we will also need to install a seprate module to work with spacy-in this case, the spacy pipeline. See, to ensure the spacy package works to its fullest capabilites, you’ll need to download a spacy pipeline in whatever language you choose (I’m using English for this example)

  • Remember to install the spacy pipeline AFTER installing the spacy package!

For this lesson, I’ll be using the en_core_web_md pipeline, which is a medium-sized English spacy pipeline. If you wish, you can download the en_core_web_sm or en_core_web_lg pipelines-these are the small-sized and large-sized English spacy pipelines, respectively. The larger the spacy pipeline you choose, the better its named-entity recognition functionalities would be-the small pipeline has 12 megabytes of info, the medium pipeline has 40 megabytes of info, and the large pipeline has 560 megabytes of info.

To install the medium-sized English spacy pipeline, run this command-python -m spacy download en_core_web_md.

  • If you’re downloading the small-sized or large-sized English spacy pipelines, replace en_core_web_md with en_core_web_sm or en_core_web_lg depending on the pipeline size you’re using.

However, even after installing the pipeline, you’ll still need to download it in your code using this line of code-spacy.load('en_core_web_md'). Remember that even though I’m using the en_core_web_md spacy pipeline, pass whatever pipeline you’ll be using as the parameter for the spacy.load() method.

Spacy in action

Now that I’ve explained the basics of setting up spacy, it’s time to show named-entity recognition in action. For the example I’ll show you, I’ll use this XLSX file containing twelve different news headlines from the Associated Press published on July 25 and 26, 2022:

Let’s see how we can find all of the named entities in these twelve headlines:

import spacy
nlp = spacy.load('en_core_web_md')
import pandas as pd

headlines = pd.read_excel(r'C:\Users\mof39\OneDrive\Documents\headlines.xlsx')

for h in headlines['Headline']:
    doc = nlp(h)
    
    for ent in doc.ents:
        print(ent.text)
    
    print(h)
    print() 

North Dakota
final day
North Dakota abortion clinic prepares for likely final day

Paul Sorvino
83
‘Goodfellas,’ ‘Law & Order’ actor Paul Sorvino dies at 83

Biden
Biden fights talk of recession as key economic report looms

Hobbled
GM
40%
Hobbled by chip, other shortages, GM profit slides 40% in Q2

Mike Pence
Nov.
Former Vice President Mike Pence to release memoir in Nov.

September
Elon Musk
Twitter sets September shareholder vote on Elon Musk buyout

Choco Taco
summer
Sorrow in Choco Taco town after summer treat is discontinued

Texas
Appeals court upholds Texas block on school mask mandates

QB Kyler Murray
Cardinals say QB Kyler Murray focused on football

Jack Harlow
Lil Nas X
Kendrick Lamar
MTV
Jack Harlow, Lil Nas X, Kendrick Lamar top MTV VMA nominees

New studies bolster theory coronavirus emerged from the wild

Northwest swelters under ‘uncomfortable’ multiday heat wave

In this example, I first performed all the necessary imports and read in the headlines dataset as a pandas dataframe. I then looped through all the values in the Headline column in the pandas dataframe, converted each value into a spacy doc (this is necessary for the named-entity recognition), and looped through all the tokens in the headline in order to find and print out any named entities that spacy finds-the headline itself is printed below all (or no) named entities that are found.

As you can see, spacy found named entities in 10 of the 12 headlines. However, you may notice that spacy’s named-entity recognition isn’t completely accurate, as it missed some tokens that are clearly named entities. Here are some surprising omissions:

  • Goodfellas and Law & Order on headline #2-referring to a movie and TV show, respectively
  • Q2 on headline #4-in the context of this article, refers to GM’s Q2 2022 profits
  • Twitter on headline #6-Twitter is one of the world’s most popular social media sites after all
  • Cardinals on headline #9-This headline refers to Arizona Cardinals QB Kyler Murray
  • VMA on headline #10-VMA refers to the MTV VMAs, or Video Music Awards
  • Northwest on headline #12-Northwest referring to the Northwest US region

Along with these surprising omissions, here are some other interesting observations I found:

  • Spacy read QB Kyler Murray as a single entity but not Vice President Mike Pence
  • MTV VMA wasn’t read as a single entity-rather, MTV was read as the entity
  • Hobbled shouldn’t be read as an entity at all

Now, what if you wanted to know each entity’s label? Take a look at the code below, paying attention to the red highlighted line (the line I revised from the above example):

import spacy
nlp = spacy.load('en_core_web_md')
import pandas as pd

headlines = pd.read_excel(r'C:\Users\mof39\OneDrive\Documents\headlines.xlsx')

for h in headlines['Headline']:
    doc = nlp(h)
    
    for ent in doc.ents:
        print(ent.text + ' --> ' + ent.label_)
    
    print(h)
    print() 

North Dakota --> GPE
final day --> DATE
North Dakota abortion clinic prepares for likely final day

Paul Sorvino --> PERSON
83 --> CARDINAL
‘Goodfellas,’ ‘Law & Order’ actor Paul Sorvino dies at 83

Biden --> PERSON
Biden fights talk of recession as key economic report looms

Hobbled --> PERSON
GM --> ORG
40% --> PERCENT
Hobbled by chip, other shortages, GM profit slides 40% in Q2

Mike Pence --> PERSON
Nov. --> DATE
Former Vice President Mike Pence to release memoir in Nov.

September --> DATE
Elon Musk --> ORG
Twitter sets September shareholder vote on Elon Musk buyout

Choco Taco --> ORG
summer --> DATE
Sorrow in Choco Taco town after summer treat is discontinued

Texas --> GPE
Appeals court upholds Texas block on school mask mandates

QB Kyler Murray --> PERSON
Cardinals say QB Kyler Murray focused on football

Jack Harlow --> PERSON
Lil Nas X --> PERSON
Kendrick Lamar --> PERSON
MTV --> ORG
Jack Harlow, Lil Nas X, Kendrick Lamar top MTV VMA nominees

New studies bolster theory coronavirus emerged from the wild

Northwest swelters under ‘uncomfortable’ multiday heat wave

To print out each entity’s label, I added a text arrow after each entity pointing to that entity’s label. What do each of the entity labels mean?

  • ORG-any sort of organization (like a company, educational institution, etc)
  • NORP-nationality/religious or political groups (e.g. American, Catholic, Democrat)
  • GPE-geographical entity
  • PERSON
  • LANGUAGE
  • MONEY
  • DATE
  • TIME
  • PRODUCT
  • EVENT
  • CARDINAL-as in cardinal number (one, two, three, etc.)
  • ORDINAL-as in ordinal number (first, second, third, etc.)
  • WORK OF ART-a book, movie, song; really anything that you can consider a work of art

All in all, the label matching seems to be pretty accurate. However, one mislabelled entity can be found on headline #6-Elon Musk is mislabelled as ORG (or organization) when he clearly isn’t an ORG. Another mislabelled entity is Hobbled-it is listed as a PERSON when it shouldn’t be listed as an entity at all.

Now, what if you wanted a neat way to visualize named-entity recognition? Well, Spacy’s Displacy module would be the answer for you. See, the Displacy module will help you visualize the NER (named-entity recognition) that Spacy conducts.

Let’s take a look at Displacy in action:

import spacy
nlp = spacy.load('en_core_web_md')
import pandas as pd

headlines = pd.read_excel(r'C:\Users\mof39\OneDrive\Documents\headlines.xlsx')

for h in headlines['Headline']:
    doc = nlp(h)
    displacy.render(doc, style='ent')

Pay attention to the code that I used here. Unlike the previous examples, I actually save the spacy pipeline I downloaded as a variable (nlp). I then read in the data-frame containing the headlines, loop through each value in the Headline column, and run the displacy.render() method, passing in the string I’m parsing (doc) and the displacy style I want to use (ent) as this method’s parameters.

After running the code, you can see a nice, colorful output showing you all the named entities (at least the named entities spacy found) in the text along with the entitiy’s corresponding label. You’ll also notice that each entity is color-coded according to its label; for instance, geographical entites (e.g. Texas, North Dakota) are colored in orange while peoples’ names (e.g. Kendrick Lamar, Lil Nas X) are colored in purple.

While running this code, you’ll also see the UserWarning above-in this case, don’t worry, as this warning simply means that spacy couldn’t find any named entities for a particular string (in this example, spacy couldn’t find any named entities for two of the 12 strings).

Oh, and one more reminder. In the displacy.render() method, you’ll need to include style='ent' as a parameter if you want to work with named-entity recognition, as here’s the default diagram that you get as an output if you don’t specify a style:

In this case, the code still works fine, but you’ll get a dependency parse diagram, which shows you how words in a string are syntactically related to each other.

Thanks for reading,

Michael

Python Lesson 35: Parts-of-speech tagging (NLP pt. 4)

Advertisements

Hello everybody,

Michael here, and today’s post will cover parts-of-speech tagging as it relates to Python NLP (this is part 4 in my NLP Python series).

Intro to parts-of-speech tagging

What is parts-of-speech (POS) tagging, exactly? See, Python NLP can do some really cool things, such as getting the roots of words (Python Lesson 34: Stemming and Lemmatization (NLP pt. 3)) and finding commonly used words (stopwords) in 24 different languages (Python Lesson 33: Stopwords (NLP pt.2)). In Python, parts-of-speech tagging is a quite self-explanatory process, as it involves tokenizing a string and identifying each token’s part-of-speech (such as a noun, verb, etc.). Keep in mind that this isn’t going to be a grammar lesson, so I’m not going to teach you how to use POS tagging to improve your grammar or proofread something you wrote.

POS tagging in action

Now that I’ve explained the basics of POS tagging, let’s see it in action! Take a look at the example below:

import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')

test = input('Please input a test string: ')
tokens = nltk.word_tokenize(test)

tagged = []

for t in tokens:
    tagged = nltk.pos_tag(tokens)
    
print(tagged)

Please input a test string: I had a fun time dancing last night.
[('I', 'PRP'), ('had', 'VBD'), ('a', 'DT'), ('fun', 'JJ'), ('time', 'NN'), ('dancing', 'VBG'), ('last', 'JJ'), ('night', 'NN'), ('.', '.')]

Before getting into the fun POS tagging, you’d first need to import the nltk package and download two of the package’s modules-punkt and averaged_perceptron_tagger. punkt is NLTK’s standard package module which allows Python to work its NLP magic while averaged_perceptron_tagger is the module that enables all the fun POS tagging capabilities.

After including all the necessary imports and downloading all the necessary package modules, I then inputted and word-tokenized a test string. I then created an empty list-tagged-that will store the results of our POS tagging.

To perform the POS tagging, I iterated through each element in the list of tokens (aptly called tokens) and used NLTK’s pos_tag() method to add the appropriate POS tag to the element. I then printed out the tagged list, which contains the results of our POS tagging. As you can see, the tagged list contains a list of tuples-the first element in each tuple is the token itself while the second element is that token’s part-of-speech. Punctuation is also included, as punctuation counts as its own token, but doesn’t belong to any part-of-speech.

You likely noticed that the POS tags are all two or three character abbrevations. Here’s a table explaining all of the POS tags:

TagPart-of-speechExample/Explanation
CCcoordinating conjuctionAny of the FANBOYS conjuctions (for, and,
nor, but, or, yet, so)
CDcardinal digitThe numbers 0-9
DTdeterminerA word in front of a noun to specify quanity
or to clarify what the noun refers to (e.g. one
car, that child)
EXexistential thereThere is a snake in the grass.
FWforeign wordSince I’m using English for this post, any word
that isn’t English (e.g. palabra in Spanish)
INprepositionon, in, at
JJadjective (base form)large, tiny
JJRcomparative adjectivelarger, tinier
JJSsuperlative adjectivelargest, tiniest
LSlist marker1), 2)
MDmodal verbOtherwise known as auxiliary verb (e.g. might
happen, must visit)
NNsingular nouncar, tree, cat, etc.
NNSplural nouncars, trees, cats, etc.
NNPsingular proper nounFord
NNPSplural proper nounAmericans
PDTpredeterminerA word or phrase that occurs before a determiner
that quantifies a noun phrase (e.g. lots of toys,
few students)
POSpossessive endingMichael’s, Tommy’s
PRPpersonal pronounPronouns associated with a grammatical person-be it first person, second person, or third person (e.g.
they, he, she)
PRP$possessive pronounPronouns that indicate possession (e.g. mine, theirs, hers)
RBadverbvery, extremely
RBRcomparative adverbearlier, worse
RBSsuperlative adverbbest, worst
RPparticleAny word that doesn’t fall within the main parts-of-speech (e.g. give up)
TOthe word ‘to’to come home
UHinterjectionYikes! Ummmm.
VBbase form of verbwalk
VBDpast tense of verbwalked
VBGgerund form of verbwalking
VBNpast participle of verbwalked
VBPpresent singular form of verb (non-3rd person)walk
VBZpresent singular form
of verb (3rd-person)
walks
WDT“wh” determinerwhich
WP“wh” pronounwho, what
WP$possessive “wh” pronounwhose
WRB“wh” adverbwhere, when

As you can see, even though English has only eight parts of speech (verbs, nouns, adjectives, adverbs, pronouns, prepositions, conjuctions, and interjections), Python has 35 (!) parts-of-speech tags.

  • Even though I’m working with English here, I imagine these POS tags can work for any language.

If you take a look at the last line of output in the above example (the line containing the list of tuples), you can see two-element tuples containing the token itself as the first element along with the token’s POS tag as the second element. And yes, punctuation in a sentence counts as a token itself, but it has no POS tag. Hence why the tuple-POS tag pair for the period at the end of the sentence looks like this-['.', '.'].

Now, what if there was a sentence that had the same word twice but used as different parts-of-speech (e.g. a sentence that had the same word used as a noun and a verb). Let’s take a look at the example below:

import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')

test = input('Please input a test string: ')
tokens = nltk.word_tokenize(test)
tagged = nltk.pos_tag(tokens)
    
print(tagged)

Please input a test string: She got a call at work telling her to call the project manager.
[('She', 'PRP'), ('got', 'VBD'), ('a', 'DT'), ('call', 'NN'), ('at', 'IN'), ('work', 'NN'), ('telling', 'VBG'), ('her', 'PRP'), ('to', 'TO'), ('call', 'VB'), ('the', 'DT'), ('project', 'NN'), ('manager', 'NN'), ('.', '.')]

Take a close look at the sentence I used in this example-She got a call at work telling her to call the project manager. Notice the repeated word here-call. In this example, call is used as both a noun (She got a call at work) and a verb (to call the project manager.). The neat thing here is that NLTK’s POS tagger recognizes that the word call is used as two different parts-of-speech in that sentence.

However, the POS tagger may not always be so accurate when it comes to recognizing the same word used as a different part of speech. Take a look at this example:

import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')

test = input('Please input a test string: ')
tokens = nltk.word_tokenize(test)
tagged = nltk.pos_tag(tokens)
    
print(tagged)

Please input a test string: My apartment building is bigger than any other apartment in a 5-block vicinity.
[('My', 'PRP$'), ('apartment', 'NN'), ('building', 'NN'), ('is', 'VBZ'), ('bigger', 'JJR'), ('than', 'IN'), ('any', 'DT'), ('other', 'JJ'), ('apartment', 'NN'), ('in', 'IN'), ('a', 'DT'), ('5-block', 'JJ'), ('vicinity', 'NN'), ('.', '.')]

In this example, I’m using the word apartment twice, as both an adjective (My apartment building) and a noun (any other apartment). However, NLTK’s POS tagger doesn’t recognize that the first instance of the word apartment is being used as an adjective to modify the noun building.

  • Hey, what can you say, programs aren’t always perfect. But I’d say NLTK’s POS tagger works quite well for parts-of-speech analysis.

Thanks for reading,

Michael

Python Lesson 34: Stemming and Lemmatization (NLP pt. 3)

Advertisements

Hello everybody,

Michael here, and today’s lesson will cover stemming and lemmatization in Python NLP (natural language processing).

Stemming

Now that we’ve covered some basic tokenization concepts (like tokenization itself and filtering out stopwords), we can move on to the next important concepts in NLP-stemming and lemmatization. Stemming is an NLP task that involves reducing words to their roots-for instance, stemming the words “liked” and “likely” would result in “like”

Now, the NLTK package has several stemmers you can use, but for this lesson (along with all Python NLP lesson on this blog) I will be using NLTK’s PorterStemmer stemmer. Let’s see stemming in action:

import nltk
nltk.download('punkt')
from nltk.stem import PorterStemmer

test = input('Please input a test string: ')
testWords = nltk.word_tokenize(test)
print(testWords)

stemmer = PorterStemmer()
stemmedWords = [stemmer.stem(word) for word in testWords]
print(stemmedWords)

Please input a test string: Byte sized programming classes for eager coding learners
['Byte', 'sized', 'programming', 'classes', 'for', 'eager', 'coding', 'learners']
['byte', 'size', 'program', 'class', 'for', 'eager', 'code', 'learner']

To start your stemming, include the first three lines of code you see above as the imports and downloads. And yes, you’ll need to import the PorterStemmer separately.

After including all the necessary downloads and imports, I then included code to input a test string, word-tokenize that test string, and print the list of tokens. After performing the word-tokenizing, I then created a PorterStemmer object (aptly named stemmer), performed a list comprehension to stem each token in the input string, and printed the stemmed list of tokens.

What do you notice in the stemmed list of tokens (it’s the last line of output by the way)? First of all, all words are displayed in lowercase, which is nothing remarkable. Secondly, notice how most of the stemmed tokens make perfect sense (e.g. sized = size, programming = program, and so on); sometimes when stemming words in Python NLP, you’ll get some weird outputs.

Now, let’s try another input string and see what kind of results we get:

import nltk
nltk.download('punkt')
from nltk.stem import PorterStemmer

test = input('Please input a test string: ')
testWords = nltk.word_tokenize(test)
print(testWords)

stemmer = PorterStemmer()
stemmedWords = [stemmer.stem(word) for word in testWords]
print(stemmedWords)

Please input a test string: The quick brown fox jumped over the lazy brown dog and jumps over the even lazier brown cat.
['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'brown', 'dog', 'and', 'jumps', 'over', 'the', 'even', 'lazier', 'brown', 'cat', '.']
['the', 'quick', 'brown', 'fox', 'jump', 'over', 'the', 'lazi', 'brown', 'dog', 'and', 'jump', 'over', 'the', 'even', 'lazier', 'brown', 'cat', '.']

Just like the previous example, this example tokenizes an input string and stems each element in the tokenized list. However, pay attention to the words “lazy” and “lazier”. Although “lazier” is a conjugation of “lazy”, “lazy” has a stem of, “lazi” while “lazier” has a stem of “lazier”.

OK, so if stemming sometimes gives you weird and inconsistent results (like in the example above), there’s a reason for that. See, stemming reduces words to their core meaning. However, unlike lemmatization (which I’ll discuss next), stemming is a lot cruder, so it’s not uncommon to get fragments of words when stemming. Plus, the PorterStemmer tool is based off an algorithm that was developed in 1979-so yea, it’s a little dated. There is a PorterStemmer2 tool that improves upon the PorterStemmer tool we used-just FYI.

Lemmatization

Now that we’ve covered the basics of word stemming, let’s move on to word lemmatization. Lemmatization, like stemming, is an NLP tool that is meant to reduce words to their core meaning. However, unlike stemming, lemmatization usually gives you a complete word rather than a fragment of a word (e.g. “lazi” from the previous example).

import nltk
nltk.download('punkt')
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer

test = input('Please input a test string: ')
tokens = nltk.word_tokenize(test)
lemmatizer = WordNetLemmatizer()
lemmatizedList = [lemmatizer.lemmatize(word) for word in tokens]

print(lemmatizedList)

Please input a test string: The two friends drove their nice blue cars across the Florida coast.
['The', 'two', 'friend', 'drove', 'their', 'nice', 'blue', 'car', 'across', 'the', 'Florida', 'coast', '.']

So, how did I accomplish the lemmatization? First of all, after adding in all the necessary downloads and imports (and typing in an import string), I first tokenized my input string. I then created a lemmatizer object (aptly named lemmatizer) using NLTK’s WordNetLemmatizer tool. To lemmatize each token in the input string, I ran list comprehension to pass each element of the list of tokens (aptly named tokens) into the lemmatizer tool to lemmatize each word. I stored the results of this list comprehension into the lemmatizedList and printed that list below the text input.

As you can see from the example above, the lemmas of the tokens above are the same as the tokens themselves (e.g. two, across, blue). However, some of the tokens have different lemmas (e.g. cars–>car, friends–>friend). That’s because, as I mentioned earlier, lemmas find the root of a word. In the case of the words cars and friends, the root of the word would be the word’s singular form (car and friend, respectively).

  • Just thought I’d put this out here, but the root word that is generated is called a lemma, and the group of words with a particular lemma is called a lexeme. For instance, the word “try” would be the lemma while the words “trying, tried, tries” could be part of (but not the only words) that are part of the lexeme.

So, from the example above, looks like the lemmatization works much better than stemming when it comes to finding the root of a word. But what if you tried lemmatizing a word that looked very different from its lemma? Let’s see an example of that below (using the lemmatizer object created from the previous example):

lemmatizer.lemmatize("bought")
'bought'

In this example, I’m trying to lemmatize the word “bought” (as in, I bought a new watch.) However, you can see that in this example, the lemma of bought is bought. That can’t be right, can it?

Why do you think that particular output was generated? Simply put, the lemmatizer tool, by default, will assume a word is a noun (even when that clearly isn’t the case).

How can we correct this? Take a look at the example below:

lemmatizer.lemmatize("bought", pos='v')
'buy'

In this example, I added the pos parameter, which specifies a part of speech for a particular word. In this case, I set the value of pos to v, as the word “bought” is a verb. Once I added the pos parameter, I was able to get the correct lemma for the word “bought”-“buy”.

  • When working with lemmatization, you’ll run into the issue quite a bit with adjectives and irregular verbs.

Thanks for reading,

Michael