PyTorch Tutorial 08 - Logistic Regression

Patrick Loeber · Beginner ·🧬 Deep Learning ·6y ago

Key Takeaways

This video tutorial demonstrates the implementation of logistic regression using PyTorch, covering data loading, scaling, and conversion to PyTorch tensors, as well as defining a custom logistic regression model, setting up the model and optimizer for training, and calculating accuracy using predicted classes and test labels. The tutorial utilizes tools such as PyTorch, SKLearn, and NumPy, and employs techniques like supervised learning and binary classification.

Full Transcript

hi everybody welcome back to a new PI torch tutorial this time we implement logistic regression if you've watched the previous tutorials then this should be very easy now once again we implement our typical PI touch pipeline with those three steps so first we set up our model we define the input and output size and the forward pass then we create the loss and the optimizer functions and then we do the actual training loop with the forward pass the backward pass and the weight updates the code here should be very similar to the code in the last tutorial where we implemented linear regression we only have to make slight adjustments for the model and the loss function so we add one more layer to our model and we select a different loss function from pi towards built-in functions so let's start first of all that it let's import some things that we need so we import torch of course and we import torch dot n n s and n so the neural network module then we import numpy s and P to make some data transformations then from SK learn we import datasets to load a binary classification dataset then from SK learn dot pre-processing we want to import standard skaila because we want to scale our features and then from SK learn dot model selection we import train test split because we want to have a separation of training and testing data and now let's do our three steps so first we want to set up the model then we want to set up the loss and the optimizer and then in the third step we do the actual training loop and as a step zero we want to prepare the data so let's do this so let's load the pressed concert data set from SK learn so we can say BC equals data sets dot load breast cancer this is a binary classification problem where we can predict cancer based on the input features so let's say x and y equals BC dot data and BC dot target and then we want to say well first of all it's gotten get the number of samples and the number of features by saying this is X dot shape so let's print this first so print the number of samples and the number of features to see how our dataset looks like and we see we have 569 samples and 30 different features so a lot of features here and now let's continue and let's split our data when we say X strain and X test and next test and y train and Y test equals here we can use the Train test but function where we put in x and y and we want to be the test size to be 20% so this is point two and let's also give this a random state equals let's say 1 2 3 4 and there should be a small s and now let's convert or first of all now we want to scale our features scale them here we set up a standard scale ax SC equals standards gala which will make our features to have zero mean and unit variance this is always recommended to do and when we want to deal with a logistic regression so now we scale our data so we say X train equals s C dot fit transform and then as an input we put in X train and then we want to do the same thing with our test data so we say X test equals SC dot here we only transform it and here we put in X test now we scaled our data now we want to convert it to torch tens us so let's say X train equals torch dot and then here we can use the function from numpy and then we put in X train and cost this to a float32 data type so we say X train dot s type numpy dot float32 because right now this is of type double and then we would run into some errors later so let's cast this and convert this to eight tens oh and now let's do this with all the other array so let's say X test equals this and our y train and also our Y test tens on my test and now as a last thing to prepare our data is to reshape our Y tends us so Y train equals y train dot view this is a built-in function from PI torch that will reshape our tenza with the given size so it gets the size why train that shape zero and one so right now our Y has only one row and we want to make it a column vector so we want to put each value in one row with only one column so this will do exactly this and also for our Y test so Y test equals this Y test and now we are think we are done with our data preparing so now let's set up our model and here our model is a linear combination of weights and a bias and then in the logistic regression case we apply a sigmoid function at the end so let's do this and for this we want to write our own class so let's call this model or we can also call this logistic regression just tick regression and this must be derived from n + dot module and then this will get a in it which has self and then it gets the number of input features and here first we call the super init so let's say super logistic regression and self dot in it and then here we define our layer so we only have one layer self dot linear equals and here we can use the built-in layer n n dot linear and this gets the input size so and input features and the output size is just one so we only want to have one value one class label at the end and then we also have to implement the forward pass here which has self and the data and our forward pass is first we apply the linear layer and then the sigmoid function so here we say Y predicted equals Torche dot sigmoid so this is also a built-in function that we can use and here we apply our self that linear layer so linear layer with our data X and then we return our y predicted so this is our model and now let's create this so model equals logistic regression of size and here we put in the number of features that we have so now our layer is of size thirty by one and no sorry thirty input features and one output feature and now we have our model and now we can continue with the loss and the optimizer so for a loss the loss function now is different than in the linear regression case so here we say criterion equals and n dot BCE loss so the binary cross-entropy loss here and our optimizer is the same so this can be this is Torche dot optim dot s GD for a stochastic gradient descent and this gets some parameters that we want to optimize so here we just say model dot parameters and it also needs a learning rate so let's say our learning rate equals point zero one and then here we say L R equals learning rate so now this is step two and now step three so let's define some number of epochs equals let's say 100 iterations and now we do our training loop so now we do for epoch in range num a pox and then first we do the forward pass forward pass and the lost calculation then we do the backward pass and then we do the updates so let's say Y predict it equals here we call our model and as theta it gets extreme and then we say loss equals criterion and this will get a the y predicted and the actual y training so the training samples or training labels and now we do the backward pass and calculate the gradients and again we simply have to call loss that dots backward and PI torch will do all the calculations for us and now we update our weights so here we simply have to say optimizer dot step and again PI torch will do all the update calculations for us and then we don't or we must not forget to empty our gradients again so one to zero the gradients because the backward function here will always add up all the radiance into the dot grat attribute so let's empty them again before the next iteration and we simply must say optimizer dot 0 grat and then let's also print some information if a POC plus 1 modulo 10 equals equals 0 so every tenth step we want to print some information let's use an F string here let's say epoch and here we can use epoch plus 1 and then we also want to see the loss so the loss equals loss dot item and that's format this to say to only print for decimal values and yeah so now we are done this is our logistic regression implementation and now let's evaluate our model so the evaluation should not be part of our computational graph where we want to track the history so we want to say with torch dot no grat and then do our evaluation here so here I want to get the accuracy so let's get all the predicted classes from our test samples so let's say this is model and here we put in X test and then let's convert this to class label so 0 or 1 so remember the sigmoid function here will return a value between 0 and 1 and if this is larger than 0.5 we say this is class 1 and otherwise its class 0 so let's say Y predicted classes equals y pretty that dot round so here we can use a built-in function again and this will do exactly this and yeah so if we do don't use this statement then this would be part of the computational graph and it would track the gradient calculations for us so here we don't want this we don't need this because we are done so that's why we use this with statement here and now let's calculate the accuracy by saying AK equals y predicted classes and here we can call the equal function equals y test and then the sum so we want to sum them up for every prediction that is correct it will add plus one and then we divide this by the number of samples of test samples so Y tests dot shape 0 this will return the number of test samples and then let's print our accuracy print accuracy equals ax dot point for F also only for decimal values and now let's run this and hope that everything is correct and Standards gala has no attribute transfrom so here I have a typo transform now let's run this again trance form one more try and now we are done and we have a accuracy of point 89 so it's okay it's good but it's not perfect so you might want to play around with for example the number of iterations and where do we have it the number of epochs or the learning rate for example or also maybe try out a different optimizer here but basically that's how we implement logistic regression I hope you liked it if you liked it please subscribe to the channel and see you next time bye

Original Description

New Tutorial series about Deep Learning with PyTorch! ⭐ Check out Tabnine, the FREE AI-powered code completion tool I use to help me code faster: https://www.tabnine.com/?utm_source=youtube.com&utm_campaign=PythonEngineer * In this part we implement a logistic regression algorithm and apply all the concepts that we have learned so far: - Training Pipeline in PyTorch - Model Design - Loss and Optimizer - Automatic Training steps with forward pass, backward pass, and weight updates Part 08: Logistic Regression 📚 Get my FREE NumPy Handbook: https://www.python-engineer.com/numpybook 📓 Notebooks available on Patreon: https://www.patreon.com/patrickloeber ⭐ Join Our Discord : https://discord.gg/FHMg9tKFSN If you enjoyed this video, please subscribe to the channel! Official website: https://pytorch.org/ Part 01: https://youtu.be/EMXfZB8FVUA Logistic Regression from scratch: https://youtu.be/JDU3AzH3WKg Code for this tutorial series: https://github.com/patrickloeber/pytorchTutorial You can find me here: Website: https://www.python-engineer.com Twitter: https://twitter.com/patloeber GitHub: https://github.com/patrickloeber #Python #DeepLearning #Pytorch ---------------------------------------------------------------------------------------------------------- * This is a sponsored link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you so much for the support! 🙏
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Patrick Loeber · Patrick Loeber · 42 of 60

1 Lists in Python - Advanced Python 01 - Programming Tutorial
Lists in Python - Advanced Python 01 - Programming Tutorial
Patrick Loeber
2 Tuples in Python - Advanced Python 02 - Programming Tutorial
Tuples in Python - Advanced Python 02 - Programming Tutorial
Patrick Loeber
3 Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Dictionaries in Python - Advanced Python 03 - Programming Tutorial
Patrick Loeber
4 Sets in Python - Advanced Python 04 - Programming Tutorial
Sets in Python - Advanced Python 04 - Programming Tutorial
Patrick Loeber
5 Strings in Python - Advanced Python 05 - Programming Tutorial
Strings in Python - Advanced Python 05 - Programming Tutorial
Patrick Loeber
6 Collections in Python - Advanced Python 06 - Programming Tutorial
Collections in Python - Advanced Python 06 - Programming Tutorial
Patrick Loeber
7 Itertools in Python - Advanced Python 07 - Programming Tutorial
Itertools in Python - Advanced Python 07 - Programming Tutorial
Patrick Loeber
8 Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Lambda in Python - Advanced Python 08 - Programming Tutorial - Map Filter Reduce
Patrick Loeber
9 Exceptions in Python - Advanced Python 09 - Programming Tutorial
Exceptions in Python - Advanced Python 09 - Programming Tutorial
Patrick Loeber
10 Logging in Python - Advanced Python 10 - Programming Tutorial
Logging in Python - Advanced Python 10 - Programming Tutorial
Patrick Loeber
11 JSON in Python - Advanced Python 11 - Programming Tutorial
JSON in Python - Advanced Python 11 - Programming Tutorial
Patrick Loeber
12 Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Random Numbers in Python - Advanced Python 12 - Programming Tutorial
Patrick Loeber
13 Decorators in Python - Advanced Python 13 - Programming Tutorial
Decorators in Python - Advanced Python 13 - Programming Tutorial
Patrick Loeber
14 Generators in Python - Advanced Python 14 - Programming Tutorial
Generators in Python - Advanced Python 14 - Programming Tutorial
Patrick Loeber
15 Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Threading vs Multiprocessing in Python - Advanced Python 15 - Programming Tutorial
Patrick Loeber
16 Threading in Python - Advanced Python 16 - Programming Tutorial
Threading in Python - Advanced Python 16 - Programming Tutorial
Patrick Loeber
17 Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Multiprocessing in Python - Advanced Python 17 - Programming Tutorial
Patrick Loeber
18 Function arguments in detail - Advanced Python 18 - Programming Tutorial
Function arguments in detail - Advanced Python 18 - Programming Tutorial
Patrick Loeber
19 The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
The asterisk (*) operator in Python - Advanced Python 19 - Programming Tutorial
Patrick Loeber
20 Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Shallow vs Deep Copying in Python - Advanced Python 20 - Programming Tutorial
Patrick Loeber
21 Context Managers in Python - Advanced Python 21 - Programming Tutorial
Context Managers in Python - Advanced Python 21 - Programming Tutorial
Patrick Loeber
22 KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
KNN (K Nearest Neighbors) in Python - Machine Learning From Scratch 01 - Python Tutorial
Patrick Loeber
23 Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Linear Regression in Python - Machine Learning From Scratch 02 - Python Tutorial
Patrick Loeber
24 Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Logistic Regression in Python - Machine Learning From Scratch 03 - Python Tutorial
Patrick Loeber
25 Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Linear and Logistic Regression in 60 lines of Python - Machine Learning From Scratch 04
Patrick Loeber
26 Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Naive Bayes in Python - Machine Learning From Scratch 05 - Python Tutorial
Patrick Loeber
27 Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Perceptron in Python - Machine Learning From Scratch 06 - Python Tutorial
Patrick Loeber
28 SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
SVM (Support Vector Machine) in Python - Machine Learning From Scratch 07 - Python Tutorial
Patrick Loeber
29 Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Decision Tree in Python Part 1/2 - Machine Learning From Scratch 08 - Python Tutorial
Patrick Loeber
30 Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Decision Tree in Python Part 2/2 - Machine Learning From Scratch 09 - Python Tutorial
Patrick Loeber
31 Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Random Forest in Python - Machine Learning From Scratch 10 - Python Tutorial
Patrick Loeber
32 PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
PCA (Principal Component Analysis) in Python - Machine Learning From Scratch 11 - Python Tutorial
Patrick Loeber
33 K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
K-Means Clustering in Python - Machine Learning From Scratch 12 - Python Tutorial
Patrick Loeber
34 Anaconda Tutorial - Installation and Basic Commands
Anaconda Tutorial - Installation and Basic Commands
Patrick Loeber
35 PyTorch Tutorial 01 - Installation
PyTorch Tutorial 01 - Installation
Patrick Loeber
36 PyTorch Tutorial 02 - Tensor Basics
PyTorch Tutorial 02 - Tensor Basics
Patrick Loeber
37 PyTorch Tutorial 03 - Gradient Calculation With Autograd
PyTorch Tutorial 03 - Gradient Calculation With Autograd
Patrick Loeber
38 PyTorch Tutorial 04 - Backpropagation - Theory With Example
PyTorch Tutorial 04 - Backpropagation - Theory With Example
Patrick Loeber
39 PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
PyTorch Tutorial 05 - Gradient Descent with Autograd and Backpropagation
Patrick Loeber
40 PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer
Patrick Loeber
41 PyTorch Tutorial 07 - Linear Regression
PyTorch Tutorial 07 - Linear Regression
Patrick Loeber
PyTorch Tutorial 08 - Logistic Regression
PyTorch Tutorial 08 - Logistic Regression
Patrick Loeber
43 PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
PyTorch Tutorial 09 - Dataset and DataLoader - Batch Training
Patrick Loeber
44 PyTorch Tutorial 10 - Dataset Transforms
PyTorch Tutorial 10 - Dataset Transforms
Patrick Loeber
45 Download Images With Python Automatically - Python Web Scraping Tutorial
Download Images With Python Automatically - Python Web Scraping Tutorial
Patrick Loeber
46 PyTorch Tutorial 11 - Softmax and Cross Entropy
PyTorch Tutorial 11 - Softmax and Cross Entropy
Patrick Loeber
47 Select Movies with Python - Web Scraping Tutorial
Select Movies with Python - Web Scraping Tutorial
Patrick Loeber
48 PyTorch Tutorial 12 - Activation Functions
PyTorch Tutorial 12 - Activation Functions
Patrick Loeber
49 List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
List Comprehension in Python - A Python Feature You MUST KNOW - Python Tutorial
Patrick Loeber
50 PyTorch Tutorial 13 - Feed-Forward Neural Network
PyTorch Tutorial 13 - Feed-Forward Neural Network
Patrick Loeber
51 How To Add A Progress Bar In Python With Just One Line - Python Tutorial
How To Add A Progress Bar In Python With Just One Line - Python Tutorial
Patrick Loeber
52 PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
PyTorch Tutorial 14 - Convolutional Neural Network (CNN)
Patrick Loeber
53 The Walrus Operator - New in Python 3.8 - Python Tutorial
The Walrus Operator - New in Python 3.8 - Python Tutorial
Patrick Loeber
54 PyTorch Tutorial 15 - Transfer Learning
PyTorch Tutorial 15 - Transfer Learning
Patrick Loeber
55 YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
YouTube Data API Tutorial with Python - Analyze Channel Statistics - Part 1
Patrick Loeber
56 YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
YouTube Data API Tutorial with Python - Find Channel Videos - Part 2
Patrick Loeber
57 YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
YouTube Data API Tutorial with Python - Get Video Statistics - Part 3
Patrick Loeber
58 YouTube Data API Tutorial with Python - Analyze the Data - Part 4
YouTube Data API Tutorial with Python - Analyze the Data - Part 4
Patrick Loeber
59 AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
AdaBoost in Python - Machine Learning From Scratch 13 - Python Tutorial
Patrick Loeber
60 Ultimate FREE Study Guide for Machine Learning and Deep Learning
Ultimate FREE Study Guide for Machine Learning and Deep Learning
Patrick Loeber

This video tutorial teaches how to implement logistic regression using PyTorch, covering data preparation, model definition, and training. It provides a comprehensive introduction to supervised learning and binary classification using PyTorch. By following this tutorial, viewers can learn how to build a logistic regression model using PyTorch and apply it to real-world problems.

Key Takeaways
  1. Load the Breast Cancer dataset from SKLearn
  2. Split the data into training and testing sets
  3. Scale the features using StandardScaler
  4. Convert the data to PyTorch tensors
  5. Reshape the target tensor to a column vector
  6. Define a custom logistic regression model using PyTorch
  7. Set up the model, loss function, and optimizer for training
  8. Define a training loop with forward pass, loss calculation, backward pass, and weight updates
  9. Calculate accuracy using predicted classes and test labels
💡 The sigmoid function is used for binary classification problems, and the Adam optimizer can be used for training the model.

Related AI Lessons

Want to get started with deep learning
Get started with deep learning by leveraging resources like Andrew Karpathy's playlist and frameworks such as TensorFlow or PyTorch
Reddit r/deeplearning
Building a Deepfake Detector From Scratch — What Nobody Tells You
Learn to build a deepfake detector from scratch and understand the challenges involved in detecting AI-generated fake media
Medium · Deep Learning
Unfolding the Meandering Path: High-Dimensional Invariance and the Flat 2D Plane of Neural…
Learn about high-dimensional invariance and its relation to the flat 2D plane of neural networks, and how to apply these concepts to improve model performance
Medium · Deep Learning
Implementing Neural Style Transfer from Scratch: The Project That Started It All
Learn to implement Neural Style Transfer from scratch and understand its significance in deep learning
Medium · Deep Learning
Up next
Image Classification with ml5.js
The Coding Train
Watch →