CoolFace
Apppublic

SheenXO/bayesian_simulator

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
app.py54 linesDownload Raw Back to root
1import streamlit as st2import numpy as np3import pandas as pd4import matplotlib.pyplot as plt5import seaborn as sns6from nltk.tokenize import word_tokenize7import nltk8 9nltk.download('punkt_tab')10 11st.title("๐Ÿ“Š Bayesian Token Co-occurrence Simulator")12 13# User input14user_input = st.text_area("โœ๏ธ Enter your training sentences (one per line):", 15"""16fido loves the red ball17timmy and fido go to the park18fido and timmy love to play19the red ball is timmy's favorite toy20""")21 22sentences = user_input.strip().split('\n')23tokenized = [word_tokenize(s.lower()) for s in sentences if s.strip()]24vocab = sorted(set(word for sentence in tokenized for word in sentence))25token2idx = {word: i for i, word in enumerate(vocab)}26idx2token = {i: word for word, i in token2idx.items()}27 28# Co-occurrence matrix29window_size = 230matrix = np.zeros((len(vocab), len(vocab)))31 32for sentence in tokenized:33    for i, word in enumerate(sentence):34        for j in range(max(0, i - window_size), min(len(sentence), i + window_size + 1)):35            if i != j:36                matrix[token2idx[word]][token2idx[sentence[j]]] += 137 38alpha = st.slider("๐Ÿ”ง Set Bayesian Prior (ฮฑ smoothing)", 0.0, 2.0, 0.1)39posterior = matrix + alpha40 41df = pd.DataFrame(posterior, index=vocab, columns=vocab)42st.subheader("๐Ÿ“ˆ Co-occurrence Heatmap")43fig, ax = plt.subplots(figsize=(10, 8))44sns.heatmap(df, annot=True, cmap="Blues", fmt=".1f", ax=ax)45st.pyplot(fig)46 47# Next-token prediction48selected_word = st.selectbox("๐Ÿ”ฎ Predict next token after:", vocab)49row = posterior[token2idx[selected_word]]50probs = row / row.sum()51prediction = np.random.choice(vocab, p=probs)52 53st.markdown(f"**Predicted next token:** `{prediction}`")54