Saravanan666/pypi-org huggingface dataset:
Package: bayesfrag
BayesFrag: Bayesian estimation of empirical seismic fragility functionsBayesFrag is an open-source Python library to perform Bayesian parameter estimation of empirical seismic fragility models. The methodology is presented inBodenmann L., Baker J.W. , Stojadinović B. (2023): "Accounting for ground motion uncertainty in empirical seismic fragility modeling", Engineering Archive [preprint],doi:10.31224/3336.Seismic fragility functions provide a relationship between damage and a ground motion intensity measure (IM). Empirical fragility functions are estimated from damage survey data collected after past earthquakes. This is challenging, because the IM values that caused the observed damage are uncertain. BayesFrag computes the joint posterior distribution of fragility function parameters and IM values at the sites of the surveyed buildings.To avoid any additional dependency on a specific library of ground motion models (GMMs), the GMM estimates are computed prior and separate to the fragility parameter estimation.Getting startedTo allow for a smooth start, we offer three tutorials that can be opened on a hosted Jupyter notebook service (e.g., Google Colab).Thefirst tutorialreproduces the results of the one-dimensional example from the manuscript and explains the implementation of the proposed estimation approach:Thesecond tutorialshows how the Bayesian approach can be applied to a realistic damage survey data set. The notebook can easily be modified and extended such that analysts can apply BayesFrag to their data sets of interest:Thethird tutorialexplains the computation of the GMM estimates, which is done prior and separate to the fragility parameter estimation:StructureThe folderbayesfragcontains the main codebase of the BayesFrag package.The folderdatacontains the data used in the two tutorials.The folderresultscontains the results illustrated in the manuscript.The notebookfigures.ipynbreproduces the figures shown in the manuscript using utility functions fromutils_plotting.py.The scriptmain_aquila_casestudy.pyperforms all computations - from parameter estimation to post-processing - to reproduce the results presented in the paper (and stored in the folderresults). This script is computationally expensive and causes high memory demand. The computations were performed on a NVIDIA V100 tensor core GPU with 25 GB of RAM and we do not recommend to run this script on a standard personal computer.InstallationBayesFrag can be installed aspip install bayesfragIt is good practice to do the installation in a new virtual environment, for example withvenvor withminiconda. BayesFrag was tested with Python >= v3.10.ContactBayesFrag is an open-source software. If you are interested in contributing to the project or have any questions, comments, or suggestions, please contact Lukas Bodenmann at bodenmann (at) ibk.baug.ethz.ch.AcknowledgmentsWe gratefully acknowledge support from theETH Risk Center("DynaRisk", Grant Nr. 395 2018-FE-213) and from theChair of Earthquake Engineering and Structural Dynamicsat ETH Zurich.LicenceBayesFrag is released under theBSD-3-Clause license.
Package: bayesHC1
Installation InstructionsRun following code in terminal:
python3 -m pip install bayesHC1Then import package and load cython as follows:
import bayesHC1DocumentationbayesHC.bayes_hier_clust(data_vec, alpha, alpha0, beta, kappa, mu)Given a tuple of datapoints, build a hierarchical cluster tree. Algorithm will continue merging clusters until there is only one overarching cluster. This algorithm is recommended for clustering $<$23 observations.Parameters:
alpha : the expected number of clustersalpha0 : scale hyperparameter for gamma prior 

beta : location hyperparameter for gamma prior 

kappa : precision hyperparameter for normal prior

mu : mean hyperparameer for normal priorReturns:nested tupleReturns a tuple with the following structure:
cluster = (c_num,left,right,value,n_k,p_k,d_k)Where:
    c_num : the number of the cluster
    left : the entire cluster tuple for one subcluster
    right : the entire cluster tuple for the other subcluster
    value : all data values included in the cluster
    n_k : number of datapoints in the cluster
    p_k : the prior on merging
    d_k : a weight on the volume of data in pairs of clusters on the subtree T_kExample<<<import pandas as pd
<<<df_sim = pd.read_table('simulated_data.csv',delimiter = ",")
<<<value = tuple([points] for points in df_sim.loc[:4,'values'])
<<<mu, kappa = 0, 100 # mean and standard deviation
<<<alpha, beta = 2,10 # scale and location
<<<z = bayes_hier_clust(value, alpha, beta, kappa,mu)
<<<z[(9,
(4, 0, 0, [24.649825190000001], 1, 1, 2.0),
(8,
(5, 0, 0, [20.543137890000001], 1, 1, 2.0),
(7,
(1, 0, 0, [19.404575810000001], 1, 1, 2.0),
(6,
(2, 0, 0, [4.4017292919999997], 1, 1, 2.0),
(3, 0, 0, [10.766117830000001], 1, 1, 2.0),
[4.4017292919999997, 10.766117830000001],
2,
0.3333333432674408,
6.0),
[19.404575810000001, 4.4017292919999997, 10.766117830000001],
3,
0.25,
16.0),
[20.543137890000001,
19.404575810000001,
4.4017292919999997,
10.766117830000001],
4,
0.27272728085517883,
44.0),
[24.649825190000001,
20.543137890000001,
19.404575810000001,
4.4017292919999997,
10.766117830000001],
5,
0.3529411852359772,
136.0)]z[1]
(4, 0, 0, [24.649825190000001], 1, 1, 2.0)Last updated on April 30, 2019.
Package: bayesianbandits
bayesianbanditsBayesian Multi-Armed Bandits for PythonProblem: Despite having a conceptually simple interface, putting together a multi-armed bandit in Python is a daunting task.Solution:bayesianbanditsis a Python package that provides a simple interface for creating and running Bayesian multi-armed bandits. It is built on top ofscikit-learnandscipy, taking advantage of conjugate priors to provide fast and accurate inference.While the API is still evolving, this library is already being used in production for marketing optimization, dynamic pricing, and other applications. Are you usingbayesianbanditsin your project? Let us know!FeaturesSimple API:bayesianbanditsprovides a simple interface - most users will only need to callpullandupdateto get started.Fast:bayesianbanditsis built on top of already fast scientific Python libraries, but, if installed, will also use SuiteSparse to further speed up matrix operations on sparse matrices. Handling tens or even hundreds of thousands of features in a sparse model is no problem.scikit-learn compatible: Use sklearn pipelines and transformers to preprocess data before feeding it into your bandit.Flexible: Pick from a variety of policy algorithms, including Thompson sampling, upper confidence bound, and epsilon-greedy. Pick from a variety of prior distributions, including beta, gamma, normal, and normal-inverse-gamma.Extensible:bayesianbanditsprovides simple interfaces for creating custom policies and priors.Well-tested:bayesianbanditsis well-tested, with nearly 100% test coverage.Compatibilitybayesianbanditsis tested with Python 3.9, 3.10, 3.11, and 3.12 withscikit-learn1.2.2, 1.3.2, and 1.4.0.Getting StartedInstall this package from PyPI.pip install -U bayesianbanditsDefine a LinearUCB contextual bandit with a normal prior.importnumpyasnpfrombayesianbanditsimport(Arm,NormalInverseGammaRegressor,ContextualAgent,UpperConfidenceBound,)arms=[Arm(1,learner=NormalInverseGammaRegressor()),Arm(2,learner=NormalInverseGammaRegressor()),Arm(3,learner=NormalInverseGammaRegressor()),Arm(4,learner=NormalInverseGammaRegressor()),]policy=UpperConfidenceBound(alpha=0.84)Instantiate the agent and pull an arm with context.agent=ContextualAgent(arms,policy)context=np.array([[1,0,0,0]])# Can be constructed with sklearn, formulaic, patsy, etc...# context = formulaic.Formula("1 + article_number").get_model_matrix(data)# context = sklearn.preprocessing.OneHotEncoder().fit_transform(data)agent.pull(context)Update the bandit with the reward.agent.update(context,np.array([15.0]))That's it! Check out thedocumentationfor more examples.
Package: bayesian-classifier
The bayesian classifier utilizes Bayes Theorem to implement a categorical classifier. The current package contains classes that implement both Full Bayes classifier and Naïve Bayes Classifier, providing a CLI interface as well.Runing Bayes Classifier on your databayesian_classifierfull_bayestrainresource/iristrain3.txt--sep","bayesian_classifierfull_bayestestfull_bayes.modelresource/iristest3.txt
Package: bayesian-cut
The Bayesian Cut Python package provides an easy to use API for the straight-forward application of Bayesian network
cuts using a full Bayesian inference framework based on the Gibbs-Sampler using the degree corrected Stochastic
Blockmodel (dc-SBM) or the Bayesian Cut (BC).
Furthermore it provides modularity, ratio-cut and norm cut based spectral network cut methods.
It also provides a rich visualization library that allow an easy analysis of posterior solution landscapes and network
cuts obtained by the various methods.Jupyter Notebooks with examples on how to use the package can be found athttps://github.com/DTUComputeCognitiveSystems/bayesian_cut/tree/master/examplesInstallationInstall the package for Python3 using the following command. Some
dependencies might require an upgrade (scikit-learn, numpy and
scipy).$ pip install bayesian_cutNow you can import the bayesian cut class by typingfrom bayesian_cut.cuts import ModelQuick StartUse the bayesian_cut package for performing graph cuts# Load the packagefrombayesian_cut.data.loadimportload_datafrombayesian_cut.cuts.bayesian_modelsimportModel# Load an example networknetwork_name='karate'X,Y=load_data(network=network_name,labels=True,remove_disconnected=True)# Set the parameters for the modeln_samples_per_chain=75n_chains=15C=2model_params={'alpha_in':1e-2,'beta_in':1e-2,'alpha_out':1e-2,'beta_out':1e-2,'b':1,'gamma':3}# Define the modelBC=Model('ShiftedApproximateBayesianCommunityDetection',X,model_params,Y=Y,C=C,block_sampling=False,marginalize_phi=True)# Add the number of chains to runBC.add_chains(number_of_chains=n_chains)# Run the Gibbs samplerBC.run_chains(n_samples=n_samples_per_chain,n_prior_updates=20,verbose=2,save_all_samples=False,parallel=True)# Obtain the cut with the highest log-likelihoodgraph_cut_z_vector=BC.get_best_chain().max_log_lik_z_# Plot the cut as an adjacency matrixfrombayesian_cut.utilsimportutilsutils.cluster_plot(BC)# Done
Package: bayesian-mab
Bayesian Multi Armed Bandit🚀 OverviewA Bayesian Multi-Armed Bandit is a statistical model used in decision-making processes under uncertainty. It is a variation of the classic multi-armed bandit problem, where you have multiple options (each represented as an arm of a bandit, or slot machine) and you must choose which to pursue to maximize your rewards. The Bayesian aspect of this model comes into play by using Bayesian inference to update the probability distribution of the rewards of each arm based on prior knowledge and observed outcomes. This approach allows for a more nuanced and dynamically adaptive decision-making process, as the model continuously updates its beliefs and predictions about the performance of each option in real time. It's especially useful in scenarios where the environment changes or when dealing with limited information.Between several use cases, we can highlightOnline adversisingWebsite optimizationPersonalizationClinical trials💻 Example UsageFor Bayesian Multi Armed Bandits (MAB), first define initialize the BayesianMAB and provide it the arm object with an index and a provided name, this will be useful for determining the winner later on.We provide an example of for loops giving positive (1) and negative (0) rewards to each arm, you can add it as you want.At any moment, we can check it we already have a winner, using the BayesianMAB.check_for_end method.frombayesian_mabimportBayesianMAB,BinaryRewardimportnumpyasnpbinary_reward=BinaryReward()bayesian_mab=BayesianMAB(arms=[BayesianArm(index=0,arm_name="Ad #1"),BayesianArm(index=1,arm_name="Ad #2"),BayesianArm(index=2,arm_name="Ad #3"),])foriinrange(4):binary_reward.update_reward(np.random.binomial(1,p=0.9))bayesian_mab.update_arm(chosen_arm=0,reward_agent=binary_reward)foriinrange(1500):binary_reward.update_reward(np.random.binomial(1,p=0.3))bayesian_mab.update_arm(chosen_arm=1,reward_agent=binary_reward)foriinrange(1500):binary_reward.update_reward(np.random.binomial(1,p=0.9))bayesian_mab.update_arm(chosen_arm=2,reward_agent=binary_reward)flg_end,winner_arm=bayesian_mab.check_for_end(winner_prob_threshold=0.80)print("Is there a winner?{}. Winner:{}".format(flg_end,winner_arm))Acknowledgments and ReferencesCook, J., 2005.Exact calculation of beta inequalities. Houston: University of Texas, MD Anderson Cancer Center. AvailablehereSlivkins, A., 2019.Introduction to multi-armed bandits. Foundations and Trends® in Machine Learning, 12(1-2), pp.1-286. AvailablehereWhite, J., 2013.Bandit algorithms for website optimization." O'Reilly Media, Inc.".Bruce, P., Bruce, A. and Gedeck, P., 2020.Practical statistics for data scientists: 50+ essential concepts using R and Python. O'Reilly Media.Praise on Vincenzo Lavorini forthisTowards Data Science blog post.
Package: bayesian-models
bayesian-modelsbayeian-modelsis a small library build on top ofpymcthat
implements common statistical modelsbayesian_modelsaims to implementsklearnstyle classes,
representing general types of models a user may wish to specify. Since
there is a very large variety of statistical models available, only some
are included in this library in a somewhat ad-hoc  manner. The following
models are planned for implementation:BEST (Bayesian Estimation Superceeds the t Test) := Statistical
comparisons' between groups, analoguous to hypothesis testing
(COMPLETED)Installationbayesian-modelscan be installed with pippip install bayesian-modelsNewer releases are first published to TestPyPI. They are installable as
followspip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple bayesian-modelsTo install from git:pip install git+ssh://git@github.com/AlexRodis/bayesian-models.gitTo install the developement version run:pip install 'bayesian_models[dev]@ git+ssh://git@github.com/AlexRodis/bayesian_models.git@dev-main'It is often desirable to run models with a GPU if available. At present,
there are known issues with thenumpyrodependency. Only these
versions are supported:jax==0.4.1
jaxlib==0.4.1To attempt to install with GPU support run:pip install 'bayesian_models[GPU]@git+ssh://git@github.com/AlexRodis/bayesian-models.git'Note: the GPU version is unstableYou must also set the following environment variable prior to all other
commands, including importsXLA_PYTHON_CLIENT_PREALLOCATE=falseThese dependencies are only required withpymc.sampling.jax.sample_numpyro_nutsand if using the default options
can be ignored
Package: bayesiannetworkai
bayesiannetworkaiA package for using Bayesian NetworksInstallation$pipinstallbayesiannetworkaiUsageTODOContributingInterested in contributing? Check out the contributing guidelines. Please note that this project is released with a Code of Conduct. By contributing to this project, you agree to abide by its terms.Licensebayesiannetworkaiwas created by GrupoAI. It is licensed under the terms of the MIT license.Creditsbayesiannetworkaiwas created withcookiecutterand thepy-pkgs-cookiecuttertemplate.
Package: bayesian-network-clb
Laboratorio #2 - Redes BayesianasUniversidad del Valle de GuatemalaInteligencia Artificial - SecciÃ³n 20InstalaciÃ³npipinstallComandos y uso de la libreria- Llamar/Instanciar la Red Bayesianafrombayesian_network_climportBayesianNetworkbn=BayesianNetwork()- Agregar nodosadd_nodes(self,all_nodes:list)->None- Agregar probabilidades en un nodoadd_probs(self,node:str,probs:list)->None- Mostrar la Red Bayesianashow_bayesian_network(self)->str- Mostrar la Red Bayesiana y sus probabilidadesshow_bayesian_network_and_probs(self)->str- Verificar si el arbol bayesiano esta completoinference_by_enumeration(self,**conditions)->float- Inferencia Probabilisticabayesian_network_complete(self)->bool
Package: bayesian-networks
Bayesian NetworksImplementation for bayesian network withEnumerationRejection SamplingLikelihood WeightingInstallsudopip3install--upgradebayesian-networksHow to useimportbayesian_networkstestcase={'netid':"burglary",'query':('B','j,m'),'result':{True:0.28,False:0.72},'samples':10000,}enum=bayesian_networks.Enumeration()results=enum.run(testcase)bayesian_networks.print_result(results,showcolors=True)rejection=bayesian_networks.RejectionSampling()results=rejection.run(testcase)bayesian_networks.print_result(results,showcolors=True)weighting=bayesian_networks.LikelihoodWeighting()results=weighting.run(testcase)bayesian_networks.print_result(results,showcolors=True)
Package: bayesian-networks-rey20074
Redes BayesianasUna librería para construir redes bayesianas y realizar inferencia probabilística.InstalaciónCon el manejador de paquetes pip:pip install bayesian-networks-rey20074Usofrom src.bayesian_networks_rey20074.BayesianNetwork import BayesianNetwork, Node

node_b = Node("b", 0.001)

node_e = Node("e", 0.002)

node_a = Node("a", multiple_parents=True)
node_a.add_connection_multiple_parents({"b": True, "e": True}, 0.95)
node_a.add_connection_multiple_parents({"b": True, "e": False}, 0.94)
node_a.add_connection_multiple_parents({"b": False, "e": True}, 0.29)
node_a.add_connection_multiple_parents({"b": False, "e": False}, 0.001)
node_a.add_connection("j", 0.9, True)
node_a.add_connection("j", 0.05, False)
node_a.add_connection("m", 0.7, True)
node_a.add_connection("m", 0.01, False)

node_j = Node("j")
node_m = Node("m")


network = BayesianNetwork()
network.add_node(node_a)
network.add_node(node_b)
network.add_node(node_e)
network.add_node(node_j)
network.add_node(node_m)
print('## GET PROBABILISTIC INFERENCE')
print(network.probabilistic_inference("m"))

print('\n## GET COMPACT REPRESENTATION')
representation = network.get_compact_representation()
print(representation)

print('## GET ELEMENTS USED FOR ALGORITHM')
collections = network.get_all_representations()
for x in collections:
    print(x)

print('\n## GET IS FULLY DESCRIBED')
desc = network.is_fully_described()

if (desc == True):
    print("Red Bayesiana Descriptiva")
else:
    print("Red Bayesiana No Descriptiva")APISe incluyen las siguientes clasesClase Nodeinit(self, title: str, probability_of_success: float = None, multiple_parents: bool = False)add_connection(self, next_node_title: str, probability_of_success: float, parent_was_succesful: bool)get_children(self)get_children_title(self)delete_connection(self, node_title: str)delete_connection(self, node_title: str, parent_was_succesful: bool)add_connection_multiple_parents(self, parent_nodes: dict, probability_of_success: float)edit_connection(self, node_title: str, probability_of_success: float)Clase BayesianNetworkinit(self)get_nodes(self)get_node(self, node_title: str)delete_node(self, node_title: str)add_node(self, node: Node)replace_node(self, node_title: str, new_node: Node)get_parent(self, child_node_title: str)get_parents(self, child_node_title: str)one_parent_probabilistic_inference(self, node_title: strmultiply_list(myList: list)multiple_parents_probabilistic_inference(self, node_title: str)probabilistic_inference(self, node_title: str)get_compact_representation(network)is_fully_described(self)
Package: bayesianpia2
Lab 2 IAinit(self, nodes, edges): el constructor de la clase. Recibe una lista de nodos y un diccionario de bordes, donde las claves son los nombres de los nodos y los valores son listas de los nombres de los nodos padre.is_fully_described(self): comprueba si se han definido los factores de probabilidad de todos los nodos de la red. Devuelve true si estoe es cierto y false si nocompact(self): devuelve una cadena que representa la red bayesiana de forma compacta.representation(self): devuelve una cadena que representa la red bayesiana de forma detallada. Incluye la tabla de probabilidad de cada nodo dada la probabilidad condicional de sus padres.compute_factor(self, node, evidence={}): calcula el factor de probabilidad del nodo node dado un diccionario de evidencia.compute_conditional_probability(self, node, parent_state): calcula la probabilidad condicional del nodo node dada la evidencia en el diccionario parent_state.
Package: bayesian-priors
Bayesian-priors is a package for visualizing prior distributions in the context of bayesian inference. The following continuous distributions are supported: normal, student-t, exponential, gamma, inverse gamma, weibull, pareto, gumbel, log-normal, cauchy, beta. In the dashboard, user inputs their desired lower and upper bounds, along with the % mass in-between. The dashboard will then display a set of  parameters that generates such distribution.
Package: bayesianroc
bayesianrocbayesianrocis a Python package written by Franz Mayr and André Carrington, for Bayesian analysis of ROC plots (including Binary Chance), over the whole plot or in a region of interest.Please read 'Bayesian ROC Tookit Documentation.docx' from the Github page for details.FeaturesClasses:BayesianROC: a subclass of DeepROC (from the Deep ROC Toolkit).  It computes measures related to the Chance and Bayesian iso performance baselines and produces associated plots.Example of Classification and AnalysisTest_Binary_Chance.py: creates a BayesianROC object and performs classification and analysis.  Questions are asked as input: you may hit enter to accept defaults, except it is recommended that you change the costs to see the effect of Binary Chance.InstallationThe package can be installed from PyPi:pipinstallbayesianroc
Package: bayesim
DescriptionThe little home on the internet for our adaptive grid sampled Bayesian inference code. Check it out if you want to compute probability distributions over ~1-10 input parameters to a relatively computationally expensive (10’s of core-seconds per evaluation) model.More detailed documentationhere.Installation and UsageInstall usingpipinstallbayesimInformationAuthors:Rachel C. Kurchin and Giuseppe RomanoVersion:0.10.0 as of August 2023
Package: bayesint
bayesintThis repository includes the Python code for calculating Bayesian credible interval of ratios of independent beta distributions. It has been used inMethods for calculating credible intervals for ratios of beta distributions with application to relative risks of premature death during the second plague pandemicGetting StartedPrerequisitesPython 2.7+InstallationClone the repository then runpythonsetup.pyinstallUsageTo get the relative risk of a contingency table given by+_Total+P = 56M- PM = 366-C = 126N - CN = 354TotalC + PN - C + M - PN + Mrunfrombayesintimportrel_riskrel_risk(56,126,366,354)# 236/549and to obtain the equal-tailed quantile interval for the data given in the contingency table runfrombayesintimporteqt_int_fraceqt_int_frac(56,126,366,354,(0,0,0,0),"risk",0.05,"estim")# (236/549, 0.184135819539239, 0.667343920284484)AuthorsMaria Bekker-Nielsen Dunbar and Tom FinnieContributingThis project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to theContributor Covenantcode of conduct.Fork itCreate your feature branch (git checkout -b my-new-feature)Commit your changes (git commit -am 'Add some feature')Push to the branch (git push origin my-new-feature)Create a new Pull RequestLicensePublic Health England 2017This project is licensed under the Open Government License, seeLICENSEfor details