Руководство для начинающих по Streamlit
Тенденция в области науки о данных и аналитики растет день ото дня. В конвейере обработки данных одним из наиболее важных шагов является развертывание модели. У нас есть много вариантов развертывания нашей модели в python. Некоторые популярные фреймворки - это Flask и Django. Но проблема с использованием этих фреймворков заключается в том, что мы должны иметь некоторые знания HTML, CSS и JavaScript. Помня об этих предпосылках, Адриен Трейль, Тьяго Тейшейра и Аманда Келли создали Streamlit. Теперь, используя streamlit, вы можете легко развернуть любую модель машинного обучения и любой проект Python, не беспокоясь о внешнем интерфейсе. Streamlit очень удобен в использовании.
В этой статье мы изучим некоторые важные функции streamlit, создадим проект Python и развернем проект на локальном веб-сервере.
Установим Streamlit. Введите следующую команду в командной строке.
pip install streamlit
После успешной установки Streamlit запустите указанный код python, и если вы не получите сообщение об ошибке, тогда streamlit успешно установлен, и теперь вы можете работать с streamlit.
Как запустить файл Streamlit?
Откройте командную строку или оболочку Anaconda и введите
streamlit run filename.py
Здесь мое имя файла - sample.py. Откройте локальный URL-адрес в веб-браузере.
Понимание основных функций Streamlit
1. Название:
Python3
# import module import streamlit as st # Title st.title( "Hello GeeksForGeeks !!!" ) |
Выход:
2. Заголовок и подзаголовок:
Python
# Header st.header( "This is a header" ) # Subheader st.subheader( "This is a subheader" ) |
Выход:
3. Текст:
Python3
# Text st.text( "Hello GeeksForGeeks!!!" ) |
Выход:
4. Уценка:
Python3
# Markdown st.markdown( "### This is a markdown" ) |
Выход:
5. Успех, информация, предупреждение, ошибка, исключение:
Python3
# success st.success( "Success" ) # success st.info( "Information" ) # success st.warning( "Warning" ) # success st.error( "Error" ) |
Выход:
6. Напишите:
Используя функцию записи, мы также можем отображать код в формате кодирования. Это невозможно при использовании st.text (»).
Python3
# Write text st.write( "Text with write" ) # Writing python inbuilt function range() st.write( range ( 10 )) |
Выход:
7. Отображение изображений:
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 ) |
Выход:
8. Флажок:
Флажок возвращает логическое значение . Когда флажок установлен, возвращается значение True, иначе возвращается значение False.
Python3
# checkbox # check if the checkbox is checked # title of the checkbox is 'Show/Hide' if st.checkbox( "Show/Hide" ): # dispaly the text if the checkbox returns True value st.text( "Showing the widget" ) |
Выход:
9. Радиокнопка:
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" ) |
Выход:
10. Поле выбора:
Вы можете выбрать любой вариант в поле выбора.
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) |
Выход:
11. Множественный выбор:
Поле с множественным выбором возвращает результат в виде списка. Вы можете выбрать несколько вариантов.
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' ) |
Выход:
12. Кнопка:
st.button () возвращает логическое значение . Он возвращает значение True при нажатии, иначе возвращает False .
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!!!" ) |
Выход:
13. Ввод текста:
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) |
Выход:
14. Ползунок:
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" ) |
Выход:
Высота в метрах:
Высота в футах:
Заключение
Таким образом, мы можем использовать streamlit для развертывания наших проектов, не зная HTML, CSS или JavaScript.
Примечание: Streamlit все еще находится в стадии разработки, и команда предлагает новые концепции.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.