📜  Streamlit 初学者指南

📅  最后修改于: 2022-05-13 01:55:50.110000             🧑  作者: Mango

Streamlit 初学者指南

数据科学和分析的趋势与日俱增。在数据科学管道中,最重要的步骤之一是模型部署。我们在Python中有很多选项来部署我们的模型。一些流行的框架是 Flask 和 Django。但是使用这些框架的问题是我们应该对 HTML、CSS 和 JavaScript 有一些了解。牢记这些先决条件,Adrien Treuille、Thiago Teixeira 和 Amanda Kelly 创建了“Streamlit”。现在使用 streamlit,您可以轻松部署任何机器学习模型和任何Python项目,而无需担心前端。 Streamlit 非常人性化。

在本文中,我们将学习streamlit 的一些重要功能,创建一个Python项目,并将项目部署到本地Web 服务器上。

让我们安装streamlit。在命令提示符中键入以下命令。

pip install streamlit

Streamlit 安装成功后,运行给定的Python代码,如果没有出现错误,则表示 streamlit 安装成功,您现在可以使用 streamlit。

如何运行Streamlit文件?

打开命令提示符或 Anaconda shell 并输入

streamlit run filename.py

运行Streamlit文件

这里我的文件名是“sample.py”。在 Web 浏览器中打开本地 URL。

了解Streamlit基本功能

1. 标题:

Python3
# import module
import streamlit as st
 
# Title
st.title("Hello GeeksForGeeks !!!")


Python
# Header
st.header("This is a header")
 
# Subheader
st.subheader("This is a subheader")


Python3
# Text
st.text("Hello GeeksForGeeks!!!")


Python3
# Markdown
st.markdown("### This is a markdown")


Python3
# success
st.success("Success")
 
# success
st.info("Information")
 
# success
st.warning("Warning")
 
# success
st.error("Error")


Python3
# Write text
st.write("Text with write")
 
# Writing python inbuilt function range()
st.write(range(10))


Python3
# Diaplay Images
 
# import Image from pillow to open images
from PIL import Image
img = Image.open("streamlit.png")
 
# display image using streamlit
# width is used to set the width of an image
st.image(img, width=200)


Python3
# checkbox
# check if the checkbox is checked
# title of the checkbox is 'Show/Hide'
if st.checkbox("Show/Hide"):
   
  # display the text if the checkbox returns True value
  st.text("Showing the widget")


Python3
# radio button
# first argument is the title of the radio button
# second argument is the options for the ratio button
status = st.radio("Select Gender: ", ('Male', 'Female'))
 
# conditional statement to print
# Male if male is selected else print female
# show the result using the success function
if (status == 'Male'):
    st.success("Male")
else:
    st.success("Female")


Python3
# Selection box
 
# first argument takes the titleof the selectionbox
# second argument takes options
hobby = st.selectbox("Hobbies: ",
                     ['Dancing', 'Reading', 'Sports'])
 
# print the selected hobby
st.write("Your hobby is: ", hobby)


Python3
# multi select box
 
# first argument takes the box title
# second argument takes the options to show
hobbies = st.multiselect("Hobbies: ",
                         ['Dancing', 'Reading', 'Sports'])
 
# write the selected options
st.write("You selected", len(hobbies), 'hobbies')


Python3
# Create a simple button that does nothing
st.button("Click me for no reason")
 
# Create a button, that when clicked, shows a text
if(st.button("About")):
    st.text("Welcome To GeeksForGeeks!!!")


Python3
# Text Input
 
# save the input text in the variable 'name'
# first argument shows the title of the text input box
# second argument displays a default text inside the text input area
name = st.text_input("Enter Your name", "Type Here ...")
 
# display the name when the submit button is clicked
# .title() is used to get the input text string
if(st.button('Submit')):
    result = name.title()
    st.success(result)


Python3
# slider
 
# first argument takes the title of the slider
# second argument takes thr starting of the slider
# last argument takes the end number
level = st.slider("Select the level", 1, 5)
 
# print the level
# format() is used to print value
# of a variable at a specific position
st.text('Selected: {}'.format(level))


Python3
# import the streamlit library
import streamlit as st
 
# give a title to our app
st.title('Welcome to BMI Calculator')
 
# TAKE WEIGHT INPUT in kgs
weight = st.number_input("Enter your weight (in kgs)")
 
# TAKE HEIGHT INPUT
# radio button to choose height format
status = st.radio('Select your height format: ',
                  ('cms', 'meters', 'feet'))
 
# compare status value
if(status == 'cms'):
    # take height input in centimeters
    height = st.number_input('Centimeters')
     
    try:
        bmi = weight / ((height/100)**2)
    except:
        st.text("Enter some value of height")
         
elif(status == 'meters'):
    # take height input in meters
    height = st.number_input('Meters')
     
    try:
        bmi = weight / (height ** 2)
    except:
        st.text("Enter some value of height")
         
else:
    # take height input in feet
    height = st.number_input('Feet')
     
    # 1 meter = 3.28
    try:
        bmi = weight / (((height/3.28))**2)
    except:
        st.text("Enter some value of height")
 
# check if the button is pressed or not
if(st.button('Calculate BMI')):
     
    # print the BMI INDEX
    st.text("Your BMI Index is {}.".format(bmi))
     
    # give the interpretation of BMI index
    if(bmi < 16):
        st.error("You are Extremely Underweight")
    elif(bmi >= 16 and bmi < 18.5):
        st.warning("You are Underweight")
    elif(bmi >= 18.5 and bmi < 25):
        st.success("Healthy")       
    elif(bmi >= 25 and bmi < 30):
        st.warning("Overweight")
    elif(bmi >= 30):
        st.error("Extremely Overweight")


输出:

标题

2. 标题和副标题:

Python

# Header
st.header("This is a header")
 
# Subheader
st.subheader("This is a subheader")

输出:

标题/副标题

3.文字:

蟒蛇3

# Text
st.text("Hello GeeksForGeeks!!!")

输出:

文本

4.降价:

蟒蛇3

# Markdown
st.markdown("### This is a markdown")

输出:

降价

5. 成功、信息、警告、错误、异常:

蟒蛇3

# success
st.success("Success")
 
# success
st.info("Information")
 
# success
st.warning("Warning")
 
# success
st.error("Error")

输出:

成功、信息、警告和错误

6. 写:

使用 write函数,我们还可以以编码格式显示代码。使用 st.text(") 是不可能的。

蟒蛇3

# Write text
st.write("Text with write")
 
# Writing python inbuilt function range()
st.write(range(10))

输出:

写()函数

7. 显示图像:

蟒蛇3

# Diaplay Images
 
# import Image from pillow to open images
from PIL import Image
img = Image.open("streamlit.png")
 
# display image using streamlit
# width is used to set the width of an image
st.image(img, width=200)

输出:

使用 streamlit 显示图像

8. 复选框:

复选框返回一个布尔值。当该框被选中时,它返回一个True值,否则返回一个False值。

蟒蛇3

# checkbox
# check if the checkbox is checked
# title of the checkbox is 'Show/Hide'
if st.checkbox("Show/Hide"):
   
  # display the text if the checkbox returns True value
  st.text("Showing the widget")

输出:

复选框未选中

选中该框时显示文本

9. 单选按钮:

蟒蛇3

# radio button
# first argument is the title of the radio button
# second argument is the options for the ratio button
status = st.radio("Select Gender: ", ('Male', 'Female'))
 
# conditional statement to print
# Male if male is selected else print female
# show the result using the success function
if (status == 'Male'):
    st.success("Male")
else:
    st.success("Female")

输出:

选择男性选项时,成功显示男性

选择女性选项时,成功显示女性

10.选择框:

您可以从选择框中选择任何一个选项。

蟒蛇3

# Selection box
 
# first argument takes the titleof the selectionbox
# second argument takes options
hobby = st.selectbox("Hobbies: ",
                     ['Dancing', 'Reading', 'Sports'])
 
# print the selected hobby
st.write("Your hobby is: ", hobby)

输出:

选择框显示可供选择的选项

打印所选选项

11. 多选框:

多选框以列表的形式返回输出。您可以选择多个选项。

蟒蛇3

# multi select box
 
# first argument takes the box title
# second argument takes the options to show
hobbies = st.multiselect("Hobbies: ",
                         ['Dancing', 'Reading', 'Sports'])
 
# write the selected options
st.write("You selected", len(hobbies), 'hobbies')

输出:

多选框

选择了 2 个选项

12. 按钮:

st.button() 返回一个布尔值。单击时返回True值,否则返回False

蟒蛇3

# Create a simple button that does nothing
st.button("Click me for no reason")
 
# Create a button, that when clicked, shows a text
if(st.button("About")):
    st.text("Welcome To GeeksForGeeks!!!")

输出:

点击第一个按钮

单击关于按钮

13. 文字输入:

蟒蛇3

# Text Input
 
# save the input text in the variable 'name'
# first argument shows the title of the text input box
# second argument displays a default text inside the text input area
name = st.text_input("Enter Your name", "Type Here ...")
 
# display the name when the submit button is clicked
# .title() is used to get the input text string
if(st.button('Submit')):
    result = name.title()
    st.success(result)

输出:

文本输入

单击提交按钮时显示成功消息

14.滑块:

蟒蛇3

# slider
 
# first argument takes the title of the slider
# second argument takes thr starting of the slider
# last argument takes the end number
level = st.slider("Select the level", 1, 5)
 
# print the level
# format() is used to print value
# of a variable at a specific position
st.text('Selected: {}'.format(level))

输出:

滑块

迷你项目:

让我们回忆一下上面学到的所有内容并创建一个 BMI 计算器网络应用程序。

当体重以公斤为单位,身高以米为单位时,BMI指数的计算公式为:

bmi = weight/height^2

蟒蛇3

# import the streamlit library
import streamlit as st
 
# give a title to our app
st.title('Welcome to BMI Calculator')
 
# TAKE WEIGHT INPUT in kgs
weight = st.number_input("Enter your weight (in kgs)")
 
# TAKE HEIGHT INPUT
# radio button to choose height format
status = st.radio('Select your height format: ',
                  ('cms', 'meters', 'feet'))
 
# compare status value
if(status == 'cms'):
    # take height input in centimeters
    height = st.number_input('Centimeters')
     
    try:
        bmi = weight / ((height/100)**2)
    except:
        st.text("Enter some value of height")
         
elif(status == 'meters'):
    # take height input in meters
    height = st.number_input('Meters')
     
    try:
        bmi = weight / (height ** 2)
    except:
        st.text("Enter some value of height")
         
else:
    # take height input in feet
    height = st.number_input('Feet')
     
    # 1 meter = 3.28
    try:
        bmi = weight / (((height/3.28))**2)
    except:
        st.text("Enter some value of height")
 
# check if the button is pressed or not
if(st.button('Calculate BMI')):
     
    # print the BMI INDEX
    st.text("Your BMI Index is {}.".format(bmi))
     
    # give the interpretation of BMI index
    if(bmi < 16):
        st.error("You are Extremely Underweight")
    elif(bmi >= 16 and bmi < 18.5):
        st.warning("You are Underweight")
    elif(bmi >= 18.5 and bmi < 25):
        st.success("Healthy")       
    elif(bmi >= 25 and bmi < 30):
        st.warning("Overweight")
    elif(bmi >= 30):
        st.error("Extremely Overweight")

输出:

计算 BMI Indec,场景 1

以米为单位的高度:

计算 BMI Indec,场景 2

身高(英尺):

计算 BMI Indec,场景 3

结论

这样我们就可以使用 streamlit 来部署我们的项目,而无需任何 HTML、CSS 或 JavaScript 知识。

注意: Streamlit 仍在开发中,团队正在引入新概念。