Skip to main content

deploying Machine learning Model : pkl, Flask,postman

1)Create model and train 

        #  importing Librarys

        import pandas as pd
        import numpy as np
        import matplotlib.pyplot as plt
        import seaborn as sns
        import requests
        from pickle import dump,load

        # Load Dataset

        url="http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"

        names = ["sepal_length", "sepal_width", "petal_length", "petal_width", "species"]

        # Loading Dataset
        df=pd.read_csv(url,names=names)

        df.tail(11)

        df.columns
        test=[
        {'sepal_length':5.1, 'sepal_width':3.5, 'petal_length':1.4, 'petal_width':0.2},
            {'sepal_length':6.9, 'sepal_width':3.1, 'petal_length':5.4, 'petal_width':2.1}
        ]

        df.info()

        # Checking null values
        df.isna().sum()

        df.describe()

        # visulization

        plt.figure(figsize=(10,8))
        sns.scatterplot(x='sepal_length',y='sepal_width',data=df,hue='species')

        plt.hist(df['species'])

        # Label Encoding



        # Selecting dependent and indepedent variable
        x=df.drop('species',axis=1)
        y=df['species']

        # split data

        from sklearn.model_selection import train_test_split
        xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.2,random_state=0)

        # fit and train model

        from sklearn.ensemble import RandomForestClassifier
        model=RandomForestClassifier()
        model.fit(xtrain,ytrain)

        ypred=model.predict(xtest)

        from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
        print("accuray is: ",accuracy_score(ytest,ypred))
        cm=confusion_matrix(ytest,ypred)
        sns.heatmap(cm,annot=True)
        print(classification_report(ytest,ypred))



        # conclusion:
        #In this task we have we explored the iris dataset and predicted the classification using RandomForestClassifier algorithm.

        dump(model,open('model.pkl','wb'))

2) Create Flask app (filenae=app.py)

        import pickle

        #create flask app
        app= Flask(__name__)

        #Load the picke model
        model=pickle.load(open('model.pkl','rb'))

        @app.route('/predict', methods = ['POST'])
        def predict():
            json_ = request.json
            query_df =  pd.DataFrame(json_)
            prediction = model.predict(query_df)
            return jsonify({"Prediction":list(prediction)})



        if __name__ == "__main__":
            app.run(debug=True)


3) Using postman we can deploy test












Popular posts from this blog

Binomial Distribution

  The binomial distribution formula is:                                                    b(x; n, P) =  n C x  * P x  * (1 – P) n – x Where: b = binomial probability x = total number of “successes” (pass or fail, heads or tails etc.) P = probability of a success on an individual trial n = number of trials Note:  The binomial distribution formula can also be written in a slightly different way, because  n C x  = n! / x!(n – x)! (this binomial distribution formula uses factorials  (What is a factorial? ). “q” in this formula is just the probability of failure (subtract your probability of success from 1). Using the First Binomial Distribution Formula The binomial distribution formula can calculate the probability of success for binomial distributions. Often you’ll be told to “plug in” the numbers to the  formul...

cammand for installing library in python

 Command for installing in jupyter notebook:                pip install library_name                ex. pip install nump installing from anaconda prompt:           1. pip install numpy           2.   conda install -c conda-forge matplotlib search for conda command for matplotlib and go to official website. Installing from anaconda navigator easy. Somtime give error then open as administrator