Lecture Notes 8
Lecture Notes 8
[In]: model=open("linear_regression_model.pkl","rb")
[In]: lr_model=joblib.load(model)
76
Chapter 3 Machine Learning Deployment as a Web Service
preds=pred_arr.reshape(1,-1)
preds=preds.astype(int)
model_prediction=lr_model.predict(preds)
return model_prediction
In the next step, we create the most important function. We accept the
user input from the browser and render the model’s final predictions on
the web page. We can name this function anything. For example, I have
used run (since it does the same thing as Flask’s app.run). In this function,
we include the front-end code as well such as defining the title, theme,
color, background, etc. For simplicity purposes, I have kept it basic, but this
can have multiple levels of enhancements. For more details, you can visit
the Streamlit website. Next, we create five input variables to accept the user
input values from the browser. This is done using Streamlit’s text_input
capability. The final part contains the model prediction, which gets the
input from our lr_prediction function defined earlier and gets rendered
in the browser through streamlit.button.
"""
streamlit.markdown(html_temp)
var_1=streamlit.text_input("Variable 1")
var_2=streamlit.text_input("Variable 2")
var_3=streamlit.text_input("Variable 3")
var_4=streamlit.text_input("Variable 4")
var_5=streamlit.text_input("Variable 5")
77
Chapter 3 Machine Learning Deployment as a Web Service
prediction=""
if streamlit.button("Predict"):
prediction=lr_prediction(var_1,var_2,var_3,
var_4,var_5)
streamlit.success("The prediction by Model : {}".
format(prediction))
Now that we have all the steps mentioned in the application file, we
can call the main function (run in our case) and use the streamlit run
command to run the app.
[In]: if __name__=='__main__':
run()
[In]: streamlit run app.py
Once we run the previous command, we will soon see the app up and
running on port 8501, as shown in Figure 3-6. We can simply click the link
and access the app.
78
Chapter 3 Machine Learning Deployment as a Web Service
As you can see, we have nothing fancy here in the UI, but it serves the
overall purpose for us to be able to interact with the model/app behind the
scenes. It is similar to what we had built using Flask, but it needed much
less HTML and CSS code. We can now go ahead and fill in the values, as
shown in Figure 3-8, and get the model prediction. For comparison sake,
we fill in the same values that we filled in the Flask-based app.
79