Diabetes Prediction Application using Streamlit | by Himanshu Sharma | Towards Data Science

Streamlit is an open-source Python library which is blazingly fast that makes it easy to build beautiful custom web-apps for machine learning and data science. It is an awesome tool that allows you to create highly interactive dashboards just with some knowledge of python.
Creating applications using streamlit creates an impact on the end-user as it has a good user interface and supports a lot of widgets that are user-friendly. Also creating apps in streamlit is easy. We will create an application using streamlit which will predict whether a user has diabetes or not. The dataset we will be using is PIMA Indian Diabetes Dataset which contains 8 prediction variables and 1 target variable.
Let us look at what are the different attributes in the dataset. The predictor variable is named Outcome which is encoded as 0 and 1 where 0 represents Non-Diabetic and 1 represents Diabetic. Other attributes information is given below.
Let’s start by exploring the dataset we will be using. In order to explore the dataset, we will use a jupyter notebook to load the dataset using pandas and perform exploratory data analysis.
import pandas as pddf = pd.read_csv('Diabetes.csv')df.head()
Heatmap
Heatmap
sns.heatmap(df.corr(),annot=True)
2. Pairplot
sns.pairplot(df,hue='Outcome')
Similarly, we can create many more plots for the EDA process and explore different properties of all the attributes.
We will create the Logistic Regression model in the jupyter notebook and save it so that we can call it in our streamlit app for prediction.
from sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionimport pickle# Split dataset into training set and test setX_train, X_test, y_train, y_test = train_test_split(df[['Pregnancies', 'Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']], df['Outcome'], test_size=0.3, random_state=109)#Creating the modellogisticRegr = LogisticRegression(C=1)logisticRegr.fit(X_train, y_train)y_pred = logisticRegr.predict(X_test)#Saving the Modelpickle_out = open("logisticRegr.pkl", "wb") pickle.dump(logisticRegr, pickle_out) pickle_out.close()
Now let’s start creating the application. In order to create the application, we need to create a script in python and for that, we need to have a code editor installed in our system. You can use any code editor but I personally use Atom because of its features. We will be creating the prediction model using Logistic Regression. Let’s start by importing the required libraries.
import streamlit as stimport pandas as pdimport numpy as npimport plotly.express as pxfrom plotly.subplots import make_subplotsimport plotly.graph_objects as goimport matplotlib.pyplot as pltimport seaborn as snsimport pickle
pickle_in = open('logisticRegr.pkl', 'rb')classifier = pickle.load(pickle_in)
Streamlit has predefined UI for its interface. We will use different widgets to display information and take user inputs for prediction.
st.sidebar.header('Diabetes Prediction')select = st.sidebar.selectbox('Select Form', ['Form 1'], key='1')if not st.sidebar.checkbox("Hide", True, key='1'):    st.title('Diabetes Prediction(Only for females above 21years of    Age)')    name = st.text_input("Name:")    pregnancy = st.number_input("No. of times pregnant:")    glucose = st.number_input("Plasma Glucose Concentration :")    bp =  st.number_input("Diastolic blood pressure (mm Hg):")    skin = st.number_input("Triceps skin fold thickness (mm):")    insulin = st.number_input("2-Hour serum insulin (mu U/ml):")    bmi = st.number_input("Body mass index (weight in kg/(height in m)^2):")    dpf = st.number_input("Diabetes Pedigree Function:")    age = st.number_input("Age:")submit = st.button('Predict')if submit:        prediction = classifier.predict([[pregnancy, glucose, bp, skin, insulin, bmi, dpf, age]])        if prediction == 0:            st.write('Congratulation',name,'You are not diabetic')        else:            st.write(name," we are really sorry to say but it seems like you are Diabetic.")
This will create the application and now we need to save it using the “.py” extension. For example if you need to save your application as “predict” then you need to save it as “predict.py”. In order to launch the application, we will open the Anaconda Command Prompt and type the command given below.
streamlit run predict.py
This will launch our application and now we can use different user inputs to create whether a person has diabetes or not.
By entering different users’ information we can generate different outcomes and see how good and accurate our model is.
This is just an example of what streamlit can do. You can explore more to learn about infinite features that streamlit provide to create web-apps and dashboards. Create your application and share your experiences in the responses of this article.
towardsdatascience.com
towardsdatascience.com
Thanks for reading! If you want to get in touch with me, feel free to reach me on hmix13@gmail.com or my LinkedIn Profile. You can also view the code and data set I have used here in my Github. Also, feel free to explore my profile and read different articles I have written related to Data Science.