Пример #1
0
    st.write(oreg)
    st.write(wa)

if add_selectbox == "Home":
    homePage()

if add_selectbox == "All Locations":
    allLocations()

if add_selectbox == "Map":
    mapLocations()

if add_selectbox == "Locations by Region":
    st.header("Locations by Region")
    option = st.selectbox(
        "Please pick a region to display locations for.",
        ('Northeast', 'Midwest', 'South', 'West'))
    if option == 'Northeast':
        northeastOption()
    if option == 'Midwest':
        midwestOption()
    if option == 'South':
        southOption()
    if option == 'West':
        westOption()

if add_selectbox == "Graphs":
    graphStores()


st.line_chart(chart_data)

map_data = pd.DataFrame(np.random.randn(1000, 2), columns=['lat', 'lon'])
st.map(map_data)

if st.checkbox("Show dataframe"):
    chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])
    chart_data

df = pd.DataFrame({
    'First column': [1, 2, 3, 4],
    'Second column': [10, 20, 30, 40]
})
st.write(df.head())

option = st.selectbox('Which number', df['First column'])
st.write('You selected: ', option)

#
option = st.sidebar.selectbox('Which number do you best?', df['First column'])

# st.sidebar.markdown()
#
# st.sidebar.slider()
#
# st.sidebar.line_chart()

left_column, right_column = st.beta_columns(2)
pressed = left_column.button('Press me?')
if pressed:
    right_column.write("You have pressed")
Пример #3
0
    "זלוטי פולני - PLN": "PLN",
    "לב בולגרי - BGN": "BGN",
    "לירה טורקית חדשה - TRY": "TRY",
    "יואן סיני - CNY": "CNY",
    "כתר נורבגי - NOK": "NOK",
    "דולר ניו זילנדי - NZD": "NZD",
    "ראנד דרום אפריקאי - ZAR": "ZAR",
    "דולר אמריקאי - USD": "USD",
    "פסו מקסיקני - MXN": "MXN",
    "שקל ישראלי - NIS": "ILS",
    "לירה שטרלינג - GBP": "GBP",
    "וון דרום קוראני - KRW": "KRW",
    "רינגיט מלזי - MYR": "MYR"
}

data = return_rate()
st.title('מחשבון המרה')
st.subheader(f'{data[1]} שערי מטבע מעודכנים נכון לתאריך')

amount = st.number_input('בחרו סכום',
                         min_value=0,
                         max_value=None,
                         value=0,
                         step=1)
from_coin = st.selectbox(':אני רוצה להמיר את הסכום ממטבע', list(coins))
to_coin = st.selectbox(':למטבע', list(coins))
btn = st.button('בצע המרה')
if btn:
    data = return_rate(coins[from_coin], coins[to_coin])
    st.header(round(amount * data[0], 2))
    st.subheader(to_coin.split(' -')[0])
def main():
    st.title('APS Regressão Linear ')
    st.text(
        'Gabriel Oliveira Ramos do Nascimento RA: 21022939 \nJackson do Nascimento Silva RA: 21022770 \nLaura  Damaceno de Almeida  RA: 20964736 \nVictor Hugo Kawabata Fuzaro RA: 20760102'
    )
    st.image('image.png', width=900)
    file = st.file_uploader('Escolha seu arquivo', type='csv')

    if file is not None:
        slider = st.slider('Quantidade de linhas', 0, 100)
        df = pd.read_csv(file)
        st.dataframe(df.head(slider))
        st.markdown('**Nome das colunas**')
        st.write(df.columns)
        st.markdown('**Número de linhas**')
        st.write(df.shape[0])
        st.markdown('**Número de colunas**')
        st.write(df.shape[1])
        exploracao = pd.DataFrame({
            'nomes': df.columns,
            'tipos': df.dtypes,
            'NA #': df.isna().sum(),
            'NA %': df.isna().sum() / df.shape[0] * 100
        })
        st.markdown('**Contagem dos tipos de dados**')
        st.write(exploracao.tipos.value_counts())
        st.markdown('**Nome das colunas do tipo int64**')
        st.markdown(list(exploracao[exploracao['tipos'] == 'int64']['nomes']))
        st.markdown('**Nomes das colunas do tipo float64:**')
        st.markdown(list(
            exploracao[exploracao['tipos'] == 'float64']['nomes']))
        st.markdown('**Nomes das colunas do tipo object:**')
        st.markdown(list(exploracao[exploracao['tipos'] == 'object']['nomes']))
        st.markdown('**Tabela com coluna e percentual de dados faltantes :**')
        st.table(exploracao[exploracao['NA #'] != 0][['tipos', 'NA %']])
        st.markdown('**Descrição dos dados :**')

        st.table(df.describe())
        opcoes = df.columns
        aux = pd.DataFrame({"coluna": df.columns, "tipos": df.dtypes})
        colunas_numericas = list(aux[aux['tipos'] != 'object']['coluna'])
        st.subheader('Estatística descritiva')

        col = st.selectbox('Selecione a coluna', colunas_numericas)
        if (col is not None):
            st.markdown('Selecione o que deseja analisar')
            mean = st.checkbox('Média')
            if mean:
                st.markdown(df[col].mean())
            mediana = st.checkbox('Mediana')
            if mediana:
                st.markdown(df[col].median())
            desvio_padrao = st.checkbox('Desvio Padrão')
            if desvio_padrao:
                st.markdown(df[col].std())
            kurtosis = st.checkbox('Kurtosis')
            if kurtosis:
                st.markdown(df[col].kurtosis())
            skewness = st.checkbox('Skewness')
        if skewness:
            st.markdown(df[col].skew())
        st.subheader('Visualização dos dados')
        selected_atributos = st.multiselect('Selecione os atributos', opcoes)
        type_visualize = st.selectbox('Selecione o tipo de visualização', [
            'selecione', 'boxplot', 'scatter plot', 'barchart', 'histograma',
            'Matriz de correlação'
        ])

        df.dropna(inplace=True)
        if (len(selected_atributos) > 2):
            st.markdown('Selecione no máximo 2 atributos')
        if (len(selected_atributos) <= 2):
            if (type_visualize == 'barchart'):
                plot_data = df[selected_atributos[0]]
                st.bar_chart(plot_data)
            if (type_visualize == 'boxplot'):
                if (len(selected_atributos) == 1):
                    fig = px.box(df,
                                 y=selected_atributos[0],
                                 hover_data=['Country'])
                    #df.boxplot([selected_atributos[0]])
                else:
                    fig = px.box(df,
                                 x=selected_atributos[0],
                                 y=selected_atributos[1],
                                 hover_data=['Country'])
                    #df.boxplot([selected_atributos[0]], by=[selected_atributos[1]])
                #st.pyplot()
                st.plotly_chart(fig)
            if (type_visualize == 'scatter plot'):
                if (len(selected_atributos) == 1):
                    fig = px.scatter(df,
                                     x=selected_atributos[0],
                                     hover_data=['Country'])
                    st.plotly_chart(fig, use_container_width=True)

                if (len(selected_atributos) == 2):
                    fig = px.scatter(df,
                                     x=selected_atributos[0],
                                     y=selected_atributos[1],
                                     hover_data=['Country'])
                    st.plotly_chart(fig, use_container_width=True)
            if (type_visualize == 'histograma'):
                sns.distplot(df[selected_atributos[0]])
                st.pyplot()
            if (type_visualize == 'Matriz de correlação'):
                st.write(df.corr())

        st.markdown('**Regressão Linear**')
        Y = st.selectbox('Selecione a variável Y', opcoes)
        x = st.multiselect('Selecione a variável X', opcoes)
        if ((Y != None) & (len(x) >= 1)):
            modelo = LinearRegression()
            X_train, X_test, y_train, y_test = train_test_split(
                df[x], df[Y], test_size=0.3, random_state=2811)
            modelo.fit(X_train, y_train)
            st.text("R quadrado = {}".format(
                modelo.score(X_train, y_train).round(2)))
            y_predict_train = modelo.predict(X_train)
            lm = modelo.predict(X_test)
            st.text("R quadrado de teste = {}".format(
                metrics.r2_score(y_test, lm).round(2)))
            sns.regplot(x=y_predict_train, y=y_train)
            st.pyplot()
            index = x
            index.append('Intercept')
            st.markdown('**Formula da Regressão Linear**')
            st.image('formula.png', width=500)
            st.table(
                pd.DataFrame(data=np.append(modelo.intercept_, modelo.coef_),
                             index=index,
                             columns=['Parametros']))
Пример #5
0
model = joblib.load('XGBoost_model.sav')
#image=Image.open('down.jpg')
#st.image(image,width=500)


st.markdown("<h1 style='text-align: center; color: red;'><strong>CUSTOMER CHURN PREDICTOR</strong></h1>", unsafe_allow_html=True) 

selectbox=st.sidebar.selectbox('Select operation to be performed',['Enter values for prediction'
                                                                   ,'View training dataset','View dataset analysis'])
if selectbox == 'Enter values for prediction':
    
    st.subheader("Enter the appropriate values for each field and press 'Predict' to get the result.")
    
    CreditScore=st.number_input('CreditScore', min_value= 1 , max_value = 850 , value =200)
    
    Geography=st.selectbox('Geography',['France','Spain','Germany'])
    if Geography=='France':
        Geography=1
    elif Geography=='Spain':
        Geography=2
    else:
        Geography=3
    
    Gender=st.selectbox('Gender',['Female','Male'])
    if Gender=='Female':
        Gender=0
    else:
        Gender=1
    
    Age=st.number_input('Age', min_value=1 , max_value=100, value=25)
    
Пример #6
0
st.line_chart(dfa)
#st.pyplot(axa)

# draw frequencies - will use them to select afterwards
st.header('Frekvenser')
st.write(resultat)

#words_to_print = [w for w in resultat.index]

#check_boxes = [st.checkbox(word_to_print, key = word_to_print) for word_to_print in words_to_print]

#st.write([w for w, checked in zip(words_to_print, check_boxes) if checked])

# show concordances
st.header('Konkordanser')
media = st.selectbox('Søk i avis eller bok', ['bok', 'avis', 'ordbok'], 0)
#ddk = st.text_input('velg ddk, skriv inn de første sifrene', '839')
if media == 'ordbok':
    ddk = ["610%", "423%", "491%", "620%", "433%", "443%", "439%"]
    media = 'bok'
else:
    ddk = None

konk_ord = st.text_input('konkordanseord', list(resultat.index)[0])
#media_type = st.radio('Mediatype', ['bok', 'avis'])

if ddk != None:
    konks = [
        k for konks in [
            nb.concordance(konk_ord,
                           corpus='bok',
def main():
    """ main function"""

    st.title("Save your passwords")
    menu = ["Home", "Login", "SingUp"]
    choice = st.sidebar.selectbox("Menu", menu)
    # choice logic
    if choice == "Home":
        st.subheader("Home page")
        st.write("write now only saving of your passowrd is done")
        text = ("Future develop to share password between users").upper()
        text
        text = ("Deletion of the saved passwords").upper()
        text
        text = ("Adding of the profile page").upper()
        text
    elif choice == "Login":
        st.subheader("This is login screen")
        # login menu
        username = st.sidebar.text_input("User Name")
        password = st.sidebar.text_input("Password", type="password")
        if st.sidebar.checkbox("Login"):
            # if password == "1234":
            create_table()
            result = login_user(username, password)
            if result:
                st.success(f"Logges in as {username}")
                user_menu = st.selectbox(
                    "Navigation",
                    ["Profile", "Stored Passwords", "Add Password"])
                if user_menu == "Profile":
                    st.subheader("user Profile")
                    st.text("yet to develop")
                    st.success("remaining menu is working")
                elif user_menu == "Stored Passwords":
                    st.subheader("List of the passwords")
                    password_data = all_password(username)
                    clean_db = pd.DataFrame(
                        password_data,
                        columns=["site", "username", "password"])
                    st.dataframe(clean_db)
                elif user_menu == "Add Password":
                    try:
                        st.subheader("Enter your creditionals")
                        user = username
                        site = st.text_input("site name")
                        site_username = st.text_input("username/email")
                        site_password = st.text_input("password")
                        print(user, site, site_username, site_password)
                        if st.button("Add"):
                            result = insert_password(user, site, site_username,
                                                     site_password)
                            if result:
                                st.success("Data was added")
                            else:
                                st.error("Error while insert")
                    except Exception as e:
                        st.error(f"Try again,Error:{e}")
            else:
                st.warning("Incorrect Password")
        else:
            text = ("Enter your username and password in the left side menu"
                    ).upper()
            text

    elif choice == "SingUp":
        st.subheader("this is singup screen")
        new_user = st.text_input("Username")
        new_password = st.text_input("Password", type="password")
        if st.button("Sign Up"):
            create_table()
            SingUp_user(new_user, new_password)
            st.success("You have sucessfully created a valid Account")
            st.info("Go to Login")

    hide_streamlit_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            </style>
            """
    st.markdown(hide_streamlit_style, unsafe_allow_html=True)
Пример #8
0
def main():
    st.title("Hello World, StreamLit")
    
    st.header("Começando a usar StreamLit!")
    
    st.subheader("O que é o StreamLit")
    st.write("O StreamLit é uma ferramenta para exibição de conteúdo, ela é bastante fácil de trabalhar, e sua API permite fazer muitas coisas diferentes!")
    
    st.subheader("É possível adicionar **imagens**!")
    st.image("logo.png")
    
    st.subheader("É possível adicionar **áudios**!")
    # st.audio("audio.webm")
    st.audio(r"https://www.dropbox.com/s/t5sgl6fz11t5bpv/Cartoon%20-%20Why%20We%20Lose%20%28feat.%20Coleman%20Trapp%29%20_NCS%20Release_.mp3?dl=1")
    
    st.subheader("É possível adicionar **vídeos**!")
    st.video("https://www.youtube.com/watch?v=WeJU_HxUxy0")
    
    st.subheader("E utilizar *sintaxe* de ~~html~~ **MarkDown**!")
    st.write('Utilizando "\*" e "~"')

    st.header("Aula StreamLit 3")
    
    st.subheader("Como utilizar botões!")
    st.write("Clique no botão a seguir:")
    botao = st.button("Clique em mim!")
    if botao:
        st.write("Você clicou no botão!")
    
    st.subheader("Agora vamos fazer um checkbox!")
    checkbox = st.checkbox("Eu sou um checkbox!")
    if(checkbox):
        st.write("O checkbox está marcado!")

    st.subheader("Agora vamos fazer um radioGroup!")
    radio = st.radio("Um radioGroup tem diversas opções!", ("Eu sou a opção 1", "Opção 2, eu sou"))
    if radio == "Eu sou a opção 1":
        st.write("Você selecionou a primeira opção!")
    if radio == "Opção 2, eu sou":
        st.write("Que a força esteja com você!")
    
    st.subheader("E uma caixa de seleção única?")
    selectBox = st.selectbox("Eu sou a sua caixa de seleção favorita", ("Choose an Option","Red Pill", "Blue Pill", "Yellow Pill?"))
    if selectBox == "Red Pill":
        st.write("Uma verdade desegradável será revelada.")
    if selectBox == "Blue Pill":
        st.write("A ignorância é uma virtude.")
    if selectBox == "Yellow Pill?":
        st.write("Are you okai?")
    
    st.subheader("A famigerada caixa de seleção MÚLTIPLA:")
    multiSelect = st.multiselect("Eu sou a caixa de seleção múltipla, muitos devs não gostam de mim, sniff", ("Press F", "The answer is 42", "All of the above"))
    if "Press F" in multiSelect:
        st.write("You paid the due respect!")
    if "The answer is 42" in multiSelect:
        st.write("Yes, it is.")
    if "All of the above" in multiSelect:
        if len(multiSelect) > 1:
            st.write("Redundant, aren't we?")
        else:
            st.write("This is a multiselection box, you know?")
    
    st.subheader("Dá pra enviar arquivos?")
    st.write("Dá sim, parceiro, saca só:")
    myFile = st.file_uploader("Pode vir quente!", 'csv')
    if myFile is not None:
        st.write("Seu arquivo está seguro em minhas mãos!")
Пример #9
0
st.write(w3)

st.subheader("Button")
w4 = st.button("Click me")
st.write(w4)

if w4:
    st.write("Hello, Interactive Streamlit!")

st.subheader("Radio")
options = ("female", "male")
w5 = st.radio("Gender", options, 1)
st.write(w5)

st.subheader("Text input")
w6 = st.text_input("Text input widget", "i iz input")
st.write(w6)

st.subheader("Selectbox")
options = ("first", "second")
w7 = st.selectbox("Options", options, 1)
st.write(w7)

st.subheader("Time Input")
w8 = st.time_input("Set an alarm for", time(8, 45))
st.write(w8)

st.subheader("Date Input")
w9 = st.date_input("A date to celebrate", date(2019, 7, 6))
st.write(w9)
Пример #10
0
def vaccineStats(vaccine):

    st.markdown('***')
    st.markdown('''<h3 style='font-family:Montserrat; font-style:italic; text-align:center;'>All About Vaccines</h3>''',unsafe_allow_html=True)
    st.markdown('<br>',unsafe_allow_html=True)
    st.markdown('***')


    vaccine_df, vaccloc_df = vaccine.values()

    vaccman = pd.read_csv('./assets/Vaccine.csv').drop('Unnamed: 0',axis=1)

    choice = st.sidebar.selectbox('Information', ['Vaccines Administered', 'Vaccines Available'],key='vaccines')
    st.sidebar.markdown('***')

    if choice == 'Vaccines Available':

        st.markdown('''> <p style='font-size:30px'><span style='font-style:italic; text-align: center; font-weight:bold; font-size:30px;'>Vaccinations of the World</span> �</p>''', unsafe_allow_html=True)
        st.markdown('''<hr>''',unsafe_allow_html=True)

        VaccineList = vaccman['vaccines'] # world
        paths = vaccman['Paths']
        information = vaccman['Info']

        first = st.beta_expander(VaccineList[0].capitalize(), expanded=True)
        first.image(paths[0],width=300)
        first.markdown('_{}_'.format(information[0]))
        

        expobjs = []
        for vaccine in VaccineList[1:]:
            expobjs.append(st.beta_expander(vaccine.capitalize()))
       
        
        for obj, path, info in zip(expobjs,paths[1:],information[1:]): 
            obj.image(path,width=300)
            obj.markdown('_{}_'.format(info))
            
            


    elif choice == 'Vaccines Administered':

        # st.write(vaccine_df.columns)

        country = st.selectbox('Select Country',vaccine_df['location'].unique(),key='locations')

        st.markdown('***')
        try:
            st.markdown('''<p><span style='font-style:italic; font-weight:bold;   text-align:center; font-size:45px; text-decoration:underline;'>{}<span>   <img src='data:image/png;base64,{}' class='img-fluid' width=50 height=50></p>'''.format(country, img_to_bytes("./assets/Countries/{}.png".format(country.lower()))), unsafe_allow_html=True)
        except:
            # file name exception
            st.markdown('''<p><span style='font-style:italic; font-weight:bold;   text-align:center; font-size:45px; text-decoration:underline;'>{}<span></p>'''.format(country), unsafe_allow_html=True)
        

    
        total = vaccine_df[vaccine_df['location'] == country]['total_vaccinations'][-1:].values[0]
        full_vacc =  vaccine_df[vaccine_df['location'] == country]['people_fully_vaccinated'][-1:].values[0]
        oneshot = vaccine_df[vaccine_df['location'] == country]['people_vaccinated'][-1:].values[0]
        last_date = vaccine_df[vaccine_df['location'] == country]['date'][-1:].values[0]

        

        fully_vacc = (full_vacc/total)*100
        partially_vacc = (oneshot/total)*100

        st.markdown('''> <p><span style='font-weight:bold; text-align:center; font-size:40px; '>{:,}</span> <span style='font-weight:bold; font-style:italic; padding-left: 20px;'>Total Vaccine Administrations.</span></p>'''.format(int(total)), unsafe_allow_html=True)
        st.markdown('''> <p><span style='font-weight:bold; text-align:center; font-size:40px; '>{:.2f}% / <span style='font-size:20px;  font-weight:normal;'>{:,}</span></span> <span style='font-weight:bold; font-style:italic; padding-left: 20px; color:limegreen;'>Fully Vaccinated.</span></p>'''.format(fully_vacc, int(total)), unsafe_allow_html=True)
        st.markdown('''> <p><span style='font-weight:bold;  text-align:center; font-size:40px; '>{:.2f}% / <span style='font-size:20px; font-weight:normal;'>{:,}</span></span> <span style='font-weight:bold; font-style:italic; padding-left: 20px; color:deepskyblue;'>Got their First Vaccine Shot.</span></p>'''.format(partially_vacc, int(total)), unsafe_allow_html=True)
        st.markdown('''> <p><span style='font-style:italic; font-weight:bold;   text-align:center; font-size:15px;'>Reported on <span style='color:dodgerblue;'>{}</span></span></p>'''.format(last_date), unsafe_allow_html=True)

        st.markdown('***')

        try:
            _, _, vaccine, lastObs, provider, website = vaccloc_df[vaccloc_df['location']==country].values[0]

            st.markdown('* _Vaccines been Administered_ ~ ___{}___'.format(vaccine))
            st.markdown('* _Last Observation Date_ ~ ___{}___'.format(lastObs))
            st.markdown('* _Nationwide Vaccine Provider_ ~ ___{}___'.format(provider))
            st.markdown('* _Website_ ~ ___{}___'.format(website))
        except:
            st.warning('___No Reported Data Found___')
Пример #11
0
delanteros = pd.read_csv('output/predict_posiciones/delanteros.csv')

imagen = Image.open("input/futbol.jpg")
st.image(imagen)

st.write("""

    En este projecto veremos como hacer nuestra propia alineación seleccionando unos parámetros, y la prediccion del valor de cada jugador.
    Lo primero de todo fue coger datos de unos 19 mil jugadores con sus respectivos atributos.
    Lo siguiente que se necesita es saber que atributos son mejores para cada posicion que queremos, en mi caso seran 4, porteros, defensas, medios y delanteros.
    

""")

atributos = st.selectbox(
    "Atributos que hacen buenos a los jugadores por posicion",
    ["porteros", "defensas", "medios", "delanteros"])

if atributos == "porteros":
    image = Image.open("output/plot_atributos_posicion/porteros.png")
    st.image(image)
elif atributos == "defensas":
    image = Image.open("output/plot_atributos_posicion/defensas.png")
    st.image(image)
elif atributos == "medios":
    image = Image.open("output/plot_atributos_posicion/medios.png")
    st.image(image)
elif atributos == "delanteros":
    image = Image.open("output/plot_atributos_posicion/delanteros.png")
    st.image(image)
Пример #12
0
    row['codigo_cidade_tse']: row['uf_municipio']
    for _, row in planos_df[['codigo_cidade_tse', 'uf_municipio']].
    drop_duplicates().sort_values(by='uf_municipio').iterrows()
}
codigos_municipios = list(municipios.keys())

query_params = st.experimental_get_query_params()
try:
    selected_municipio = int(query_params.get('municipio',
                                              ['20516'])[0])  # João Pessoa
    default_municipio_index = codigos_municipios.index(selected_municipio)
except ValueError:
    default_municipio_index = 0
codigo_cidade = st.selectbox(
    'Município',
    codigos_municipios,
    format_func=lambda municipio: municipios[municipio],
    index=default_municipio_index)
st.experimental_set_query_params(municipio=codigo_cidade)


# Carrega texto das propostas
@st.cache
def load_propostas(arquivo):
    path = os.path.join(DATA_RAW_PATH, arquivo)
    try:
        txt = gzip.open(path, mode='rt').read().strip()
    except FileNotFoundError:
        txt = None
    return txt
Пример #13
0
def main():

    sampleFile = st.selectbox(
         "Select sample file:", 
         ("samples/177deg_long_1.wav",
         "samples/177deg_short_1.wav",
         "samples/177deg_short_2.wav",
         "samples/234deg_long_1.wav",
         "samples/234deg_long_2.wav",
         "samples/234deg_short_1.wav",
         "samples/234deg_short_2.wav",
         "samples/234deg_short_3.wav",
         "samples/293deg_long_1.wav",
         "samples/293deg_long_2.wav",
         "samples/293deg_short_1.wav",
         "samples/293deg_short_2.wav")
    )
    
    # Load input from wav
    rate, samples = scipy.io.wavfile.read(sampleFile)
    if samples.ndim > 1:
        # Keep only one channel if audio is stereo
        samples = samples[:, 0]
    input_signal = Signal(samples, rate)
    st.write("Input sample rate:", rate)

    plot_signal(input_signal, "Input")

    # Filter and decimate reference signal, a 30Hz tone

    ref_signal = lowpass(
        input_signal,
        width=500,
        attenuation=60,
        f=500
    )
    ref_signal = decimate(ref_signal, DECIMATED_RATE)
    plot_signal(ref_signal, "Reference signal")

    # Filter FM signal

    fm_signal = bandpass(
        input_signal,
        width=1000,
        attenuation=60,
        f1=8500,
        f2=11500
    )
    plot_signal(fm_signal, "FM filtered")

    # Center FM signal on 0Hz

    carrier = np.exp(-1.0j*2.0*np.pi*9960/fm_signal.rate*np.arange(len(fm_signal.samples)))
    fm_signal.samples = fm_signal.samples * carrier
    plot_signal(fm_signal, "FM centered")

    # Lowpass and decimate FM signal

    fm_signal = lowpass(
        fm_signal,
        width=500,
        attenuation=60,
        f=1500
    )

    fm_signal = decimate(fm_signal, DECIMATED_RATE)
    plot_signal(fm_signal, "FM centered and decimated")

    # Get phase of FM signal to get the variable signal

    var_signal = Signal(
        np.unwrap(np.angle(fm_signal.samples)),
        fm_signal.rate,
        fm_signal.delay
    )
    plot_signal(var_signal, "Variable signal")

    # Remove DC of variable signal

    var_signal = bandpass(
        var_signal,
        width=15,
        attenuation=60,
        f1=15,
        f2=45
    )

    plot_signal(var_signal, "Variable signal")

    bearing = compare_phases(ref_signal, var_signal)
    st.write("Bearing: {}°".format(bearing))

    # plt.show()
    st.pyplot()
    plt.close()
Пример #14
0
img = Image.open('sample.jpg')
st.image(img, caption='Kohei Imanishi', use_column_width=True)

# Interactive Widget

# Check Box
if st.checkbox('Show Image'):
    img = Image.open('sample.jpg')
    st.image(img, caption='Kohei Imanishi', use_column_width=True)

if st.checkbox('Show Line Chart'):
    chart_df = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])
    st.line_chart(chart_df)

# Select Box
option = st.selectbox('Tell me your favorite number.', list(range(1, 11)))
'Your favorite number is', option, '.'

# Text Input
st.write('Interactive Widgets')
text = st.text_input('Tell me your another hobby.')
'Your Another Hobby:', text

# Slider
condition = st.slider('How are you right now?', 0, 100, 50)
'Current Status:', condition

# Layout

# Sidebar
# st.sidebar.write('Interactive Widgets')
Пример #15
0
def solution_page():
    st.title('Сторінка з розв\'язанням задачі')

    session_state = SessionState.get(choose_button=False,
                                     input_type='',
                                     random='',
                                     file='',
                                     db='')
    session_state.input_type = st.selectbox('Оберіть спосіб вхідних даних',
                                            ['З файлу', 'Рандомізовано'])

    if session_state.input_type == 'Рандомізовано':
        quantity = st.number_input('Кількість робіт',
                                   step=1,
                                   value=50,
                                   min_value=1,
                                   max_value=500)
        work_end = st.number_input('Кінець роботи машини',
                                   step=1,
                                   value=1000,
                                   min_value=1,
                                   max_value=99999)

        min_fine = st.number_input('Мінімальний штраф',
                                   step=1,
                                   value=10,
                                   min_value=1,
                                   max_value=99999)
        max_fine = st.number_input('Максимальний штраф',
                                   step=1,
                                   value=100,
                                   min_value=1,
                                   max_value=99999)

        min_execution_time = st.number_input(
            'Мінімальний час виконання роботи',
            step=1,
            value=5,
            min_value=1,
            max_value=99999)
        max_execution_time = st.number_input(
            'Максимальний час виконання роботи',
            step=1,
            value=40,
            min_value=1,
            max_value=99999)

        method = st.selectbox('Оберіть метод вирішення задачі', [
            'Жадібний алгоритм №1', 'Жадібний алгоритм №2',
            'Жадібний алгоритм №3'
        ])

        if st.button('Розв\'язати'):
            condition = generate_random_condition(quantity, work_end, min_fine,
                                                  max_fine, min_execution_time,
                                                  max_execution_time)
            show_answer(condition, method)
            st.table(condition2table(condition))

    if session_state.input_type == 'З файлу':
        filename = file_selector()
        # st.write('Ви обрали `%s`' % filename)
        condition = parse_condition_csv(filename)
        st.table(condition2table(condition))
        method = st.selectbox('Оберіть метод вирішення задачі', [
            'Жадібний алгоритм №1', 'Жадібний алгоритм №2',
            'Жадібний алгоритм №3'
        ])
        if st.button('Розв\'язати'):
            show_answer(condition, method)
Пример #16
0
def make_data():
    st.subheader("Створимо екземпляр власноруч")
    st.markdown(
        "За допомогою полей нижче оберіть всі параметри бажаного екземпляру.")
    bk_ft = [
        'Kindle Edition', 'Paperback', 'Mass Market Paperback', 'Hardcover',
        'ebook', 'Nook', 'Board book', 'Bonded Leather', 'Trade Paperback',
        'Library Binding', 'Audio CD', 'Audible Audio', 'online fiction',
        'Unknown Binding', 'Interactive ebook', 'Capa mole - 15,5 x 23 x 2cm',
        'Comic', 'Audiobook', 'Online Fiction - Complete', 'Audio Cassette',
        'Broché', 'Leather Bound', 'eBook Kindle', 'paper', 'hardcover',
        'Poche', 'audio cassette', 'Board Book', 'PDF ', 'Diary', 'Bolsillo',
        'Taschenbuch', 'Online Fiction', 'paperback', 'Other Format',
        'Mass Market', 'Perfect Paperback', 'Audio', 'Box-Set', 'free online',
        'Softcover', 'Broschiert', 'Hardcover Chapbook', 'Klappenbroschur',
        'Paperback, Kindle, Ebook, Audio', 'Innbundet', 'Wattpad', 'Bìa mềm',
        'Capa Mole', 'Hardcover Boxed Set', 'Digital Comic', 'Box Set',
        'Hardback', 'Boxed Set', 'MP3 CD', 'softcover', 'Paperback, eBook',
        'cloth', 'Trade Paper', 'Hard Cover', 'Podiobook', 'web',
        'Large Paperback', 'Tapa dura con sobrecubierta', 'Novel', 'Capa mole',
        'Graphic Novels', 'Spiral-bound', 'Turtleback', 'Board', 'Newsprint',
        'Tapa blanda', 'CD-ROM', 'Flexibound', 'paperback, Kindle eBook',
        'Cofanetto', 'broché', 'School & Library Binding',
        'Bantam New Fiction', 'Hardcover, Case bound',
        'Mass Market Paperback ', 'Paperback and Kindle', 'Paperback ',
        'Vinyl Cover', 'Audio Cd', 'Slipcased Hardcover', 'Kovakantinen',
        'Novelty Book', 'Hardbound', 'Kindle',
        'Science Fiction Book Club Omnibus', ' Trade Paperback', 'Pocket',
        'Audio Book', 'capa mole', 'Capa Dura', 'Edición Kindle', 'Big Book',
        'Capa comum', 'Brossura', 'Gebunden', '単行本', 'Paperback/Ebook',
        'Podcast', 'Fiction', 'Softcover, free ebook', 'Pamphlet',
        'Hardcover-spiral', 'audiobook', 'Casebound',
        'Hard cover, Soft cover, e-book', 'Capa dura', 'Unbound',
        'Newsletter Serial', 'Trade paperback', 'online serial',
        'Hardcover im Schuber', 'Gebundene Ausgabe',
        'Interactive Fiction, Gamebook', 'hardbound', 'Digital', 'Brochura',
        'revised edition'
    ]
    #['book_format', 'book_pages','book_review_count','book_rating_count',
    #'author_count', 'genre_count', 'workcount', 'fan_count', 'rating_count', 'review_count', 'average_rate']
    book_title = st.text_input("Поле book_title", 'The Ship')
    url_500 = pd.read_csv(
        'url_shape.csv')['book_image_url'].unique().tolist()[:25]
    book_image_url = st.selectbox("Поле book_image_url", url_500)
    book_desc = st.text_area('Поле book_desc', 'About')
    all_genres = pd.read_csv('all_genres.csv')
    all_genres = all_genres['0'].unique().tolist()
    genres = st.multiselect('Поле book_genre', all_genres,
                            ['Fiction', 'Fantasy', 'Romance'])
    genres = '|'.join(genres)
    all_authors = pd.read_csv('all_authors.csv')['0'].unique().tolist()[:25]
    authors = st.multiselect('Поле book_authors', all_authors, ['A. Buelow'])
    authors = '|'.join(authors)
    book_format = st.selectbox("Поле book_format", bk_ft)
    book_pages = st.slider('Поле book_pages', min_value=1, max_value=1500)
    book_pages = str(book_pages) + ' pages'
    book_review_count = st.slider('Поле book_review_count',
                                  min_value=1,
                                  max_value=150_000)
    book_rating_count = st.slider('Поле book_rating_count',
                                  min_value=1,
                                  max_value=5_000_000)

    df2 = {
        'id': [np.max(data.id)],
        'book_title': [book_title],
        'book_image_url': [book_image_url],
        'book_desc': [book_desc],
        'book_genre': [genres],
        'book_authors': [authors],
        'book_format': [book_format],
        'book_pages': [book_pages],
        'book_review_count': [book_review_count],
        'book_rating_count': [book_rating_count]
    }

    return pd.DataFrame(df2)
Пример #17
0
dataset = st.sidebar.file_uploader("Choose a file")
nodes_processed = st.sidebar.progress(0)
progress_text = st.sidebar.empty()
metric_selector = st.sidebar.selectbox("Metric", list(metrics.keys()))

if dataset is not None:
    df = format_data(dataset)
    total_count = len(df)
    progress_text.text(f"{labeled_count}/{total_count} datapoints processed")

    metric_function = metrics[metric_selector]

    root = build_tree(df, "root")
    node_attr_func = lambda node: f"shape={'box' if node.name in ['True', 'False'] else 'ellipse'}, label={node.name}"
    edge_name_func = lambda parent, child: f"style=bold,label={child.label or ''}"
    dot_data = UniqueDotExporter(root,
                                 nodeattrfunc=node_attr_func,
                                 edgeattrfunc=edge_name_func)
    dot_data = '\n'.join(dot_data)
    graph = graphviz.Source(dot_data)
    st.graphviz_chart(dot_data)

    node_names = list(reversed(rules.keys()))
    nodepath = st.selectbox("Node", node_names)

    data = rules[nodepath].data
    st.write(data)
    select_splitting_attr(data, True)

    # st.write(RenderTree(root))
Пример #18
0
    df = data.loc[:,['LIFD','Underweight']]
    df['maxunder'] = df.groupby('LIFD')['Underweight'].transform('mean')
    df = df.drop('Underweight', axis=1).drop_duplicates()
    df = data.loc[:,['LIFD','Underweight']]
    df['maxunder'] = df.groupby('LIFD')['Underweight'].transform('mean')
    df = df.drop('Underweight', axis=1).drop_duplicates()

    fig = sns.barplot(data=df, x='LIFD', y='maxunder')
    fig.set(xticklabels = ['Not LIFD', 'LIFD'])
    st.write(plt.show())
    st.pyplot()

st.subheader("Choix de Digramme")

option=st.selectbox('Quelle digramme voulez vous afficher ?',('','Heatmap', 'Diagramme en bare'))

if(option=='Heatmap'):
    corr = data.corr()
    mask = np.zeros_like(corr, dtype = np.bool)
    mask[np.triu_indices_from(mask)] = True
    st.write(sns.heatmap(corr, mask = mask,  linewidths = .5 ,cmap='Greens'))
    st.pyplot()
    
elif(option==''):
    st.write(plt.show())    
else:
    f,(ax1, ax2, ax3) = plt.subplots(1, 3, figsize = (15, 7.2))
    df_with_LIFD = data.loc[data['LIFD'] == 1]
    df_with_NLIFD = data.loc[data['LIFD'] == 0]
Пример #19
0
def imdb_func():
    st.title("IMDB")
    st.write(
        "The dataset is a collection of highly polar movie reviews from IMDB. This dataset is used for training a binary sentiment classification model."
    )

    max_features = 20000
    with st.spinner('Loading Data...'):
        (x_train, y_train), (x_test,
                             y_test) = imdb.load_data(num_words=max_features)

    st.write(" ")
    st.markdown('**Shape**')
    st.write('\nTraining dataset :', x_train.shape, "\nTesting dataset :",
             x_test.shape)

    classes = ["Negative", "Positive"]

    st.write(" ")
    st.write("**Data** ")
    index = imdb.get_word_index()
    feature = []
    for i in range(3):
        reverse_index = dict([(value, key) for (key, value) in index.items()])
        decoded = " ".join([reverse_index.get(j - 3, "#") for j in x_train[i]])
        decoded = decoded[1:]
        feature.append(decoded)
    label = [classes[y_train[i]] for i in range(3)]

    df = pd.DataFrame(list(zip(feature, label)),
                      columns=['Reviews', 'Sentiments'])
    st.table(df)

    st.write("**Classes** ")
    s = ""
    for i in range(len(classes)):
        if i is not (len(classes) - 1):
            s += str(classes[i]).title()
            s += ","
            s += " "
        else:
            s += str(classes[i])
    st.write(s)

    x_train = sequence.pad_sequences(x_train, maxlen=100)
    x_test = sequence.pad_sequences(x_test, maxlen=100)

    st.write("")
    st.write("**Build Model**")
    dropout = st.checkbox("Dropout")

    opt = st.selectbox("Choose the type of Optimizer ",
                       ("adam", "sgd", "rmsprop", "adagrad"))

    val = st.checkbox('Validation Set')
    epoch = st.slider("Epochs", 0, 250, step=1)
    b_s = st.slider("Batch Size", 32, 1024, step=32)

    st.write("")
    st.write("")
    if st.button("Train Model"):
        model = Sequential()
        model.add(Embedding(max_features, 128))
        model.add(LSTM(128, recurrent_dropout=0.2))
        if (dropout):
            model.add(Dropout(0.2))
        model.add(Dense(1, activation='sigmoid'))
        model.compile(loss='binary_crossentropy',
                      optimizer=opt,
                      metrics=['accuracy'])

        with st.spinner(
                'Training may take a while, so grab a cup of coffee, or better, go for a run!'
        ):
            if val:
                result = model.fit(x_train,
                                   y_train,
                                   batch_size=int(b_s),
                                   epochs=int(epoch),
                                   validation_split=0.2)
            else:
                result = model.fit(x_train,
                                   y_train,
                                   batch_size=int(b_s),
                                   epochs=int(epoch))
        st.success("Model Trained.")
        results = model.evaluate(x_test, y_test, batch_size=128)
        st.write("Loss: ", results[0])
        st.write("Accuracy: ", results[1])
        model.save("models/imdb.h5")
        st.write("")
        st.write("**Predictions** (Random Test Samples)")

        l = []
        f = []

        index = imdb.get_word_index()
        for i in range(3):
            r = np.random.randint(0, len(x_test))
            reverse_index = dict([(value, key)
                                  for (key, value) in index.items()])
            decoded = " ".join(
                [reverse_index.get(j - 3, "#") for j in x_test[r]])
            decoded = decoded[1:]
            f.append(decoded)
            l.append(classes[y_train[r]])
        df2 = pd.DataFrame(list(zip(f, l)), columns=['Reviews', 'Sentiments'])
        st.table(df2)
Пример #20
0
import streamlit as st
import pandas_datareader.data as web
from datetime import datetime as dt, timedelta as td

st.title('FinPython Crypto Tracker')
opts = st.selectbox('Select Pair',
                    ('BTC-USD', 'ETH-USD', 'BNB-USD', 'XRP-USD', 'LINK-USD',
                     'DOGE-USD', 'EOS-USD', 'BSV-USD'))
prices = web.get_data_yahoo(opts, start=dt.now() - td(days=365), end=dt.now())
st.line_chart(prices)
    This is a Word Cloud generator for the #66DaysofData Challenge. The Word Cloud is generated with the tweets form the 
    paricipant, when they used the above mentioned hashtag. 
    
    If you arent a participant and want to see different results you can try one of the following users: 
    KenJee\_DS, MarkusM99098101, KOrfanakis, \_paulo\_lopez\_, JackRaifer.

    The Word Cloud is created from a database with {rows} individual tweets ({date_from} to {date_to}).

    You can read more about the project on my [porfolio website](https://markusmueller-ds.github.io/portfolio/66days_analysis.html) (WIP)
"""

st.markdown(html_str, unsafe_allow_html=True)

st.write("")

option = st.selectbox(
    'Do you want the Word Cloud with or without lemmatization?', ['no', 'yes'])

user_name = st.text_input('Twitter handle (without the @):')
# st.write(f'WordCloud wird für {user_name} erstellt')

if (st.button('Create WordCloud')):
    # FILTER DATAFRAME WITH USER NAME
    df_user = df[df['user_name'] == user_name]
    df_user.reset_index(inplace=True)

    # REMOVE LINKS
    link_re = re.compile('http://\S+|https://\S+')
    str_user = ''

    for x in range(len(df_user)):
        str_ = df_user['full_text'][x]
Пример #22
0
def main():
    session_state = SessionState.get(
        last_predictions = None,
        last_post_predictions = None,
        cqt = None,
        labels = None,
        cqt_view = None,
        labels_view = None,
        last_config = ""
    )

    # ======== SIDE BAR ========
    st.sidebar.header('Models')

    architecture_selected = st.sidebar.selectbox('Architecture', ['MLP', 'CNN', 'LSTM', 'BiLSTM', 'DNN'])
    architecture_selected = architecture_selected.lower()

    folders = file_handler.get_folder_name_list(MODEL_FOLDER, prefix=architecture_selected)
    
    for i in range(len(folders)):
        parts = folders[i].split('_')
        folders[i] = '{} Epoch, {} Early'.format(parts[1][:-5], parts[2][:-5])

    selected_conf = st.sidebar.selectbox('Configurations', folders)

    if selected_conf is not None:
        selected_conf_parts = selected_conf.split()
        selected_conf_name = '{}_{}epoch_{}early'.format(architecture_selected, selected_conf_parts[0], selected_conf_parts[2])
        file_names = file_handler.get_file_name_list(join(MODEL_FOLDER, selected_conf_name))
    else:
        file_names = []

    keys, losses = parse_file_list(file_names)
    selected_variant = st.sidebar.selectbox('Fold Variants', keys)

    #include_negatives = st.sidebar.checkbox('Include negatives (Preview only)')
    #brightness_multiplier = st.sidebar.slider('Brightness multiplier (Preview only)', 1.0, 10.0, value=1.0)
    #brightness_offset = st.sidebar.slider('Brightness offset (Preview only)', -2.0, 2.0, value=0.0)
    #enable_color_ramp = st.sidebar.checkbox('Enable color ramp')

    st.sidebar.header('Post-Processing')
    rounding_threshold = st.sidebar.slider('Rounding threshold', 0.0, 1.0, value=0.5, step=0.05)
    minimum_fill = st.sidebar.slider('Minimum fill', 0, 50, value=8)
    gap_threshold = st.sidebar.slider('Gap threshold', 0, 50, value=5)
    post_iter_count = st.sidebar.slider('Post processing iteration count', 0, 5, value = 1)

    # ======== MAIN PAGE ========

    st.title('AMT_FGV')

    if selected_variant is None:
        st.error('Please select a model')
        return

    selected_model_path = join(MODEL_FOLDER, selected_conf_name, selected_variant)
    run_data = load_losses(join(MODEL_FOLDER, selected_conf_name, losses[selected_variant]))

    st.text(selected_model_path)
    st.text('This model is ran for %i epochs.' % (run_data.iloc[-1, 0] + 1))

    # ============== LOSS RAW DATA ====================
    # Change to altair/matplotlib if axis labels are needed
    # https://github.com/streamlit/streamlit/issues/1129
    if st.checkbox('Show loss'):
        st.subheader('Loss Graph')
        st.line_chart(run_data.iloc[:, 1:3])
        #if st.checkbox('Show raw data'):
        #    st.dataframe(run_data.iloc[:])

    ##################################################

    preset_options = ['Upload a file']
    for key in presets:
        preset_options.append(key)

    selected_preset = st.selectbox('Select a preset or upload', preset_options)
    audio_player = st.empty()

    status = st.empty()

    file_bytes = None
    if selected_preset == preset_options[0]:
        file_bytes = st.file_uploader('Upload file', type=['wav', 'txt'])

        if file_bytes is not None:
            if st.button('Load'):
                cqt, labels = preprocessing_handler.preprocess(file_bytes, status, architecture_selected)

                cqt_view, labels_view = cqt, labels

                if architecture_selected == 'cnn' or architecture_selected == 'mlp':
                    cqt_view, labels_view = preprocessing_handler.preprocess(file_bytes, status, 'mlp')
                elif architecture_selected == 'lstm' or architecture_selected == 'bilstm' or architecture_selected == 'dnn':
                    cqt_view = cqt_view.T
                    if labels_view is not None:
                        labels_view = labels_view.T

                session_state.cqt = cqt
                session_state.labels = labels
                session_state.cqt_view = cqt_view
                session_state.labels_view = labels_view
    else:
        file_path = join(PRESET_FOLDER, presets[selected_preset])
        file_bytes = file_handler.get_file_bytes(file_path)

        if st.button('Load'):
            cqt, labels = preprocessing_handler.preprocess(file_path, status, architecture_selected)

            cqt_view, labels_view = cqt, labels

            if architecture_selected == 'cnn' or architecture_selected == 'mlp':
                cqt_view, labels_view = preprocessing_handler.preprocess(file_path, status, 'mlp')
            elif architecture_selected == 'lstm' or architecture_selected == 'bilstm' or architecture_selected == 'dnn':
                    cqt_view = cqt_view.T
                    if labels_view is not None:
                        labels_view = labels_view.T

            session_state.cqt = cqt
            session_state.labels = labels
            session_state.cqt_view = cqt_view
            session_state.labels_view = labels_view

    if file_bytes is not None:
        audio_player.audio(file_bytes)

    cqt = session_state.cqt
    labels = session_state.labels
    cqt_view = session_state.cqt_view
    labels_view = session_state.labels_view

    config = selected_model_path
    if file_bytes is not None:
        if isinstance(file_bytes, io.BytesIO):
            config += base64.b64encode(file_bytes.read()).decode()[:32]
        else:
            config += base64.b64encode(file_bytes).decode()[:32]
    
    if config != session_state.last_config:
        session_state.last_predictions = None
        session_state.last_post_predictions = None
        session_state.cqt = None
        session_state.labels = None
        session_state.cqt_view = None
        session_state.labels_view = None

        session_state.last_config = config

        return

    # ================= Data freq =====================
    #data = np.load('sl_data/tmp/Y_input_shuffled-nm.npy', mmap_mode='r')
    #if data.shape[0] > data.shape[1]:
    #    data = data[:].T
    #else:
    #    data = data[:]

    #st.write(data.shape)
    #freq = np.sum(np.clip(data, 0, 1), axis=1)
    #st.write(freq.shape)

    ##zeroes = np.sum(np.abs(np.clip(data, 0, 1) -1), axis=1)
    #zeroes = np.zeros(data.shape[0]) + data.shape[1]

    #st.write(freq.shape)

    #ones_zeroes_data = np.asarray([zeroes, freq]).T
    #st.write(ones_zeroes_data.shape)

    #ones_zeroes = pd.DataFrame(
    #    ones_zeroes_data,
    #    columns=['zeroes', 'ones']
    #)

    #st.bar_chart(ones_zeroes)

    #st.write((freq / data.shape[1]) * 100)
    


    #########

    if cqt is not None:
        #st.text('CQT\'s shape: {}'.format(cqt.shape))
        #if labels is not None:
        #    st.text('Label\'s shape: {}'.format(labels.shape))
        st.text('Label')

        cqt_view_widget = st.empty()
        label_view_widget = st.empty()
        
        # CQT

        #slider = st.slider('Offset', max_value=get_cqt_length('sl_data/tmp/train_X.npy') - 800, step=1)
        #pre_processed_CQT = load_preprocessed_CQT('sl_data/tmp/train_X.npy', 800, offset=slider)
        
        long_width = int(np.max(cqt_view.shape))
        if long_width - VIEW_WIDTH <= 0:
            slider = 0
        else:
            slider = st.slider('Offset', max_value=long_width - VIEW_WIDTH, step=1)
        #view_cqt = prepare_view_data(cqt_view, VIEW_WIDTH, offset=slider)

        #### !!! Get min_val from file
        #min_val = np.min(view_cqt) if include_negatives else 0
        
        # Color ramp attempt

        #image = np.clip((view_cqt - np.clip(min_val, np.NINF, 0.0)) * brightness_multiplier + brightness_offset, 0.0, 1.0)
        #if enable_color_ramp:
        #    image = color_ramp(image)
        #cqt_view_widget.image(image, use_column_width=True)

        #D = librosa.amplitude_to_db(view_cqt[:, slider:(slider+800)], ref=np.max)
        #librosa.display.specshow(D, x_axis='time', y_axis='cqt_note', bins_per_octave=36)
        #st.pyplot()

        #cqt_fig = px.imshow(view_cqt[:, slider:(slider + 800)], origin='lower', zmax=2)
        #cqt_fig.update_layout(autosize=False, width=500, height=400, margin=dict(l=10, r=10, b=10, t=1000))
        #st.plotly_chart(cqt_fig, use_container_width=True)

        # Labels
        if labels_view is not None:
            #pre_processed_CQT2 = load_preprocessed_CQT('sl_data/model1/train_Y.npy', 800, offset=slider)

            pre_processed_labels = prepare_view_data(labels_view, VIEW_WIDTH, offset=slider)
            label_image = np.clip(pre_processed_labels, 0.0, 1.0)
            label_view_widget.image(label_image, use_column_width=True)

            label_fig = px.imshow(label_image[:, slider:(slider + VIEW_WIDTH)], height=220, origin='lower')
            #st.plotly_chart(label_fig, use_container_width=True)
        else:
            label_view_widget.warning('Labels are not supported for this file')

        # Running
        if (st.button('Run Model')):
            model_status = st.text('[Model Status]')
            predictions = np.asarray(loader.run_model_sl(selected_model_path + '.h5', cqt, model_status, architecture_selected))
            session_state.last_predictions = predictions

            # Post
            post_predictions = preprocessing_handler.post_process(predictions, rounding_threshold, minimum_fill, gap_threshold, post_iter_count)
            session_state.last_post_predictions = post_predictions

        # ============ RESULT ===============
        post_last_run_widget = st.empty()
        if session_state.last_predictions is not None:
            last_predictions = session_state.last_predictions
            prepared_predictions = prepare_view_data(last_predictions, VIEW_WIDTH, offset=slider)
            
            st.text('Last run result')
            st.image(prepared_predictions, use_column_width=True)

        if session_state.last_post_predictions is not None:
            if st.button('Rerun Post-Processing'):
                session_state.last_post_predictions = preprocessing_handler.post_process(last_predictions, rounding_threshold, minimum_fill, gap_threshold, post_iter_count)

            post_predictions = session_state.last_post_predictions
            post_prepared_predictions = prepare_view_data(post_predictions, VIEW_WIDTH, offset=slider)
            
            st.text('Last run after post-process')
            st.image(post_prepared_predictions, use_column_width=True)

            # TESTING PURPOSES
            if labels_view is not None:
                if st.checkbox('Show Confusion Matrix'):
                    cm_labels = labels_view[:, :post_predictions.shape[1]].T
                    cm_preds = post_predictions.T
                    st.write(cm_labels.shape)
                    st.write(cm_preds.shape)
                    confusion_matrix = multilabel_confusion_matrix(cm_labels, cm_preds)
                    cm_dict = ''
                    for i, entry in enumerate(confusion_matrix):
                        # TN, FP, FN, TP
                        cm_dict += f'{i}: [{entry[0, 0]}, {entry[0, 1]}, {entry[1, 0]}, {entry[1, 1]}]\n\n'
                    st.write('TN, FP, FN, TP')
                    st.write(cm_dict)

                    report = classification_report(cm_labels, cm_preds)
                    st.text(report)
            ########
            
            if st.button('Process Sheet'):
                byte_data = create_midi(post_predictions, architecture_selected)
                lily_pond = pred2sheet(post_predictions)

                #np.save('post_predictions.npy', post_predictions)
                st.info('Click on the URL to download')
                st.markdown(get_download_link(byte_data, 'midi_result.mid','Download MIDI'), unsafe_allow_html=True)
                st.text_area('LilyPond', lily_pond)
def run_eda_app() :
    st.subheader('EDA 화면입니다.')

    car_df = pd.read_csv('data/Car_Purchasing_Data.csv', encoding='ISO-8859-1')
   
    radio_menu = ['데이터프레임','통계치']
    selected_radio = st.radio('선택하세요',radio_menu)

    if selected_radio == '데이터프레임' :
        st.dataframe(car_df)

    elif selected_radio == '통계치' :
        st.dataframe(car_df.describe())

    columns = car_df.columns
    columns = list(columns)

    selected_columns = st.multiselect('컬럼을 선택하시오.',columns)

    if len(selected_columns) != 0 :
        st.dataframe(car_df[selected_columns])

    else :
        st.write('선택한 컬럼이 없습니다.')

    # 상관계수를 화면에 보여주도록 만듭니다.
    # 멀티셀렉트에 컬럼명을 보여주고,
    # 해당 컬럼들에 대한 상관계수를 보여주세요.
    # 단, 컬럼들은 숫자 컬럼들만 멀티셀렉트에 나타나야 합니다.

    print(car_df.dtypes != object)

    corr_columns = car_df.columns[car_df.dtypes != object]
    selected_corr = st.multiselect('상관계수 컬럼 선택',corr_columns)

    if len(selected_corr) > 0 :
        st.dataframe(car_df[selected_corr].corr() )

        # 위에서 선택한 컬럼들을 이용해서, 시본의 페어플롯을 그린다.
        
        fig = sns.pairplot(data= car_df[selected_corr])
        st.pyplot(fig)

    else :
        st.write('선택한 컬럼이 없습니다.')


    # 컬럼을 하나만 선택하면, 해당 컬럼의 min과 max에 해당하는
    # 사람의 데이터를 화면에 보여주는 기능

    number_columns = car_df.columns[car_df.dtypes != object]
    selected_col = st.selectbox('컬럼 선택',number_columns)

    min_data = car_df[selected_col] == car_df[selected_col].min()
    st.write('최소값 데이터')
    st.dataframe(car_df.loc[min_data],)

    max_data = car_df[selected_col] == car_df[selected_col].max()
    st.write('최대값 데이터')
    st.dataframe(car_df.loc[max_data],)

    # 고객 이름을 검색 할 수 있는 기능 개발

    # 1. 유저한테 검색어를 받자
    word = st.text_input('검색어를 입력하세요.')

    # 2. 검색어를 데이터프레임 커스터머 네임에서 검색하자.
    result = car_df.loc[car_df['Customer Name'].str.contains(word,case=False),]
Пример #24
0
def main():

    st.title('Petrobras Conexões para a Inovação')
    opcoes = ('Dataset', 'Análise exploratória', 'Visualização dos dados',
              'Métricas')
    st.image('logo.png', width=300)
    st.subheader('Desafio Análise dos Dados para Aplicação de ML')

    st.sidebar.title('Opções')
    sidebarCategoria = st.sidebar.radio('', opcoes)

    file = st.file_uploader('Upload da base de dados para análise (.csv)',
                            type='csv')

    if file is not None:
        index = st.checkbox('Utilizar primeira coluna como index')
        df = pd.read_csv(file, index_col=0) if index else pd.read_csv(file)

        aux = pd.DataFrame({"colunas": df.columns, 'tipos': df.dtypes})
        colunas_numericas = list(aux[aux['tipos'] != 'object']['colunas'])
        colunas_object = list(aux[aux['tipos'] == 'object']['colunas'])
        colunas = list(df.columns)

        st.subheader(sidebarCategoria)

        # Dataset
        if (sidebarCategoria == opcoes[0]):
            st.write('Número de observações: ', df.shape[0],
                     'Número de variáveis: ', df.shape[1])

            st.markdown('**Dataset (describe)**')
            st.table(df[colunas_numericas].describe().transpose())

            st.markdown('**Dataset (overview)**')
            df_pivot = pd.DataFrame({
                'types': df.dtypes,
                'nulls': df.isna().sum(),
                '% nulls': df.isna().sum() / df.shape[0],
                'size': df.shape[0],
                'uniques': df.nunique()
            })
            st.table(df_pivot)

            numero_linhas = st.slider(
                'Escolha o numero de linhas que deseja visualizar: ',
                min_value=5,
                max_value=50)
            st.dataframe(df.head(numero_linhas))

            st.markdown('**Observações (valores únicos)**')
            variavel = st.selectbox('Escolha uma variável: ', df.columns)
            st.dataframe(pd.DataFrame({variavel: df[variavel].unique()}))

        # Análise exploratória
        elif (sidebarCategoria == opcoes[1]):
            st.markdown('**Estimativas de Localização e Variabilidade**')

            col = st.selectbox('Selecione a coluna :', colunas_numericas)
            if col is not None:
                st.markdown('Selecione a estimativa que deseja analisar :')

                mean = st.checkbox('Média')
                if mean:
                    st.markdown(df[col].mean())

                median = st.checkbox('Mediana')
                if median:
                    st.markdown(df[col].median())

                desvio_pad = st.checkbox('Desvio padrão')
                if desvio_pad:
                    st.markdown(df[col].std())

                amplitude_iqr = st.checkbox('Amplitude Interquatílica')
                if amplitude_iqr:
                    st.markdown(df[col].quantile(0.75) -
                                df[col].quantile(0.25))

                st.markdown('**Quantidade de dados faltantes:**')
                dados_faltante = pd.DataFrame({
                    'types':
                    df.dtypes,
                    'NA':
                    df.isna().sum(),
                    '% NA': (df.isna().sum() / df.shape[0]) * 100
                })
                st.table(dados_faltante)

                st.markdown('**Quantidade de outliers:**')
                st.markdown(
                    '$$x ∉ [Q1 - 1.5 * {IQR}, Q3 + 1.5 * {IQR}] \Rightarrow x  { é outlier}$$'
                )

                q1 = df[colunas_numericas].quantile(0.25)
                q3 = df[colunas_numericas].quantile(0.75)
                iqr = q3 - q1
                outliers_abaixo = df[colunas_numericas][
                    df[colunas_numericas].apply(pd.to_numeric) < (
                        q1 - 1.5 * iqr)].count()
                outliers_acima = df[colunas_numericas][
                    df[colunas_numericas].apply(pd.to_numeric) > (
                        q3 + 1.5 * iqr)].count()

                outliers = pd.DataFrame({
                    'types':
                    df[colunas_numericas].dtypes,
                    'outliers abaixo':
                    outliers_abaixo,
                    'outliers acima':
                    outliers_acima,
                    '% outliers': ((outliers_abaixo + outliers_acima) /
                                   df[colunas_numericas].shape[0]) * 100
                })
                st.table(outliers)

        # Visualização dos dados
        elif (sidebarCategoria == opcoes[2]):

            histograma = st.checkbox('Histograma')
            if histograma:
                col_num = st.selectbox('Selecione a Coluna Numerica: ',
                                       colunas_numericas,
                                       key='unique')
                st.markdown('Histograma da coluna' + str(col_num) + ': ')
                st.write(criarHistograma(col_num, df))

            barras = st.checkbox('Gráfico de barras')
            if barras:
                col_num_barras = st.selectbox('Selecione a coluna numerica: ',
                                              colunas_numericas,
                                              key='unique')
                col_cat_barras = st.selectbox(
                    'Selecione uma coluna categorica : ',
                    colunas_object,
                    key='unique')
                st.markdown('Gráfico de barras da coluna ' +
                            str(col_cat_barras) + ' pela coluna ' +
                            col_num_barras)
                st.write(criarBarras(col_num_barras, col_cat_barras, df))

            boxplot = st.checkbox('Boxplot')
            if boxplot:
                col_num_box = st.selectbox('Selecione a Coluna Numerica:',
                                           colunas_numericas,
                                           key='unique')
                col_cat_box = st.selectbox(
                    'Selecione uma coluna categorica : ',
                    colunas_object,
                    key='unique')
                st.markdown('Boxplot ' + str(col_cat_box) + ' pela coluna ' +
                            col_num_box)
                st.write(criarBoxplot(col_num_box, col_cat_box, df))

            scatter = st.checkbox('Scatterplot')
            if scatter:
                col_num_x = st.selectbox('Selecione o valor de x ',
                                         colunas_numericas,
                                         key='unique')
                col_num_y = st.selectbox('Selecione o valor de y ',
                                         colunas_numericas,
                                         key='unique')
                col_color = st.selectbox('Selecione a coluna para cor',
                                         colunas)
                st.markdown('Selecione os valores de x e y')
                st.write(criarScatterplot(col_num_x, col_num_y, col_color, df))

            correlacao = st.checkbox('Correlacao')
            if correlacao:
                st.markdown('Gráfico de correlação das colunas númericas')
                st.write(criarCorrelacao(df, colunas_numericas))

        # Metricas
        elif (sidebarCategoria == opcoes[3]):
            metrica = ('Missing_Value', 'Outliers')

            missing_value = st.checkbox('Missing_value')
            if missing_value:
                percentual, pontuacao_mv = calculaPontuacao(df, metrica[0])
                st.markdown(
                    'Média dos dados faltantes do dataset acima de 50%: -5 pontos'
                )
                st.markdown(
                    'Média dos dados faltantes do dataset entre 36 e 50%: -4 pontos'
                )
                st.markdown(
                    'Média dos dados faltantes do dataset entre 21 e 35%: -3 pontos'
                )
                st.markdown(
                    'Média dos dados faltantes do dataset entre 6 e 20%: -2 pontos'
                )
                st.markdown(
                    'Média dos dados faltantes do dataset entre 1 e 5%: -1 ponto'
                )

                st.write('Percentual: ', round(percentual, 3),
                         'Pontuação Dataset Dados Faltantes: ', pontuacao_mv)

            outliers = st.checkbox('Outliers')
            if outliers:
                percentual, pontuacao_out = calculaPontuacao(df, metrica[1])
                st.markdown(
                    'Média dos outliers do dataset acima de 50%: -5 pontos')
                st.markdown(
                    'Média dos outliers do dataset entre 36 e 50%: -4 pontos')
                st.markdown(
                    'Média dos outliers do dataset entre 21 e 35%: -3 pontos')
                st.markdown(
                    'Média dos outliers do dataset entre 6 e 20%: -2 pontos')
                st.markdown(
                    'Média dos outliers do dataset entre 1 e 5%: -1 ponto')

                st.write('Percentual: ', round(percentual, 3),
                         'Pontuação Dataset Outliers: ', pontuacao_out)

            st.write('**Pontuação Média Geral do Dataset: **',
                     (calculaPontuacao(df, metrica[0])[1] +
                      calculaPontuacao(df, metrica[1])[1]) / 2)
Пример #25
0
def main():
    menu = ['主页', '排名', '查询', '其他']
    choice = st.sidebar.selectbox('工具箱', menu)

    @st.cache
    def load_data():
        data = pd.read_csv('project_20_listings.csv')
        data.rename(columns={'snapshotted_at': 'date'}, inplace=True)
        data['date'] = pd.to_datetime(pd.to_datetime(data['date']).dt.date)
        return data

    data = load_data()
    if choice == '主页':
        st.title('傲基2.0品类管理')
        st.header('品类详情')
        st.markdown('针对每个asin,日排名规则为:')
        st.markdown('''
        每日排名取当日排名的最高值
        ''')

    elif choice == '排名':
        c1, c2 = st.beta_columns(2)
        category = st.selectbox('CategoryID:', data['category_id'].unique())
        table = pd.pivot_table(data[data['category_id'] == category],
                               values=['ranking'],
                               index=['asin'],
                               columns=['date'],
                               aggfunc={'ranking': max})
        st.write(table['ranking'])
        with c1:
            chosed_asin = st.selectbox(
                'Asin', data[data['category_id'] == category].asin.unique())
            st.write(table['ranking'].loc[f'{chosed_asin}'])
        with c2:

            df = table['ranking'].loc[f'{chosed_asin}']
            fig = px.line(df, x=df.index, y=df, title=f'{chosed_asin}排名变化')
            st.subheader('当月排名变化情况')
            st.plotly_chart(fig)

        start_time = st.slider('该品类下所有Asin的最高日排名',
                               value=datetime(2021, 1, 28),
                               format='MM/DD/YY')
        if start_time in table['ranking'].columns:
            st.write(
                table['ranking'][f'{start_time}'],
                'and change in data compared to previous date is:',
            )
        else:
            st.write('data is not yet available now')

        with st.beta_expander('原始数据详情', expanded=True):
            i = st.number_input('输入你想要看到的条数', min_value=1, value=50, step=50)
            detail = data.iloc[:i, :]
            st.write(detail)

    elif choice == '查询':

        ci = st.multiselect('品类ID', data['category_id'].unique())
        newdate = st.multiselect(
            '日期', data[(data['category_id'].isin(ci))].date.unique())
        asin = st.multiselect(
            'ASIN', data[data['category_id'].isin(ci)
                         & (data['date'].isin(newdate))].asin.unique())
        newtable = data[(data['category_id'].isin(ci))
                        & (data['asin'].isin(asin)) &
                        (data['date'].isin(newdate))]
        st.write(newtable)
Пример #26
0
def main():
    st.markdown(
        "![somestuff](https://az712634.vo.msecnd.net/content/14b2744cf8d6418c87ffddc3f3127242/9502630827244d60a1214f250e3bbca7/073d9d18570e437e9c3a091aa0dc3dae/2d7a9f7214f0450885c9b52f5fbec5fe/image)"
    )
    html_temp = """ 
	<div style ="background-color:#010203;padding:3px"> 
	<h1 style ="color:gold;text-align:center;">Predicting Loan Credit History and Status</h1> 
	<h2 style = "color:aqua; text-align: center;">
	The loan application will visualize the good or bad 
	credit risks according to the set of attributes of bank members.</h2>
	</div> 
	"""

    # display the front end aspect
    st.markdown(html_temp, unsafe_allow_html=True)

    html_temp1 = """ 
	<div style ="background-color:#00ff98;padding:53px"> 
	<p style ="color:purple;text-align:left;">This User Interface is meant to bring to you the members loan status and credit history.\
		 Feel free to navigate through all the sections of this web application.\
		  You can also upload your own data for your country and visualize it. We're all yours.</p> 
	</div> 
	"""

    menu = [
        "Home", "DataFrame", "Visualize", "About", "Login", "SignUp",
        "Prediction"
    ]
    #If one chooces to proceed with the Home Button --->
    choice = st.sidebar.selectbox('Menu', menu)
    if choice == 'Home':
        st.subheader("Welcome Dear Reader):-")
        st.subheader("Let's Visualize the Loan Prediction Dataset:")
        # display the front end aspect
        st.markdown(html_temp1, unsafe_allow_html=True)
        st.markdown("")
        st.markdown('Please answer this question to get updates')
        option = st.selectbox('How would you like to be contacted?',
                              ('Email', 'Home phone', 'Mobile phone'))
        # st.markdown("To view more, please proceed to the Visualize section under the dropdown menu. It's Fantastic")
        # st.sidebar.title("Visualization Selector")
        # st.sidebar.markdown("Select the Charts/Plots accordingly:")
    #If interested to see the Dataframe ---->
    elif choice == 'DataFrame':
        st.subheader('The data has 100 entries and 17 attributes.')
        st.write('Choose one to continue with the following section:')
        a = st.radio('Choose whole or Subset to continue:',
                     ['whole', 'subset'], 1)
        if a == "whole":
            st.dataframe(
                data.style.set_properties(**{
                    "background-color": "lawngreen",
                    "color": "blue"
                }))
        else:
            b = st.radio('Choose from the options, categorical, numerical, or top 5'\
             ,['CatVariables', 'NumVariables', 'top_5'],1)
            if b == 'CatVariables':
                st.dataframe(
                    CatVariables.style.set_properties(**{
                        "background-color": "lawngreen",
                        "color": "black"
                    }).highlight_max(axis=0))
            elif b == 'NumVariables':
                st.dataframe(
                    NumVariables.style.set_properties(**{
                        "background-color": "lawngreen",
                        "color": "black"
                    }).highlight_max(axis=0))
            else:
                st.dataframe(
                    data.head().style.set_properties(**{
                        "background-color": "lawngreen",
                        "color": "black"
                    }).highlight_max(axis=0))

    #if choice made is to see visualizations --->
    elif choice == 'Visualize':
        a = st.radio('Please choose on of the following',
                     ['Pie', 'Bar', 'Line'], 2)
        if a == 'Pie':
            fig = px.pie(data,values=data['credit_history'].value_counts(),\
             names=['Good','Bad'],title='Distribution of Member Credit History, (good or bad)',\
             hole=0.2)
            fig1 = px.pie(data, values = data['loan_status'].value_counts(), \
             names=['Yes','No'],title='Distribution of Member Loan Status, (Yes or No)',\
             hole=0.2)
            st.plotly_chart(fig)
            st.plotly_chart(fig1)
        if a == 'Bar':
            # 	st.title("Bar Charts of Cases,Deaths and Recoveries")
            fig = go.Figure(data=[
                go.Bar(name='Gender vs Income',
                       x=data['gender'],
                       y=data['applicantincome']),
                go.Bar(name='Self Employement vs Savings',
                       x=data.self_employed,
                       y=data['totalsavings']),
                # 	go.Bar(name='South Korea', x=sk_df.index, y=sk_df['Recovered']),
                # 	go.Bar(name='Georgia', x=geo_df.index, y=geo_df['Recovered'])
            ])
            st.plotly_chart(fig)

        # 	st.write('Equally, the bar graph could easily depict the death Rate.')
        # if a == 'Line':
        # 	fig = go.Figure()
        # 	fig.add_trace(go.Scatter(x=uk_df.index, y=uk_df['ConfirmedCases'],name='United Kingdom Deaths'))
        # 	fig.add_trace(go.Scatter(x=swe_df.index, y=swe_df['ConfirmedCases'],name='Sweden Deaths'))
        # 	fig.add_trace(go.Scatter(x=sk_df.index, y=sk_df['ConfirmedCases'],name='South Korea Deaths'))
        # 	fig.add_trace(go.Scatter(x=geo_df.index, y=geo_df['ConfirmedCases'],name='Georgia Deaths'))

        # 	fig.update_layout(title="Case Count in the 4 Countries")
        # 	st.plotly_chart(fig)

        # 	fig2 = go.Figure()
        # 	fig2.add_trace(go.Scatter(x=uk_df.index, y=uk_df['ConfirmedDeaths'],name='United Kingdom Deaths'))
        # 	fig2.add_trace(go.Scatter(x=swe_df.index, y=swe_df['ConfirmedDeaths'],name='Sweden Deaths'))
        # 	fig2.add_trace(go.Scatter(x=sk_df.index, y=sk_df['ConfirmedDeaths'],name='South Korea Deaths'))
        # 	fig2.add_trace(go.Scatter(x=geo_df.index, y=geo_df['ConfirmedDeaths'],name='Georgia Deaths'))

        # 	fig2.update_layout(title="Death Count in the 4 Countries")
        # 	st.plotly_chart(fig2)
    elif choice == "Login":
        st.subheader("Login Section")

        username = st.sidebar.text_input("User Name")
        password = st.sidebar.text_input("Password", type='password')
        if st.sidebar.checkbox("Login"):
            # if password == '12345':
            create_usertable()
            hashed_pswd = make_hashes(password)

            result = login_user(username, check_hashes(password, hashed_pswd))
            if result:

                st.success("Logged In as {}".format(username))

                task = st.selectbox(
                    "Task", ["Add Post", "Data", "Analytics", "Profiles"])
                if task == "Add Post":
                    st.subheader("Add Your Post")
                elif task == "Data":
                    st.subheader(
                        "The link to download the sourcefiles and data is at :"
                    )
                    st.markdown(
                        "1. [Link to the dataset]('https://archive.ics.uci.edu/ml/datasets/Statlog+%28German+Credit+Data%29')"
                    )
                    st.markdown(
                        "2. [Data Preprocessing source file](https://colab.research.google.com/drive/1C6kOITj4NGa_2l4NDYq8-08B5vKr9Wi7#scrollTo=pNa_XznlaJvV)"
                    )
                    st.markdown("$\mathcal{Check}$")
                    st.markdown("$\pi$ is a number,but $\mu$ is a Statistic.")
                    st.markdown("$\mathcal{Everything\quad Counts!}$")
                elif task == "Analytics":
                    st.subheader("Analytics")
                elif task == "Profiles":
                    st.subheader("User Profiles")
                    user_result = view_all_users()
                    clean_db = pd.DataFrame(user_result,
                                            columns=["Username", "Password"])
                    st.dataframe(clean_db)
            else:
                st.warning("Incorrect Username/Password")
    #if choice made is to Create a new account/sign-up --->
    elif choice == "SignUp":
        st.subheader("Create New Account")
        new_user = st.text_input("Username")
        new_password = st.text_input("Password", type='password')

        if st.button("Signup"):
            create_usertable()
            add_userdata(new_user, make_hashes(new_password))
            st.success("You have successfully created a valid Account")
            st.info("Go to Login Menu to login")

    #if choice made is to Predict on Bank Member Worthiness --->
    elif choice == 'Prediction':
        st.markdown(
            'For this particular project, you only have to pick 5 variables \
			that are most relevant. These are the Gender, Marital Status,\
			 ApplicantIncome, LoanAmount, and Credit_History ')
        # front end elements of the web page
        html_temp = """ 
		<div style ="background-color:#87ceeb;padding:13px"> 
		<h1 style ="color:gold;text-align:center;">Streamlit Loan Prediction ML App</h1> 
		</div> 
		"""
        # display the front end aspect
        st.markdown(html_temp, unsafe_allow_html=True)

        # following lines create boxes in which user can enter data required to make prediction
        Gender = st.selectbox('Gender', ("Male", "Female"))
        Married = st.selectbox('Marital Status', ("Unmarried", "Married"))
        ApplicantIncome = st.number_input("Applicants monthly income")
        LoanAmount = st.number_input("Total loan amount")
        Credit_History = st.selectbox('Credit_History',
                                      ("Unclear Debts", "No Unclear Debts"))
        result = ""

        # when 'Predict' is clicked, make the prediction and store it
        if st.button("Predict"):
            result = prediction(Gender, Married, ApplicantIncome, LoanAmount,
                                Credit_History)
            st.success('Your loan is {}'.format(result))
            print(LoanAmount)
Пример #27
0
        # Use markdown to place the badge at the bottom.
        st.markdown(
            "<div align='center'><br>"
            "<img src='https://img.shields.io/badge/MADE%20WITH-PYTHON%20-rgb(221,55,55)?style=for-the-badge'"
            "alt='API stability' height='25'/>"
            "<img src='https://img.shields.io/badge/DASHBOARDING%20WITH-Streamlit-rgb(30,77,155)?style=for-the-badge'"
            "alt='API stability' height='25'/></div>",
            unsafe_allow_html=True)

    elif page == 'Filter Data':

        st.markdown("## **Filter Data**")
        st.subheader("Pick a subject to display data for")
        subject_dropdown = st.selectbox(
            label="Subject choice",
            options=subjects)  # Drop down to pick subjects.
        levels_selection = st.multiselect(
            label="Specify a level if required",  # Multiselect to pick levels.
            options=levels['Level'])

        st.subheader("Filtered results")
        master = master[master['Department'] ==
                        subject_dropdown]  # Select all data for that subject.
        if levels_selection:
            # If they have specified levels then select all data corresponding to that choice.
            master1 = master[master['Level'].isin(levels_selection)]
        else:
            master1 = master

        # If data exists then plot the graph.
Пример #28
0
def file_selector(folder_path='./data/input_files'):
    filenames = os.listdir(folder_path)
    selected_filename = st.selectbox('Select a file', filenames)
    return os.path.join(folder_path, selected_filename)
Пример #29
0
def main():
    st.title("World-wide COVID-19 Outbreak Data Analysis")
    st.image(image, caption='-', use_column_width=True)
    st.markdown("""
    > COVID-19 is an infectious disease caused by a newly discovered type of coronavirus. The new virus and the disease it causes were not known before the outbreak in Wuhan, China, in December 2019.
    COVID-19 is now a pandemic occurring in many countries around the world.
    """)


    countries = ['Indonesia', 'Brunei','Malaysia','Cambodia','Singapore',
    'Thailand','Vietnam',"Laos", 'Burma', 'Philippines', 'Timor-Leste']

    analysis = st.sidebar.selectbox("Choose Analysis", ["Overview", "Country statistics", "Statistical comparison", "Data"])

    if analysis == "Overview":
        REGION = st.sidebar.radio("Select area", ('Southeast Asia', 'South Asia', 'East Asia', 'West Asia', 'Central Asia', 'North Asia',
        'Western Europe', 'Eastern Europe', 'Central Europe', 'Northern Europe', 'Southern Europe'))
        if REGION == 'Southeast Asia':
            st.header("COVID-19 cases and fatality rate on Southeast Asia")
            st.markdown("""\
                The data used are the reported case numbers of Southeast Asia countries"""
                f""" ({', '.join(countries)}). """
                """Based on existing data, the case fatality rate (CFR) is calculated as:  
                $$
                CFR[\%] = \\frac{fatalities}{\\textit{all cases}}
                $$
                """)
            st.warning("""
            You can select/ deselect countries and switch between linear and log scales.
            """)

            confirmed, deaths, recovered = read_data()

            multiselection = st.multiselect("Select countries:", countries, default=countries)
            logscale = st.checkbox("Log scale", False)

            confirmed = confirmed[confirmed["Country/Region"].isin(multiselection)]
            confirmed = confirmed.drop(["Lat", "Long"],axis=1)
            confirmed = transform2(confirmed, collabel="confirmed")

            deaths = deaths[deaths["Country/Region"].isin(multiselection)]
            deaths = deaths.drop(["Lat", "Long"],axis=1)
            deaths = transform2(deaths, collabel="deaths")

            frate = confirmed[["country"]]
            frate["frate"] = (deaths.deaths / confirmed.confirmed)*100

            # saveguard for empty selection 
            if len(multiselection) == 0:
                return 

            SCALE = alt.Scale(type='linear')
            if logscale:
                confirmed["confirmed"] += 0.00001

                confirmed = confirmed[confirmed.index > '2020-01-22']
                frate = frate[frate.index > '2020-01-22']
                
                SCALE = alt.Scale(type='log', domain=[10, int(max(confirmed.confirmed))], clamp=True)


            c2 = alt.Chart(confirmed.reset_index()).properties(height=150).mark_line().encode(
                x=alt.X("date:T", title="Date"),
                y=alt.Y("confirmed:Q", title="Cases", scale=SCALE),
                color=alt.Color('country:N', title="Country")
            )

            # case fatality rate...
            c3 = alt.Chart(frate.reset_index()).properties(height=100).mark_line().encode(
                x=alt.X("date:T", title="Date"),
                y=alt.Y("frate:Q", title="Fatality rate [%]", scale=alt.Scale(type='linear')),
                color=alt.Color('country:N', title="Country")
            )

            per100k = confirmed.loc[[confirmed.index.max()]].copy()
            per100k.loc[:,'inhabitants'] = per100k.apply(lambda x: inhabitants[x['country']], axis=1)
            per100k.loc[:,'per100k'] = per100k.confirmed / (per100k.inhabitants * 1_000_000) * 100_000
            per100k = per100k.set_index("country")
            per100k = per100k.sort_values(ascending=False, by='per100k')
            per100k.loc[:,'per100k'] = per100k.per100k.round(2)

            c4 = alt.Chart(per100k.reset_index()).properties(width=75).mark_bar().encode(
                x=alt.X("per100k:Q", title="Cases per 100k inhabitants"),
                y=alt.Y("country:N", title="Countries", sort=None),
                color=alt.Color('country:N', title="Country"),
                tooltip=[alt.Tooltip('country:N', title='Country'), 
                        alt.Tooltip('per100k:Q', title='Cases per 100k'),
                        alt.Tooltip('inhabitants:Q', title='Inhabitants (n/100k)')]
            )

            st.altair_chart(alt.hconcat(c4, alt.vconcat(c2, c3)), use_container_width=True)
        elif REGION == 'South Asia':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'North Asia':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'East Asia':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'Central Asia':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'West Asia':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'Western Europe':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'Eastern Europe':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'Central Europe':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'Northern Europe':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')
        elif REGION == 'Southern Europe':
            st.info('Tampilkan Maps')
            st.warning('Data belum dimuat! Tampilkan seperti Asia Tenggara')

        st.markdown(f"""\
            <div style="font-size: small">
            ⚠️ Please take the CFR with a grain of salt. The ratio is 
            highly dependend on the total number of tests conducted in a country. In the early stages
            of the outbreak often mainly severe cases with clear symptoms are detected. Thus mild cases
            are not recorded which skews the CFR.
            </div><br/>

            """, unsafe_allow_html=True)

    elif analysis == "Data":

        confirmed, deaths, recovered = read_data()
        st.header("Global datasets")
        st.markdown("""\
            The reported number of confirmed (active), recovered and deceased COVID-19 cases per day. 
            """)

        #Data for confirmed cases
        #Rename for view Maps because on streamlit must 'latitude/lat' or 'longitude/long'
        st.subheader('Confirmed')
        st.dataframe(data=confirmed)
        st.subheader('Deaths')
        st.dataframe(data=deaths)
        st.subheader('Recovered')
        st.dataframe(data=recovered)
    elif analysis == 'Statistical comparison':
        st.warning("Tulis disini!")

    elif analysis == "Country statistics":        

        confirmed, deaths, recovered = read_data()
        
        st.header("Country statistics")
        st.markdown("""\
            The reported number of active, recovered and deceased COVID-19 cases by country """
            f""" (currently only {', '.join(confirmed['Country/Region'])}).  
            """
            """  
            ℹ️ You can select countries and plot data as cummulative counts or new active cases per day. 
            """)

        # selections
        selection = st.selectbox("Select country:", confirmed['Country/Region'])
        cummulative = st.radio("Display type:", ["total", "new cases"])
        #scaletransform = st.radio("Plot y-axis", ["linear", "pow"])
        
        confirmed = confirmed[confirmed["Country/Region"] == selection].iloc[:,3:]
        confirmed = transform(confirmed, collabel="confirmed")

        deaths = deaths[deaths["Country/Region"] == selection].iloc[:,3:]
        deaths = transform(deaths, collabel="deaths")

        recovered = recovered[recovered["Country/Region"] == selection].iloc[:,3:]
        recovered = transform(recovered, collabel="recovered")

        
        df = reduce(lambda a,b: pd.merge(a,b, on='date'), [confirmed, recovered, deaths])
        df["active"] = df.confirmed - (df.deaths + df.recovered)

        variables = ["recovered", "active", "deaths"]
        colors = ["steelblue", "orange", "black"]

        value_vars = variables
        SCALE = alt.Scale(domain=variables, range=colors)
        if cummulative == 'new cases':
            value_vars = ["new"]
            df["new"] = df.confirmed - df.shift(1).confirmed
            df["new"].loc[df.new < 0]  = 0
            SCALE = alt.Scale(domain=["new"], range=["orange"]) 

        dfm = pd.melt(df.reset_index(), id_vars=["date"], value_vars=value_vars)

        # introduce order col as altair does auto-sort on stacked elements
        dfm['order'] = dfm['variable'].replace(
            {val: i for i, val in enumerate(variables[::-1])}
        )

        c = alt.Chart(dfm.reset_index()).mark_bar().properties(height=200).encode(
            x=alt.X("date:T", title="Date"),
            y=alt.Y("sum(value):Q", title="Cases", scale=alt.Scale(type='linear')),
            color=alt.Color('variable:N', title="Category", scale=SCALE), #, sort=alt.EncodingSortField('value', order='ascending')),
            order='order'
        )

        if cummulative != 'new cases':
            st.altair_chart(c, use_container_width=True)
        else:
            # add smooth 7-day trend
            rm_7day = df[['new']].rolling('7D').mean().rename(columns={'new': 'value'})
            c_7day = alt.Chart(rm_7day.reset_index()).properties(height=200).mark_line(strokeDash=[1,1], color='red').encode(
                x=alt.X("date:T", title="Date"),
                y=alt.Y("value:Q", title="Cases", scale=alt.Scale(type='linear')),
            )
            st.altair_chart((c + c_7day), use_container_width=True)
            st.markdown(f"""\
                <div style="font-size: small">Daily reported new cases (incl. 7-day average).</div><br/>
                """, unsafe_allow_html=True)
        pass
Пример #30
0
def app():
    """ Mortality Prediction App """
    st.title("Disease Mortality Prediction App")

    menu = ['Home', 'Login', 'Sign Up']
    submenu = ['Plot', 'Prediction']

    choice = st.sidebar.selectbox(label='Menu', options=menu)

    if choice == 'Home':
        st.subheader("Home")

        st.write("""
            ### What is Hepatitis B?
            A serious liver infection caused by the hepatitis B virus that's easily preventable by a vaccine.\n
            This disease is most commonly spread by exposure to infected bodily fluids.
            Symptoms are variable and include yellowing of the eyes, abdominal pain and dark urine. \
            Some people, particularly children, don't experience any symptoms. \n
            In chronic cases, liver failure, cancer or scarring can occur.\
            The condition often clears up on its own. Chronic cases require medication and possibly a liver\
            transplant.

            ### Symptoms: 
            - Fever, fatigue, muscle or joint pain,
            - Loss of appetitie,
            - Mild nausea and vomitting,
            - Stomach pain,
            - Bloated or swollen stomach,
            - Yellow skin/eyes (called Jaundice)

            ### Treatment:
            The treatment depends on the severity.\n
            The condition often clears up on its own. Chronic cases require medication and possibly a liver\
                transplant. 
            """)

    elif choice == 'Login':
        username = st.sidebar.text_input("Username")
        password = st.sidebar.text_input("Password", type='password')

        if st.sidebar.checkbox("Login"):
            create_usertable()
            hashed_pswd = passowrd_hash(password)
            result = login_user(username, verify_hash(password, hashed_pswd))
            # if password == '12345':
            if result:
                st.success(f"Welcome, {username}.")
                task = st.selectbox(label="Choose a Task to perform:",
                                    options=submenu)

                # plotting data:
                if task == 'Plot':
                    st.header("Data Visualization")

                    # plotting the class plot
                    st.subheader("Looking at the Training Data")
                    df = pd.read_csv(r"data/clean_hepatitis_dataset.csv")
                    st.dataframe(df)

                    plt.figure()
                    sns.countplot(x='class', data=df)
                    plt.xticks(ticks=[0, 1], labels=['Die', 'Live'])
                    plt.ylabel('Count')
                    plt.xlabel('Class')
                    st.pyplot()

                    # plotting frequency distribution
                    st.subheader('Frequency Distribution by Age')
                    freq_df = pd.read_csv(
                        r'data/freq_distribution_hepatitis_dataset.csv')
                    st.dataframe(freq_df[1:])

                    plt.figure()
                    sns.barplot(x='age', y='count', data=freq_df)
                    plt.xlabel('Distribution')
                    plt.ylabel('Count')
                    st.pyplot()

                    features = df.columns.to_list()
                    # plotting relation between any two features:

                    if st.checkbox("Relationship Plot"):
                        x_axis = st.selectbox(label="Select X-axis: ",
                                              options=features)
                        y_axis = st.selectbox(
                            label="Select Y-axis: ",
                            options=[x for x in features if x is not x_axis])
                        plot_relation(x_axis, y_axis, df)

                    # plotting area chart
                    if st.checkbox("Area Chart"):
                        selected_features = st.multiselect("Choose Features:",
                                                           options=features)
                        new_df = df[selected_features]
                        st.area_chart(data=new_df)

                # predictions:
                elif task == "Prediction":
                    st.subheader("Predictive Analysis")
                    user_input = get_user_input()
                    clf = get_model()
                    if st.button('Predict'):
                        prediction = clf.predict([user_input])
                        prob_live = clf.predict_proba([user_input])[0][1]
                        prob_die = clf.predict_proba([user_input])[0][0]
                        if prediction == 1:
                            st.warning(
                                f"Patient has {prob_die:.2f} chances of dying."
                            )
                        elif prediction == 2:
                            st.success(
                                f"Patient has {prob_live:.2f} chances of living"
                            )

                    # Interpretation of our model.
                    if st.checkbox("Interpret the Model result."):

                        df = pd.read_csv(r'data/clean_hepatitis_dataset.csv')
                        feature_names = [
                            'protime', 'sgot', 'bilirubin', 'age',
                            'alk_phosphate', 'albumin', 'spiders', 'histology',
                            'fatigue', 'ascites', 'varices', 'sex',
                            'antivirals', 'steroid'
                        ]
                        x = df[feature_names]
                        class_names = ['Die(1)', 'Live(2)']

                        explainer = LimeTabularExplainer(
                            x.values,
                            feature_names=feature_names,
                            class_names=class_names,
                            discretize_continuous=True)

                        exp = explainer.explain_instance(np.array(user_input),
                                                         clf.predict_proba,
                                                         num_features=14,
                                                         top_labels=1)

                        score_list = exp.as_list()
                        label_limits = [i[0] for i in score_list]
                        label_scores = [i[1] for i in score_list]

                        plt.barh(label_limits, label_scores)
                        st.pyplot()

                        plt.figure(figsize=(20, 10))
                        fig = exp.as_pyplot_figure()
                        st.pyplot()

            else:
                st.warning("Incorrect username/password.")

    elif choice == 'Sign Up':
        new_username = st.text_input("Username")
        new_password = st.text_input("Password", type='password')
        confirm_password = st.text_input("Confir Passoword", type='password')

        if confirm_password == new_password:
            st.success("Password Confirmed.")
        else:
            st.warning("Passwords do not match.")

        if st.button("Submit"):
            create_usertable()
            hashed_new_password = passowrd_hash(new_password)
            add_userdata(username=new_username, password=hashed_new_password)
            st.success("You have successfully created a new account.")
            st.info("Login to get started.")