Build User Input UI with Streamlit

Learn how to take user input in Streamlit.

Taking input from the user

Here we’ll allow the user to input data and display the prediction.

We’ll use the following methods:

  • text_input(str): This method takes a string as a parameter and creates a text input field with the input parameter as its label.

  • st.selectbox(str, options = ): This method creates a drop-down menu. It takes in two parameters, the string to use as the label and the list of options. The options need to be passed as a list of string values.

  • st.slider(str, start, end, step): This creates a slider with the given parameters. The step parameter is considered as the step size of the slider.

The following code is used to take input from user:

name = st.text_input("Name of Passenger ")
sex = st.selectbox("Sex",options=['Male' , 'Female'])
age = st.slider("Age", 1, 100,1)
p_class = st.selectbox("Passenger Class",options=['First Class' , 'Second Class' , 'Third Class'])

Every time the user gives an input, the script is re-run, and the respective variables will store the input values.

Before we can use these values for prediction, we need to scale and modify them.

sex = 0 if sex == 'Male' else 1
f_class , s_class , t_class = 0,0,0
if p_class == 'First Class':
	f_class = 1
elif p_class == 'Second Class':
	s_class = 1
else:
	t_class = 1
input_data = scaler.transform([[sex , age, f_class , s_class, t_class]])
prediction = model.predict(input_data)
predict_probability = model.predict_proba(input_data)
  • First, we set the value of sex to either 0 or 1.
  • Then, we use one-hot encoding on the passenger class.
  • Finally, we scale the input and calculate the prediction and probability.

Get hands-on with 1400+ tech skills courses.