This video demonstrates how to deploy a trained machine learning model using FastAPI by creating a proper project structure with data and model folders, training a Random Forest classifier on the Iris dataset, saving the model as a pickle file, and creating a FastAPI application with Pydantic validation to accept input features and return predictions through a REST API endpoint.
Deploy Machine Learning Models with FastAPI: A Step-by-Step Guide
Added:in this video I will show you how to create a machine learning model and deploy it using fast API we will be following these six steps in step one we will create folder structure we will have folders like data and model in data we will have our CSV file in model we will store our model object in pickle form in main.py we will write flash application code in train.py we will train our machine learning model and in requirement. dxt we will store our libraries or python libraries step two we will install packages from this requirement. txt in step three we will read CSV file from this folder data in step four we will train our machine learning model and we will write the code in train.py this will be script to train the model in step five we will deploy model using fast API in main.py we will write our fast API application code and step six is to test model using fast API how our project and folder structure will look like so we will have a project Nam as Iris classification inside that we will have two folders one is data and the second one is model in data we will save our iris. CSP P file which is going to be used to develop our machine learning model in model we will store our machine learning model as pickle object in main.py we will have fast API application code in train.py we will have our machine learning model training code and in requirement. dxt we will have python libraries that we are going to install if you watch this video till the end you don't have to go anywhere else to learn about model deployment using fast API because we will be covering everything from scratch so let's go to our pycharm and start creating this project let's open pycharm in Windows I will type pyam here you can even use vs code editor it is not necessary that you have to use pyam only now we have to create a new project so I will go here and click on this new project after that you have to give your location my current location is desktop you can select your location from here and maybe you can give C or D drive anyone but for now I'm going to keep it desktop and here in Python project here you see name you have to give your name here so I will write here _ classification and this will be our project folder name then you have to click on this create button you don't have to do anything else just click on this create and this will create a new project for us it is also creating virtual environment automatically so we don't even need to create any virtual environment here now I will just make it full screen and here you can see it has created this project structure Iris classification and this is the virtual environment it has created we don't need this and if you click here you can just close this sub folders now as I have said that we are going to create two folders data and models so let's create then you have to right click here and select new directory and here you have to write directory name first I will write data then let's create second directory again right click new and then directory name the second directory name is model so we have these two directory now in data we will have our CSV file and in model we will have our model. pickle object then we have to create python files first I will create main.py right click new and then python file select this one type main.py you see we have this main.py now let's create train.py python file and then write train.py this we will use to train our machine learning model press enter and now one last file that we create requirements.txt where we will Define the packages that we want to install right click new and then you have to click here just file because this is going to be a text file not a python file and type here requirements dot txt so now we have our project which is _ classification and we also have our folder structure we have data model main.py requirements.txt and train.py now our folder data is empty so we will copy CSV file into this folder I'll go to desktop and this is the project structure or folder iror classification I will open this and inside this I have this folder data and inside this I will paste iris. CSV file so this is the file I have pasted and now let's go back to this Iris classification and let's go back to our pycha and if I open this data I can see iris. CSV file is there so we will be using this file or this data to train our machine learning model now let's first Define the libraries that we are going to install in requirement. dxt so I will double click and it is already open here first I will install fast API second psychic learn then third I have to write it like this Psy learn then third identic this will help us to give suggestions then uvon uon is a server used by fast API to deploy our models then pandas numpy and Jo to read our pickle file now let's open Terminal on the left hand side you will see this option terminal now I'll write here pip install dasr then requirements.txt and you have to remove this Dot and back slash press enter this will install all the libraries that we have in requirement.
dxt you see that it has started downloading it let's wait all the packages are in installed now we will start training our model I will open this train.py and I will import all the libraries that we need import pandas aspd from SK learn dot model selection import train test plate from sklearn do emble import random Forest classifier we will be using this random Forest classifier algorithm from sklearn do metrix import accuracy score and then import Jo now let us read our CSV file so I will write here load data set data I will create a variable data and then from pandas PD do rore CSV I will give the CSV file name which is stored in this directory data so in double codes I will write here data and then Iris do CSV and then we can check this I will print data.
head and I will run this to run it right click here and click run train and here in the output you can see our data frame so if I scroll on the left side you will see that we have SLE length SLE width petal length petal width and species these are these are our features and species is our Target variable we have to predict the class of species and there are three categories in this species class we can check that I will print it so I'll write here print data then species dot value uncore counts and to run it right click and click run train so you see that in the output we got there are three categories setosa ver color and vinica and 50 is the total number of samples in each of these categories so we have these three categories and we have to predict whether the flower belongs to which species now you see that this species column is in string so we have this seta ver and virin but you know that machine learning model only understand numbers they don't understand string so we will convert this string into numbers so let's do that map species to numerical values now I will call our data and then species and then I will call again our data and species then I will call the function map and inside this I will create a dictionary and in this dictionary I will write right first category is satoa you see here this is the first category satoa and we will uh mark this as zero then the second category is versy color and then we will number it as one the last one is virginica and we will number it as two and then we can again print this so I will copy this from here and paste it here and let me print it again so I will run this and now here in the output you see that earlier we had this string satoa ver and vinica and now we have converted it into number 0 1 and two so 0 is for SATA one is for ver col and two is for virginica now we can use this target variable in our classification model so now let's define our features and labels that is our Target variable so I will write here Define features and labels that is X and Y X is our feature and Y is our Target variable so in X we will have all the columns except the last one so I will write here data I will take all the column and drop last one so last column is species I will drop this and then I have to give the AIS AIS is equal to 1 for columns Now by default it is taking this as labels then I will Define Y which is our Target variable data and then we just want species so I will write here species this is our Target variable and now we will split this data set X and Y into train test so X train X test y train y test I will write here split data into training and testing sets first is X train then X test y train and then y test and then we will call this train test split inside this we will pass our X and Y and then test size is going to be let's say 0.2 and random state is equal to let's say 42 you can give any number here this is just for the randomness so that you will get the same sample every time you run this script now let's train our model so we will create an object of our random Forest class I will write here initialize and drain the model so I will make an object model and then I will call this random for class classifier and then I'm going to fit this model on X train and Y train so we have fit this model on our train set now we want to make prediction on our test data that is X test so let's predict it predict so I will make one variable Yore pred where I will save the prediction and then I will call this model from this I will call the method predict and then I want to make prediction on our testing data set that is xcore test and then I can also check this prediction so I will write a print Yore print so let let me execute this script to show you our predictions so you see these are the prediction it says that the flower belongs to one then the second belongs to zero one means what what do you mean by one so you see here one means verol so the first flower belongs to Vera second flower belongs to setosa third belong bels to ver color then fourth belongs to ver color and so on so these are our predicted values now we will do the evaluation to check the accuracy of this model and then we will save this model as our pickle file so let's do the model evaluation model evaluation I will make a variable accuracy and to calculate accuracy I will call this function accuracy score and inside this I will pass over y test to compare it with Y bread and then let's print this accuracy print accuracy and let's run this again to check the accuracy it says 1.0 that means our model is 100% correct so this accuracy is really really too much it is 100% correct now let's save this model as our pickle file for this I will call job job Le dump and inside this I will give our model which is nothing but this model that we have created here so this one this model I'm passing here and then I have to give location where I want to store it so I want to store this in this folder model so I will write here model inside this I want to save this model as a name model. pkl or pickle so right now you see that it is empty and once I run the script you will see we will have model dople object stored in this so I will just run this and now you see that if I expand this so we have this model do PK stored in this folder so what we have done we have trained our model now the last part is to create our fast API application so now we will open our main.py let me close this requir one.
dxt and also close this TR py and I will just open this our main.py so let's first import the libraries that we need from Fast API import fast API then from ptic import base model import J import numai as NP so we have imported all the libraries that we need here and I will also tell you why we are using this Library so penic is used for data validation and settings management with python type annotations and for base model so in the fast API application base model is used to define and validate the request body that you will see as we move step by step so now we will load our train model that we have saved here model. pkl so I will write here load the train model I will make a variable model and then I will call Job Le from this I will call load and then I have to give the path so the path is model this is the directory inside this model. PK so here I'm loading our model and then next we will create an instance of fast API create instance of fast API so I will write here app and then fast API so we have created this instance now we will Define the request body for our input data that is the input features that we will send and based on that we will get our predicted value so let's define that Define the request body for input data all our features or you can say independent variables so I will define a class class predict request and this will take base model that we have imported then inside this we don't have to do anything it's very straightforward what are our independent variables so our independent variables are SLE length SLE width petal length and petal width so let's write down that I will write here SLE underscore length and then we also Define the data type so it is going to be float because it is taking inputs in uh digits then SLE width SLE width data type is going to be float so spelling there is a mistake I will write a with then we have petal length the data type is going to be again float petal underscore width the data type is is again going to be float so we have defined our this base model or our class predict request now we will Define the prediction end point and that's it then we can deploy this using fast API so let's define the prediction end point or the URL where it will go and hit so I will write here Define the prediction end point and then I will call app app is nothing but the object of fast API that we have here so I will write Here app and then we will use the method post and then I will Define the URL here so when I will call this it will go to this page predict and inside this I will Define this predict method so I will write here Define function name is predict and inside this our parameter is going to be request and this request will take this class predict request so I will call this predict request class here and then what we have to do we have to pass these independent variables or these features as arrays and store that in a variable so I will Define a variable data here and then I will call np.
array and inside this I will make a list and inside this I will create a sub list here and then I will call request so we have this request here that we have defined and from this I will call all of these variables dot SLE length and then request dot SLE with then request dot petal length and then request do petal width so I have called all of these features from this request and once I have this data or these features then I will do the prediction and save it in a variable prediction so I will write here prediction here and then I will call to make prediction I will call our model which is stored in this model object if I scroll up you see here okay I have made spelling mistake I have to write here no this is right model okay so I have this model here to make prediction I will call this model and from this I will call the method predict and then I will pass our data this data where we have our features and we will save the prediction in this prediction uh variable and then we will map this because what we will get in prediction we will get 0 1 and two and we want to map it with the original one that is zero is for stoa one is for verol and two is for vinica so I will create species uncore map a new object where I will map this zero is for satoa then one is for verol and then two it is for Virgin so once we get the prediction at0 one and two we will convert them into this original SATA ver and virgin string format and then we will return this return we will return a prediction what we will return we will return this species map and then we will convert this into integer of prediction and then we will take the values at index zero so now when we will call this this will start the server and and you will be able to access your API so before that I'll just add one more thing so that it looks nice when we go to the URL I will write here app.get and this is the URL where we will go and I will Define a function define read uncore ru and then this will return a message and the message will be nothing but welcome to the iris classification API that's it so we have defined our fast API application now we will run this when we will go to the page we will see this welcome to the iris classification API and then there we can test this also so let me run this I hope we will not get any error click on this run main we did not get any error so now let's run this server let's go to this terminal here and here you have to type [Music] uvon main app and you can pass this parameter reload as well let's run it now it says that the app is started and you have to go to this port 8,000 let's click on this so this will open a browser and here you see welcome to the IR classification API so this is inj format and if you click on this raw data you will see here welcome to the iris classification API that we have Define here in this get so and if you click on this headers you will see this response object and this is the Json object welcome to the iris classification API now to test it you can just put a slash here and then write [Music] docs so you will come on this fast API uh this is a Swagger documentation so here you can test your model so now you see here we have this independent variables so let me open this CSV file and we will do the testing now let's go back to our UI and if you click on this predict so you see that these are the independent variables it takes SLE length SLE width petal length petal width and once you give the value you will get the prediction here and then you can click on this get here so you see the code 200 that is successful response here and now we will test it I will click here try it out and now you have to give the values here to make prediction now we are testing it so let's see SE let's say we will take this 10th row number we should get the out outut as satoa so first I will write 4.4 for SLE length I will write here 4.4 for SLE width I will write 2.9 so you have to write here 2.9 then for petal length it is [Music] 1.4 1.4 and then last we have petal with 0.
2 so I will write here 0.2 and to test it you have to click on this execute we click here and now let's see the output so you see the response body prediction and the prediction it is SATA so we got a correct prediction here because this also belongs to satoa class let's try out one one more or two so let's try for this verola uh row number 52 so let's change the value now for simple length we will give seven I will write here seven for then the next value is 3.2 4.7 3 2 then third one is 4.7 and the last one is 1.4 which is petal width 1.4 now let's execute it to check the prediction so the prediction is verol and if you see here so we got the Cur prediction here ver colon you can also click on this reset and then all the values will be reset to zero and you can try it again so you see that how easy it is to deploy your model using fast API and you can also test it you don't need to use Postman or you don't have to write any python script you can just pass your values here and test it you can even go down and explore this what all options here you will see so you have some sttp validation error predict request validation error so if you get any error you will see those error here as well I hope you enjoyed this video if you like my video you can sub subscribe to my channel thank you for watching
Up Next

Docker Crash Course: Virtualization Fundamentals for Beginners
@TechWorldwithNana
2.7M views•2023-02-15

IFS Therapy Demonstration: Complete Session with Unburdening
@IFSCA
95.9K views•2021-01-13

FastAPI vs Flask vs Django: Choosing the Right Python Web Framework
@TechWithTim
302.5K views•2024-05-26

Game of Thrones Opening Credits: A Cinematic Analysis
@gameofthrones
46.3M views•2011-04-18
Related Study Plans & Knowledge Roadmaps
Structured learning paths in General & Interdisciplinary Studies



























![Just Ship It! Deploying Your Dart API with Google Cloud Run [step by step, using Docker]](https://i.ytimg.com/vi/SIDOSAdevWM/maxresdefault.jpg)



![[Dart Backend] Bài 3: Login, register, profile api + Tích hợp JWT + Bảo mật mật khẩu](https://i.ytimg.com/vi/n1VF9Bo3Mbk/maxresdefault.jpg)







