Team Ai
Apppublic

chasemathsi/BayesianInference

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
example.py107 linesDownload Raw Back to root
1import gradio as gr2import numpy as np3import matplotlib.pyplot as plt4from scipy.stats import norm, binom, beta, gamma, poisson5 6import pandas as pd7 8class Prior():9    def __init__(self, distribution, param1, param2):10        self.distribution = distribution11        self.param1 = param112        self.param2 = param213        self.left = distribution.ppf(0.0001, param1, param2)14        self.right = distribution.ppf(0.9999, param1, param2)15 16    def plot(self):17        x = np.linspace(self.left, self.right, 100)18        y = self.distribution.pdf(x, self.param1, self.param2)19        20        # Set common axis limits for both plots21        plt.xlim(self.left, self.right)22        plt.ylim(0, max(y) * 1.1)23        24        return plt.plot(x, y)25 26 27class SamplingModel():28    def __init__(self, distribution, data):29        self.data = pd.read_csv(data.name, header=None).to_numpy().squeeze()30        self.distrubution = distribution31 32    def plot(self):33        plt.hist(self.data, density=True)34        35        # Set common axis limits for both plots36        left, right = plt.xlim()37        plt.xlim(left, right)38        39        plt.show()40 41 42 43 44class PosteriorModel():45    def __init__(self, distribution):46        pass47 48        49 50 51 52 53def run(data, prior_dist, sampling_dist, param1, param2):54    plt.figure(figsize=(8*3, 5*3))55    dists = {56        "Normal":norm,57        "Beta":beta,58        "Gamma":gamma59    }60 61    # set up prior and sampling model62    prior = Prior(dists[prior_dist], param1, param2)63    model = SamplingModel(sampling_dist, data)64    prior.plot()65    model.plot()66    plt.grid()67    plt.autoscale(tight = True)68    69    # Save and return the plot70    plt.tight_layout()71    return plt72 73 74# demo = gr.Interface(75#     fn=run,76#     inputs=[77#         gr.components.File(label="Upload CSV"),78#         gr.components.Dropdown(79#             choices=["Normal", "Binomial", "Beta", "Gamma", "Poisson"], 80#             label="Choose Prior Distribution"81#         ),82#         gr.components.Dropdown(83#             choices=["Normal", "Binomial", "Beta", "Gamma", "Poisson"], 84#             label="Choose Sampling Distribution"85#         ),86#         gr.components.Number(label=r"\theta"),87#         gr.components.Number(label=r"\sigma^2")88#     ],89#     outputs="plot"90# )91 92def predict(img):93    x = torch.tensor(img, dtype=torch.float32).unsqueeze(0).unsqueeze(0) / 255.94    with torch.no_grad():95        out = model(x)96    probabilities = torch.nn.functional.softmax(out[0], dim=0)97    values, indices = torch.topk(probabilities, 5)98    confidences = {LABELS[i]: v.item() for i, v in zip(indices, values)}99    return confidences100 101gr.Interface(fn=predict,102             inputs="sketchpad",103             outputs="label",104             live=True).launch()105 106# demo.launch()107