A Machine Learning project is never really complete if we don’t have a good way to showcase it.
While in the past, a well-made visualization or a small PPT used to be enough for showcasing a data science project, with the advent of dashboarding tools like RShiny and Dash, a good data scientist needs to have a fair bit of knowledge of web frameworks to get along.
Not to mention the many ways to do the same thing, making it confusing for us data science folks for whom web development is a secondary skill.
So, are we doomed to learn web frameworks? Or to call our developer friend for silly doubts in the middle of the night?
This is where StreamLit comes in and delivers on its promise to create web apps just using Python.
Zen of Python: Simple is better than complex and Streamlit makes it dead simple to create apps.
This post is about understanding how to create apps that support data science projects using Streamlit.
To understand more about the architecture and the thought process that led to streamlit, have a look at this excellent Turn Python Scripts into Beautiful Machine Learning Tools.
Installation is as simple as running the command:
pip install streamlit
To see if our installation is successful, we can just run:
This should show you a screen that says:
You can go to the local URL:
localhost:8501 in your browser to see a Streamlit app in action. The developers have provided some cool demos that you can play with. Do take your time and feel the power of the tool before coming back.
Streamlit aims to make app development easy using simple Python.
So let us write a simple app to see if it delivers on that promise.
Here I start with a simple app which we will call the Hello World of streamlit. Just paste the code given below in a file named
import streamlit as stx = st.slider('x') st.write(x, 'squared is', x * x)
And, on the terminal run:
streamlit run helloworld.py
And voila, you should be able to see a simple app in action in your browser at
localhost:8501 that allows you to move a slider and gives the result.
It was pretty easy. In the above app, we used two features from Streamlit:
st.sliderwidget that we can slide to change the output of the web app.
st.writecommand. I am amazed at how it can write anything from charts, dataframes, and simple text. More on this later.
Important: Remember that every time we change the widget value, the whole app runs from top to bottom.
Widgets provide us a way to control our app. The best place to read about the widgets is the API reference documentation itself but I will describe some most prominent ones that you might end up using.
streamlit.slider(label, min_value=None, max_value=None, value=None, step=None, format=None)
We already saw
st.slider in action above. It can be used with min_value,max_value, and step for getting inputs in a range.
The simplest way to get user input be it some URL input or some text input for sentiment analysis. It just needs a single label for naming the textbox.
import streamlit as sturl = st.text_input('Enter URL') st.write('The Entered URL is', url)
This is how the app looks:
Tip: You can just change the file
helloworld.py and refresh the browser. The way I work is to open and change
helloworld.py in sublime text and see the changes in the browser side by side.
One use case for checkboxes is to hide or show/hide a specific section in an app. Another could be setting up a boolean value in the parameters for a function.
[st.checkbox()](https://streamlit.io/docs/api.html#streamlit.checkbox) takes a single argument, which is the widget label. In this app, the checkbox is used to toggle a conditional statement.
import streamlit as st import pandas as pd import numpy as npdf = pd.read_csv("football_data.csv") if st.checkbox('Show dataframe'): st.write(df)
We can use
[st.selectbox](https://streamlit.io/docs/api.html#streamlit.selectbox) to choose from a series or a list. Normally a use case is to use it as a simple dropdown to select values from a list.
import streamlit as st import pandas as pd import numpy as npdf = pd.read_csv("football_data.csv")option = st.selectbox( 'Which Club do you like best?', df['Club'].unique())'You selected: ', option
We can also use multiple values from a dropdown. Here we use
st.multiselect to get multiple values as a list in the variable
import streamlit as st import pandas as pd import numpy as npdf = pd.read_csv("football_data.csv")options = st.multiselect( 'What are your favorite clubs?', df['Club'].unique())st.write('You selected:', options)
So much for understanding the important widgets. Now, we are going to create a simple app using multiple widgets at once.
To start simple, we will try to visualize our football data using streamlit. It is pretty much simple to do this with the help of the above widgets.
import streamlit as st import pandas as pd import numpy as npdf = pd.read_csv("football_data.csv")clubs = st.multiselect('Show Player for clubs?', df['Club'].unique())nationalities = st.multiselect('Show Player from Nationalities?', df['Nationality'].unique())# Filter dataframe new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))]# write dataframe to screen st.write(new_df)
Our simple app looks like:
That was easy. But it seems pretty basic right now. Can we add some charts?
Streamlit currently supports many libraries for plotting. Plotly, Bokeh, Matplotlib, Altair, and Vega charts being some of them. Plotly Express also works, although they didn’t specify it in the docs. It also has some inbuilt chart types that are “native” to Streamlit, like
We will work with
plotly_express here. Here is the code for our simple app. We just used four calls to streamlit. Rest is all simple python.
import streamlit as st import pandas as pd import numpy as np import plotly_express as pxdf = pd.read_csv("football_data.csv")clubs = st.multiselect('Show Player for clubs?', df['Club'].unique()) nationalities = st.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))] st.write(new_df)# create figure using plotly express fig = px.scatter(new_df, x ='Overall',y='Age',color='Name')# Plot! st.plotly_chart(fig)
In the start we said that each time we change any widget, the whole app runs from start to end. This is not feasible when we create apps that will serve deep learning models or complicated machine learning models. Streamlit covers us in this aspect by introducing Caching.
In our simple app. We read the pandas dataframe again and again whenever a value changes. While it works for the small data we have, it will not work for big data or when we have to do a lot of processing on the data. Let us use caching using the
st.cache decorator function in streamlit like below.
import streamlit as st import pandas as pd import numpy as np import plotly_express as pxdf = st.cache(pd.read_csv)("football_data.csv")
Or for more complex and time taking functions that need to run only once, using:
@st.cache def complex_func(a,b): DO SOMETHING COMPLEX# Won't run again and again. complex_func(a,b)
When we mark a function with Streamlit’s cache decorator, whenever the function is called streamlit checks the input parameters that you called the function with.
If this is the first time Streamlit has seen these params, it runs the function and stores the result in a local cache.
When the function is called the next time, if those params have not changed, Streamlit knows it can skip executing the function altogether. It just uses the results from the cache.
For a cleaner look based on your preference, you might want to move your widgets into a sidebar, something like Rshiny dashboards. This is pretty simple. Just add
**_st.sidebar_** in your widget’s code.
import streamlit as st import pandas as pd import numpy as np import plotly_express as pxdf = st.cache(pd.read_csv)("football_data.csv")clubs = st.sidebar.multiselect('Show Player for clubs?', df['Club'].unique()) nationalities = st.sidebar.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))] st.write(new_df)# Create distplot with custom bin_size fig = px.scatter(new_df, x ='Overall',y='Age',color='Name')# Plot! st.plotly_chart(fig)
I love writing in Markdown. I find it less verbose than HTML and much more suited for data science work. So, can we use Markdown with the streamlit app?
Yes, we can. There are a couple of ways to do this. In my view, the best one is to use Magic commands. Magic commands allow you to write markdown as easily as comments. You could also have used the command
import streamlit as st import pandas as pd import numpy as np import plotly_express as px''' # Club and Nationality AppThis very simple webapp allows you to select and visualize players from certain clubs and certain nationalities. ''' df = st.cache(pd.read_csv)("football_data.csv")clubs = st.sidebar.multiselect('Show Player for clubs?', df['Club'].unique()) nationalities = st.sidebar.multiselect('Show Player from Nationalities?', df['Nationality'].unique())new_df = df[(df['Club'].isin(clubs)) & (df['Nationality'].isin(nationalities))] st.write(new_df)# Create distplot with custom bin_size fig = px.scatter(new_df, x ='Overall',y='Age',color='Name')''' ### Here is a simple chart between player age and overall '''st.plotly_chart(fig)
Streamlit has democratized the whole process to create apps, and I couldn’t recommend it more.
In this post, we created a simple web app. But the possibilities are endless. To give an example here is face GAN from the streamlit site. And it works by just using the same guiding ideas of widgets and caching.
I love the default colors and styles that the developers have used, and I found it much more comfortable than using Dash, which I was using until now for my demos. You can also include audio and video in your streamlit apps.
On top of that, Streamlit is a free and open-source rather than a proprietary web app that just works out of the box.
I don’t have an idea if it will perform well in a production environment yet, but its a boon for the small proof of concept projects and demos. I aim to use it more in my workflow from now on, and considering the capabilities it provides without all the hard work, I think you should too.
You can find the full code for the final app here.
#python #data-science #deep-learning #machine-learning #artificial-intelligence
Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.
#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners
At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.
In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.
Table of Contents hide
The Size and declared value and its sequence of the object can able to be modified called mutable objects.
Mutable Data Types are list, dict, set, byte array
The Size and declared value and its sequence of the object can able to be modified.
Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.
id() and type() is used to know the Identity and data type of the object
a**=str(“Hello python world”)****#str**
Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.
Python supports 3 types of numeric data.
int (signed integers like 20, 2, 225, etc.)
float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)
complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)
A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).
The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.
# String Handling
#single (') Quoted String
# Double (") Quoted String
# triple (‘’') (“”") Quoted String
In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.
The operator “+” is used to concatenate strings and “*” is used to repeat the string.
'Output : Python python ’
#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type
If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.
If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.
In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.
#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition
AppClues Infotech is one of the leading Python app development company in USA. We are a one-stop solutions provider for mobile consulting, experience design, app development, IoT development, and cloud solutions for businesses varying in size from start-up to enterprise.
Our Python App Development Solutions
• Machine Learning Solutions
• Custom Python Development
• Python Mobile App Development
• Python CMS Development
• Python Up-gradation & Migration
• Django Framework Development
#python app development #top python app development company in usa #hire python app developers in usa #how to develop python mobile app #best python app development services #custom python app development
With more of us using smartphones, the popularity of mobile applications has exploded. In the digital era, the number of people looking for products and services online is growing rapidly. Smartphone owners look for mobile applications that give them quick access to companies’ products and services. As a result, mobile apps provide customers with a lot of benefits in just one device.
Likewise, companies use mobile apps to increase customer loyalty and improve their services. Mobile Developers are in high demand as companies use apps not only to create brand awareness but also to gather information. For that reason, mobile apps are used as tools to collect valuable data from customers to help companies improve their offer.
There are many types of mobile applications, each with its own advantages. For example, native apps perform better, while web apps don’t need to be customized for the platform or operating system (OS). Likewise, hybrid apps provide users with comfortable user experience. However, you may be wondering how long it takes to develop an app.
To give you an idea of how long the app development process takes, here’s a short guide.
_Average time spent: two to five weeks _
This is the initial stage and a crucial step in setting the project in the right direction. In this stage, you brainstorm ideas and select the best one. Apart from that, you’ll need to do some research to see if your idea is viable. Remember that coming up with an idea is easy; the hard part is to make it a reality.
All your ideas may seem viable, but you still have to run some tests to keep it as real as possible. For that reason, when Web Developers are building a web app, they analyze the available ideas to see which one is the best match for the targeted audience.
Targeting the right audience is crucial when you are developing an app. It saves time when shaping the app in the right direction as you have a clear set of objectives. Likewise, analyzing how the app affects the market is essential. During the research process, App Developers must gather information about potential competitors and threats. This helps the app owners develop strategies to tackle difficulties that come up after the launch.
The research process can take several weeks, but it determines how successful your app can be. For that reason, you must take your time to know all the weaknesses and strengths of the competitors, possible app strategies, and targeted audience.
The outcomes of this stage are app prototypes and the minimum feasible product.
#android app #frontend #ios app #minimum viable product (mvp) #mobile app development #web development #android app development #app development #app development for ios and android #app development process #ios and android app development #ios app development #stages in app development