Home

Package `HydeNet`

image

Contents

1. writeNetworkModel RE EE ET OE BEES OER R topics documented Hyde package 3 Hyde package Hydbrid Decision Networks Description Facilities for easy implementation of hybrid Bayesian networks using R Bayesian networks are directed acyclic graphs representing joint probability distributions where each node represents a random variable and each edge represents conditionality The full joint distribution is therefore factorized as a product of conditional densities where each node is assumed to be independent of its non desendents given information on its parent nodes Since exact closed form algorithms are computationally burdensome for inference within hybrid networks that contain a combination of continuous and discrete nodes particle based approximation techniques like Markov Chain Monte Carlo are popular We provide a user friendly interface to constructing these networks and running inference using rjags Econometric analyses maximum expected utility under competing policies value of information involving decision and utility nodes are also supported bindPosterior Bind Posterior Distributions Description After determining the posterior distributions are satisfactory it can be advantageous to bind the posterior distributions together in order to aggregate values and perform other manipulations and analyses Usage bindPosterior hydePost relabel_factor TRUE Arguments hydePost An obj
2. Author s Jarrod Dalton and Benjamin Nutter Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat data PE Net lt setDecisionNodes Net treat compiledNet lt compileJagsModel Net n chains 5 x Generate the posterior distribution for the model but not the x decision model Posterior lt HydePosterior compiledNet variable names c d dimer death n iter 1000 Posterior x Generate the posterior for the decision model Decision lt compileDecisionModel Net n chains 5 rewriteHydeFormula 31 Posterior decision lt HydePosterior Decision variable names c d dimer death n iter 1000 rewriteHydeFormula Rewrite HydeNetwork Graph Model Formula Description This is a convenience function used to assist in the updating of HydeNetwork network objects It makes it possible to add and subtract individual parent relationships without deleting an entire node It s still a work in progress Usage rewriteHydeFormula old_form new_form Arguments old_form The current formula in a HydeNetwork object new_form The formula specifications to be added Details To allow changes to be made on the node parent level the formulae are broken down into a vector of component where each element identifies a unique parent child relationship So if a node has rep resentation nodeA
3. treat d dimerxangio death pextreat data PE Net lt setDecisionNodes Net treat plot Net decision1 lt compileDecisionModel Net ttx An effectively equivalent call as the previous decision2 lt compileDecisionModel Net policyMatrix Net x Using a customized policy matrix x Note this is a bit of nonsense you can t decide if a test is negative tx or positive but we ll do this for illustration custom_policy lt policyMatrix Net treat No angio c Negative Positive decision3 lt compileDecisionModel Net custom_policy compileJagsModel Compile Jags Model from a Hyde Network Description Generates the JAGS code from the Hyde network and uses it to create an object representing a Bayesian graphical model Usage compileJagsModel network data NULL Arguments network An object of class HydeNetwork compileJagsModel 11 data A list of data values to be observed in the nodes It is passed to the data argu ment of rjags jags Alternatively a data frame representing a policy matrix may be provided to compile multiple JAGS models Additional arguments to be passed to jags model Details compileJagsModel is a partial wrapper for jags model Running compileJagsModel network is equivalent to running jags model textConnection writeNetworkModel network Value Returns a compiledHydeNetwork object The jags element of this object is suitable to pass to
4. Suggests knitr survival testthat VignetteBuilder knitr SystemRequirements JAGS http mcmc jags sourceforge net LazyLoad yes LazyData true URL https github com nutterb HydeNet BugReports https github com nutterb HydeNet issues 1 NeedsCompilation no Repository CRAN Date Publication 2015 10 12 00 47 40 R topics documented Index Hyde package bindPosterior BJDealef o coce cb baa AA AAA BlackJack ina e a a a WAA BlackJackTrain compileDecisionModel compileJagsModel Cities ott he De oe hs amp Ge amp Sotho ezpectedVariables faCtOTREGEX sg eee ee ee wR HydeNetwork 2 HydePosterior HydeUtilities Jags Disisi epai a Aaaa jagsFunctions mergeDefaultPlotOpts modelToNode PE egos cas Beh a i Ge AMS hele Ee EG plot HydeNetwork policyMatrix print ep is se Gad WA Sle eda RR Re BRek print HydeNetwork print HydePosterior rewriteHydeFormula setDecisionNodes SENOS 3 2 cand el Ewe eas setNodeModels TranslateFormula update HydeNetwork vecetofProb s s sea e ee Pe OS writeJagsFormula writeJagsModel
5. coda samples Otherwise the primary function of the object is plotting the network with observed data shown Author s Benjamin Nutter See Also jags model Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat data PE compiledNet lt compileJagsModel Net n chains 5 x Generate the posterior distribution Posterior lt HydePosterior compiledNet variable names c d dimer death n iter 1000 Posterior x For a single model ie not a decision model the user may choose to x use the code rjags function code coda samples ttx However this does not have a succinct print method s lt coda samples compiledNet jags variable names c d dimer death n iter 1000 12 cpt cpt Compute a conditional probability table for a factor given other fac tors Description The function cpt operates on sets of factors Specifically it computes the conditional probability distribution of one of the factors given other factors and stores the result in a multidimensional array inputCPT is a utility function aimed at facilitating the process of populating small conditional probability distributions i e those for which the response variable doesn t have too many levels there are relatively few independent variables and the independent variables also don t have too
6. package Hyde This is a utility function used only within setNode and is not visible to the user Author s Jarrod Dalton and Benjamin Nutter jagsDists JAGS Probability Distributions Description A dataset listing the JAGS probability distributions and their parameters Usage jagsDists 22 jagsFunctions Format A data frame with 30 rows and 7 variables DistName Distribution Name FnName Function Name xLow Minimum value for x the random variable xHigh Maximum value for x the random variable Parameters Names of the parameters paramLimit Limits on the parameter paramLogic The text of a logical check used in setNode to ensure stated parameters are valid Source http people math aau dk kkb Undervisning Bayes14 sorenh docs jags_user_manual pdf jagsFunctions JAGS Functions Compatible with R Description A dataset listing the JAGS functions and their R equivalents Usage jagsFunctions Format A data frame with 30 rows and 3 variables jags_function JAGS function name r_function R function Name r_package R package where the function is found Source http people math aau dk kkb Undervisning Bayes14 sorenh docs jags_user_manual pdf mergeDefaultPlotOpts 23 mergeDefaultPlotOpts rdname plot HydeNetwork Description rdname plot HydeNetwork Usage mergeDefaultPlotOpts network node df Arguments network a HydeNetwork object node df A data frame of
7. 1 6 rmultinom n 1 prob c 4 3 15 10 03 02 di2 as factor 1 6 rmultinom n 1 prob rev c 4 3 15 10 03 02 di3 as factor 1 6 rmultinom n 1 prob c 15 10 02 3 4 03 cpt1 lt cpt di3 dil di2 data cpti dil 1 di2 4 Pr di3 dil 1 di2 4 cpt1 1 4 cpt1 1 4 plyr aaply cpt1 c 1 2 sum card dil card di2 matrix of ones l lt list y di3 x c di1 di2 all cpt 1 data cpt1 Not run 14 expected Variables inputCPT wetGrass rain morning inputCPT wetGrass rain morning factorLevels lt list wetGrass c dry moist VeryWet rain c nope yep morning c NO YES reduce FALSE End Not run expectedVariables List Expected Parameter Names and Expected Variables Names Description To assist in formula that defines the relationship to a node expectedVariables returns to the console a sample string that can be pasted into setNode and populated with the desired coefficients Usage expectedVariables network node returnVector FALSE expectedParameters network node returnVector FALSE Arguments network A HydeNetwork object node A node name within network returnVector Logical If FALSE the sample string for use in setNode is returned Otherwise the vector of parent names is returned Details Each node is calculated as a model of its parents If no training data are pro
8. 36 TranslateFormula g7 lt glm death pe treat data PE family binomial Net2 lt setNodeModels Net gl g2 g3 g4 g5 86 87 print Net writeNetworkModel Net pretty TRUE TranslateFormula Translate R Formula to JAGS Description While most functions available in JAGS have equivalents in R they don t always use the exact same names R formulas are converted to character strings function names translated and the corresponding JAGS formula is returned Usage rToJags f Arguments f R formula object Details Only a limited subset of R functions are recognized here but no attempt is made to restrict the user to functions that will be recognized by JAGS For now the user should remain aware of what functions are available in JAGS and only use the corresponding functions in R The JAGS functions may be referenced in the JAGS user manual see References The corresponding R functions are listed in the jagsFunctions data set use data jagsFunctions to review Author s Jarrod Dalton and Benjamin Nutter References http people math aau dk kkb Undervisning Bayes14 sorenh docs jags_user_manual pdf update HydeNetwork 37 update HydeNetwork Update Probabilistic Graphical Network Description Add or remove nodes or add parents within a HydeNetwork model Usage S3 method for class HydeNetwork update object formula Arguments object A HydeNetwork object formula A f
9. it may be better to leave this option FALSE so that the models can all be compiled together especially if you are working interactively Using fitModel TRUE will cause the model to be fit and the JAGS code for the parameters to be stored in the nodeParams attribute Validation The validation of parameters is performed by comparing the values provided with the limits defined in the jagsDists paramLogic variable look at data jagsDists data HydeNet For most node types validation will be peformed for numeric variables For deterministic variables the validation will only check that the parameter definition is a formula It is possible to pass character strings as definitions but when this is done HydeNet assumes you are passing JAGS code Unfortunately HydeNet doesn t have to capability to validate JAGS code so if there is an error in the character string definition it won t show up until you try to compile the network If you pass a character string as a parameter and leave validate TRUE a message will be printed to indicate that validation is being ignored This message can be avoided by using validate FALSE The two exceptions to this rule are when you pass fromFormula and fromData as the param eter definition These will skip the validation without warning since the definition will be built by HydeNet and be proper JAGS code barring any bugs of course Author s Jarrod Dalton and Benjamin Nutter Examples d
10. nodeBxnodeC it will be broken down to nodeA nodeB nodeA nodec After decomposing the formulae any instances of a component in form that are subtracted in form2 are removed Next all added components in form2 that do not already exist in form are added Lastly the parents of each node are combined and the specification of the network is written Author s Jarrod Dalton and Benjamin Nutter 32 setNode setDecisionNodes Classify Multiple Nodes as Decision or Utility Nodes Description Depending on how your Hyde Network was built you may not have had the opportunity to declare which nodes are decision or utlity nodes For instance when passing a list of models there is no way to indicate in the model object that the node should be considered a decision node As a matter of convenience these function will set any nodes indicated to decision or utility nodes It will make no other modifications to a node s definition Usage setDecisionNodes network setUtilityNodes network Arguments network A Hyde Network object Networks to be classified as decision nodes These may be quoted or unquoted Author s Jarrod Dalton and Benjamin Nutter setNode Set Node Relationships Description The relationship between a node and its parents must be defined before the appropriate JAGS model statement can be constructed setNode is the utility by which a user can define the distribution of the node and its rela
11. on 1 000 Black Jack hands Usage BlackJackTrain Format A data frame with 10000 rows and 7 variables dealerUpcard The card in the dealer s hand visible to all players card1 Value of the first card card2 Value of the second card initialPoints Total points with the two cards hitl Binary variable indicating if a hit was taken card3 Value of the third card pointsAfterCard3 Total points with three cards hit2 Binary variable indicating if a hit was taken card4 Value of the fourth card pointsAfterCard4 Total points with four cards hit3 Binary variable indicating if a hit was taken card5 Value of the fifth card pointsAfterCard5 Total points with five cards compileDecisionModel 9 Source Bicycle Cards Blackjack Retrieved from http www bicyclecards com card games rule blackjack compileDecisionModel Compile JAGS Models to Evaluate the Effect of Decisions in a Network Description Nodes at which a decision can be made such as the decision to test or not test treat or not treat or use open or robotic surgery may impact the outcome for a subject These types of decisions may not be truly random and understanding how these decisions may impact downstream outcomes may be beneficial to making the decision Compiling the decision network permits the network to be evaluated under the conditions of each set of decisions separately Usage compileDecisionModel network policyMatrix NULL data NULL Arguments network
12. or not treatment for PE was administered No Yes death Factor indicating patient mortality No Yes Source Simulated data not from real patients plot HydeNetwork 25 plot HydeNetwork Plotting Utilities Probabilistic Graphical Network Description Plotting Utilities Probabilistic Graphical Network Usage S3 method for class HydeNetwork plot x customNodes NULL customEdges NULL useHydeDefaults TRUE mergeCustomNodes node_df customNodes mapEdges n p mergeCustomEdges edge_df customEdges customNode node_id HydePlotOptions variable NULL determ NULL decision NULL utility NULL restorePackageDefaults FALSE Arguments ya an object of class HydeNetwork customNodes a data frame giving additional specifications for nodes The customizations pro vided here will override the default settings customEdges a data frame giving custom settings for edges arrows between nodes for the plot method additional arguments to be passed to DiagrammeR render_graph For customNode named node attributes to assign to a node s plotting character istics useHydeDefaults A logical value indicating if the default plot parameters in options Hyde plotOptions should be applied to the plot node_df A data frame of node attributes n node names from a network object p the list of parents from a network object edge_df The default edge attribute data frame node_id The name of a node in
13. two cards only one of the dealer s cards is shown and this is called the upcard Usage BJDealer Format A data frame with 70 rows and 3 variables dealerUpcard dealer upcard dealerOutcome outcome of dealer s hand under the rule that cards are drawn until the dealer s hand total is at least 17 probability conditional probability of dealerOutcome given dealerUpcard BlackJack Source https www blackjackinfo com dealer outcome probabilities BlackJack Black Jack Hybrid Decision Network Description An object of class HydeNetwork establishing a graphical model for a game of Black Jack Usage BlackJack Format A HydeNetwork object constructed using the code shown in the example The network has seven random nodes three ten deterministic nodes three decision nodes and one utility node This is almost the same network used in vignette DecisionNetworks package HydeNet Examples Not run BlackJack lt HydeNetwork initialAces card1 card2 initialPoints card1 card2 highUpcard dealerUpcard hit1 initialPoints highUpcard acesAfterCard3 initialAces card3 pointsAfterCard3 card1 card2 card3 acesAfterCard3 hit2 pointsAfterCard3xhighUpcard acesAfterCard4 acesAfterCard3xcard4 pointsAfterCard4 cardixcard2xcard3xcard4dxacesAfterCard4 hit3 pointsAfterCard4 highUpcard acesAfterCard5 acesAfterCard4xcard5 pointsAfterCard5 card1 card2 card3 card4 card5xacesAf
14. A HydeNet object with decision nodes defined policyMatrix A data frame of policies to apply to decision nodes for comparing networks under different conditions See policyMatrix Additional arguments to pass to jags model excepting the data argument The data argument is created by compileDecisionModel and cannot be passed manually data An optional list of data values to be observed in the nodes It is passed to the data argument of rjags jags Any values given in data will override values provided in policyMatrix with a warning Details compileDecisionModel only accepts nodes of type dbern Bernoulli random variable taking either O or 1 or dcat categorical variables as decision nodes When the node is type dcat the decision options are extracted from the JAGS statement returned by writeJagsModel The options for each decision nodes if there are multiple nodes are combined via expand grid to make a table of all possible decisions Each row of this table is passed as a list to the data argument of jags model via compileJagsModel and a list of JAGS model objects is returned coda samples may be run on each of these models Value Returns a list of compiledHydeNetwork objects Author s Jarrod Dalton and Benjamin Nutter 10 compileJagsModel See Also policyMatrix compileJagsModel Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe
15. HydeUtilities 19 TranslateFormula 36 update HydeNetwork 37 validateParameters HydeUtilities 19 vectorProbs 38 writeJagsFormula 38 40 41 writeJagsModel 39 40 41 writeNetworkModel 39 41
16. Package HydeNet October 12 2015 Type Package Title Hybrid Bayesian Networks Using R and JAGS Version 0 10 0 Date 2015 10 11 Author Jarrod E Dalton lt daltonj ccf org gt and Benjamin Nutter lt benjamin nutter gmail com gt Maintainer Benjamin Nutter lt benjamin nutter gmail com gt Description Facilities for easy implementation of hybrid Bayesian networks using R Bayesian networks are directed acyclic graphs representing joint probability distributions where each node represents a random variable and each edge represents conditionality The full joint distribution is therefore factorized as a product of conditional densities where each node is assumed to be independent of its non descendents given information on its parent nodes Since exact closed form algorithms are computationally burdensome for inference within hybrid networks that contain a combination of continuous and discrete nodes particle based approximation techniques like Markov Chain Monte Carlo are popular We provide a user friendly interface to constructing these networks and running inference using the rjags package Econometric analyses maximum expected utility under competing policies value of information involving decision and utility nodes are also supported License MIT file LICENSE Depends R gt 3 0 0 nnet rjags Imports ArgumentCheck broom gt 0 3 7 DiagrammeR gt 0 8 plyr dplyr graph gRbase magrittr stats stringr utils
17. The order of factors follows the order provided by the user This argument is only used when the node type is either dcat or dbern the node Fitter is not cpt nodeData is NULL and no variable for the node exists in the network s data element If any of those conditions is not met factorLevels is ignored This proves particularly important when data are specified in order to prevent a user specification from conflicting with expected factors across nodes 34 setNode validate Logical Toggles validation of parameters given in When passing raw JAGS code ie character strings this will be ignored with a message as the validation is applicable to numerical formula values fitModel Logical Toggles if the model is fit within the function call This may be set globally using options Hyde_fitModel See Details for more about when to use this option Details The functions fromFormula and fromData help to control how Hyde determines the values Of parameters passed to JAGS If the parameters passed in params argument are to be calculated from the data or inferred from the formula these functions may be used as placeholders instead of writing JAGS code in the params argument By default options Hyde_fitModel FALSE This prevents setNode from fitting any models Instead the fitting is delayed until the user calls writeJagsModel and all of the models are fit at the same time When using large data sets that may require time to run
18. a HydeNetwork object May be quoted or unquoted variable determ decision utility Named lists of attributes to use as defaults node attribute settings for each vari able type restorePackageDefaults A logical value When TRUE the original package defaults are restored 26 plot HydeNetwork Details Generate and customize plots of a HydeNetwork class network HydeNet provides some initial defaults for standard variable nodes deterministic nodes decision nodes and utility nodes Since these nodes are assumed to be of inherent difference and interest the options are defined in a way to make these easier to identify in a plot The default options may be altered by the user to their liking by invoking HydePlotOptions Node attributes are more fully explained in the documentation for the DiagrammeR package Individual nodes may be define with customNode Author s Jarrod Dalton and Benjamin Nutter Source http rich iannone github io DiagrammeR graphviz html See especially the section on Attributes http graphviz org http graphviz org content attrs Examples Not run x Plots may open in a browser data BlackJack package HydeNet plot BlackJack HydePlotOptions variable list shape rect fillcolor A6DBAQ determ list shape rect fillcolor E7D4E8 fontcolor 1B7837 linecolor 1B7837 decision list shape triangle fillcolor 1B7837 linecolor white u
19. amed list with the formulae specifying the relationships between nodes e nodeFitter a named list giving the fitting function for each node HydeNetwork 17 e nodeFitterArgs A named list with additional arguments to be passed to fitter functions e nodeParams A named list Each element is a vector of parameters that will be expected by JAGS e fromData A named list with the logical value of wheather parameters should be estimated from the data e nodeData A named list with the data for each node If a node s entry in fromData is TRUE and nodeData is NULL it will look to the data attribute instead e factorLevels If the vector associated with the node is a factor or character the levels of the factor are stored here Although it may seem redundant it allows factor levels to be specified in cases where the node is not define with data If data are provided to the node this element is determined from the data and cannot be manually overwritten e nodeModel A list of model objects This is a storing place for models that have already been fit so that they don t have to be refit again e nodeDecision A named list of logical flags for whether the node is a decision node or not e nodeUtility A named list of logical flags for whether the node is a utility node or not e dag The dag object returned by gRbase Most of the plotting utilities will be based on this element e data A common data frame for nodes that do not have their own
20. ariables and compute the probability of no as their respective complements See details Details If a formula object is entered for the vars parameter the formula must have the following structure response varl var2 etc The other option is to pass a named list containing two elements y and x Element y is a character string containing the name of the factor variable in data to be used as the dependent variable and element x is a character vector containing the name s of the factor variable s to be used as independent or conditioning variables In inputCPT when the parameter reduce is set to FALSE any non negative number e g cell counts is accepted as input Conditional probabilities are then calculated via a normalization pro cedure However when reduce is set to TRUE a only probabilities in 0 1 are accepted and b all inputted probabilities for each specific combination of independent variable values must not sum to a value greater than or the calculated probability for the first level of the dependent variable would be negative The cpt function with a weight vector passed to parameter wt works analogously to inputCPT reduce FALSE 1 e it accepts any non negative vector and computes the conditional probability array by normal izing sums of weights Author s Jarrod Dalton and Benjamin Nutter Examples a very imbalanced dice example n lt 50000 data lt data frame dil as factor
21. aset and function to apply to it Index Topic datasets BJDealer 4 BlackJack 5 BlackJackTrain 8 jagsDists 21 jagsFunctions 22 PE 24 gt 42 bindPosterior 3 BJDealer 4 BlackJack 5 BlackJackTrain 8 compileDecisionModel 9 compileJagsModel 70 10 cpt 12 customNode plot HydeNetwork 25 dataframeFactors HydeUtilities 19 decisionOptions HydeUtilities 19 defaultPolicyMatrix policyMatrix 27 expectedParameters expectedVariables 14 expectedVariables 14 factorRegex 15 fromData setNode 32 fromFormula setNode 32 Hyde Hyde package 3 Hyde package 3 HydeNetwork 16 HydePlotOptions plot HydeNetwork 25 HydePosterior 18 HydeUtilities 19 inputCPT cpt 12 jagsDists 21 43 jagsFunctions 22 makeFactorRef HydeUtilities 19 make JagsReady HydeUtilities 19 mapEdges plot HydeNetwork 25 matchLevelNumber HydeUtilities 19 matchVars HydeUtilities 19 mergeCustomEdges plot HydeNetwork 25 mergeCustomNodes plot HydeNetwork 25 mergeDefaultPlotOpts 23 modelToNode 23 nodeFromFunction HydeUtilities 19 PE 24 plot HydeNetwork 25 plotHydeNetwork plot HydeNetwork 25 policyMatrix 9 10 27 polyToPow HydeUtilities 19 print cpt 28 print HydeNetwork 29 print HydePosterior 30 rewriteHydeFormula 31 rToJags TranslateFormula 36 setDecisionNodes 32 setNode 32 setNodeModels 35 setUtilityNodes setDecisionNodes 32 termName
22. ata PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat setNodeModels 35 data PE print Net d dimer x Manually change the precision Net lt setNode Net d dimer nodeType dnorm mu fromFormula tau 1 2 65 nodeFormula d dimer pregnant pe nodeFitter 1m print Net d dimer setNodeModels Set Node Properties Using Model Objects Description Set node properties using pre defined model objects Model objects may be imported from other programs but need to be valid model objects with the additional restriction that the responses and independent variables must be named nodes in the network This will NOT create a network from a list of models For that see HydeNetwork Usage setNodeModels network Arguments network A HydeNetwork object Model objects to be incorporated into network Author s Jarrod Dalton and Benjamin Nutter Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat print Net gl lt lm wells 1 data PE g2 lt glm pe wells data PE family binomial g3 lt lm d dimer pe pregnant data PE g4 lt xtabs pregnant data PE g5 lt glm angio pe data PE family binomial g6 lt glm treat d dimer angio data PE family binomial
23. cal indicating if the weights in p should be normalized each value is taken as a proportion of the sum Author s Jarrod Dalton and Benjamin Nutter Examples vectorProbs c 1 2 3 wells writeJagsFormula Write the JAGS Formula for a Hyde Node Description Based on the information provided about the node an appropriate JAGS model is written in text This is combined with the other node models to generate the complete network writeJagsFormula 39 Usage writeJagsFormula fit nodes S3 method for class cpt writeJagsFormula fit nodes S3 method for class glm writeJagsFormula fit nodes S3 method for class 1m writeJagsFormula fit nodes S3 method for class multinom writeJagsFormula fit nodes S3 method for class xtabs writeJagsFormula fit Arguments fit a model object nodes a vector of node names usually passed from network nodes Additional arguments to be passed to other methods Details Methods for different model objects can be written so that this function can be extended as desired The resulting formulas are based on the coefficient matrix of the fitted model and the returned result is the JAGS code representing the regression equation of the model In the writeJagsFormula gl1m method appropriate transformations exist for the following combi nations 1 family binomial link logit 2 family poisson link log 3 famil
24. card3 card4 4 BlackJack lt setNode BlackJack pointsAfterCard5 determ define fromFormula nodeFormula pointsAfterCard5 ifelse acesAfterCard5 5 15 ifelse acesAfterCard5 4 ifelse card1 card2 card3 card4 card5 5 gt 51 cardi card2 card3 card4 card5 5 40 card card2 card3 card4 card5 5 30 ifelse acesAfterCard5 3 ifelse card1 card2 card3 card4 card5 5 gt 51 card card2 card3 card4 card5 5 30 card1 card2 card3 card4 card5 5 20 ifelse acesAfterCard5 2 ifelse card1 card2 card3 card4 card5 5 gt 31 card1 card2 card3 card4 card5 5 20 card1 card2 card3 card4 card5 5 10 ifelse acesAfterCard5 gt 0 ifelse card1 card2 card3 card4 card5 5 gt 22 card1 card2 card3 card4 card5 5 10 card card2 card3 card4 card5 5 cardi card2 card3 card4 card5 5 8 BlackJack Train BlackJack lt setNode BlackJack playerFinalPoints determ define fromFormula nodeFormula playerFinalPoints ifelse hit1 0 initialPoints ifelse hit2 0 pointsAfterCard3 ifelse hit3 pointsAfterCard4 pointsAfterCard5 BlackJack lt setDecisionNodes BlackJack hit1 hit2 hit3 BlackJack lt setUtilityNodes BlackJack payoff End Not run BlackJackTrain Black Jack Network Training Dataset Description These are simulated data
25. d A distinct print method has been written for this object Author s Jarrod Dalton and Benjamin Nutter Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat data PE compiledNet lt compileJagsModel Net n chains 5 x Generate the posterior distribution Posterior lt HydePosterior compiledNet variable names c d dimer death n iter 1000 tx Posterior Distributions for a Decision Model Net lt setDecisionNodes Net angio treat decisionNet lt compileDecisionModel Net n chains 5 decisionsPost lt HydePosterior decisionNet variable names c d dimer death n iter 1000 HydeUtilities Hyde Network Utility Functions Description The functions described below are unexported functions that are used internally by HydeNet to prepare modify network objects and prepare JAGS code 20 HydeUtilities Usage termName term reg decisionOptions node network makeJagsReady mdl regex nodes matchLevelNumber t lev matchVars terms vnames nodeFromFunction node_fn polyToPow poly validateParameters params dist makeFactorRef network dataframeFactors dataframe Arguments term Usually the term column from the output of broom tidy reg A regular expression usually provided by factorRegex node Character string indicating a node in a network network A Hyde Netw
26. ect of class HydePosterior relabel_factor Logical If TRUE factors that had been converted to integers for the JAGS code can be relabelled as factors for additional analysis in R Details For the purposes of this function it is assumed that if the posterior distributions are satisfactory the multiple chains in a run can be bound together Subsequently the multiple runs are bound together Lastly the factors are relabeled if requested Author s Jarrod Dalton and Benjamin Nutter 4 BJDealer Ezamples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat data PE compiledNet lt compileJagsModel Net n chains 5 x Generate the posterior distribution Posterior lt HydePosterior compiledNet variable names c d dimer death n iter 1000 Bound lt bindPosterior Posterior x Bind a Decision Network x Note angio shouldn t really be a decision node x We use it here for illustration Net lt setDecisionNodes Net angio treat compiledDecision lt compileDecisionModel Net n chains 5 PosteriorDecision lt HydePosterior compiledDecision variable names c d dimer death n iter 1000 BJDealer Blackjack Dealer Outcome Probabilities Description A dataset containing the conditional probability of various dealer outcomes given the upcard The dealer and player each get
27. ells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat data PE HydeNet writeJagsModel Net pe HydeNet writeJagsModel Net treat writeNetworkModel Generate JAGS Code for a Network s Model Description Based on the parameters given to a network the code for each node is generated and all of the node models are pasted into a single JAGS model script Usage writeNetworkModel network pretty FALSE Arguments network an object of class HydeNetwork pretty Logical When TRUE the model is printed to the console using the cat function useful if you wish to copy and paste the code for manual editing Otherwise it is returned as a character string Author s Jarrod Dalton and Benjamin Nutter See Also writeJagsModel writeJagsFormula Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio 42 gt death pextreat data PE x Default printing writeNetworkModel Net x Something a little easier on the eyes writeNetworkModel Net pretty TRUE gt Chain together multiple operations Description This is a copy of the documentation for gt in dplyr The copy here is made to conform to CRAN requirements regarding documentation Please see the dplyr documenation for the complete and current documentation Usage lhs gt rhs Arguments lhs rhs A dat
28. etNode BlackJack acesAfterCard3 determ define fromFormula nodeFormula acesAfterCard3 initialAces ifelse card3 10 1 0 BlackJack A setNode BlackJack acesAfterCard4 determ define fromFormula nodeFormula acesAfterCard4 acesAfterCard3 ifelse card4 10 1 0 BlackJack A setNode BlackJack acesAfterCard5 determ define fromFormula nodeFormula acesAfterCard5 acesAfterCard4 ifelse card5 10 1 0 BlackJack lt setNode BlackJack initialPoints determ define fromFormula nodeFormula initialPoints card1 card2 2 BlackJack lt setNode BlackJack pointsAfterCard3 determ define fromFormula nodeFormula pointsAfterCard3 ifelse acesAfterCard3 3 13 ifelse acesAfterCard3 2 cardi card2 card3 3 10 ifelse acesAfterCard3 1 ifelse card1 card2 card3 3 gt 22 card1 card2 card3 3 10 card1 card2 card3 3 card1 card2 card3 3 BlackJack BlackJack lt setNode BlackJack pointsAfterCard4 determ define fromFormula nodeFormula pointsAfterCard4 ifelse acesAfterCard4 4 14 ifelse acesAfterCard4 3 ifelse card1 card2 card3 card4 4 gt 38 card1 card2 card3 card4 4 30 card1 card2 card3 card4 4 20 ifelse acesAfterCard4 gt 0 ifelse card1 card2 card3 card4 4 gt 22 cardi card2 card3 card4 4 10 card1 card2 card3 card4 4 card1 card2
29. factorRegex g6 16 HydeNetwork HydeNetwork Define a Probablistic Graphical Network Description Using either a directed acyclic graph DAG or a list of models define a probabilistic graphical network to serve as the basis of building a model Usage HydeNetwork nodes S3 method for class formula HydeNetwork nodes data NULL HH S3 method for class list HydeNetwork nodes Arguments nodes Either a formula that defines the network as passed to gRbase dag or a list of model objects additional arguments to gRbase dag data A data frame with the data for estimating node parameters Details The DAG becomes only one element of the object returned by HydeNetwork The dag object is used to extract the node names and a list of parents for each node These will be used to help quantify the relationships When given a formula the relationships are defined but are not quantified until wri teNetworkModel is called When a list of models is given rather than refitting models when writeNetworkModel is called the quantified relationships are placed into the object Value Returns an object of class HydeNetwork The object is really just a list with the following compo nents e nodes a vector of node names e parents a named list with each element being a vector of parents for the node named e nodeType a named list with each element specifying the JAGS distribution type e nodeFormula a n
30. for CPT objects Description Just a wrapper to strip the attributes off change the class and print the array Usage S3 method for class cpt print x Arguments x Object of class cpt Additional arguments to be passed to other methods Author s Jarrod Dalton and Benjamin Nutter print HydeNetwork 29 print HydeNetwork Print a HydeNetwork Description Print a HydeNetwork Usage S3 method for class HydeNetwork print x Arguments x a HydeNetwork object additional arguments to be passed to print methods Currently none in use Details Prints a HydeNetwork object with a brief summary of each node Author s Jarrod Dalton and Benjamin Nutter Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat print Net print Net d dimer Net lt setNode Net d dimer nodeType dnorm mu fromData tau fromData nodeFormula d dimer pregnant pe nodeFitter 1m print Net d dimer 30 print HydePosterior print HydePosterior Print a Hyde Posterior Distribution Object Description Print a Hyde Posterior Distribution Object Usage S3 method for class HydePosterior print x Arguments x a HydePosterior object additional arguments to be passed to print methods Currently none in use Details Prints a brief description of a HydePosterior object
31. given setNode will assume you intended current utility A value of either current or a logical value If current the current value of the setting is retained This allows utility nodes set by setUtilityNode to re tain the classification as a utility node if setNode is run after setUtilityNode If TRUE the node will be considered a utility node This is only a valid option when the node is of type determ and it has no children Note if any char acter value other than current is given setNode will assume you intended current fromData Logical Determines if a node s relationship is calculated from the data object in network Defaults to TRUE whenever network has a data object parameters to be passed to the JAGS distribution function Each parameter in the distribution function must be named For example the parameters to pass to dnorm would be mu tau The required parameters can be looked up using the expectedParameters function If parameters are to be estimated from the data the functions fromData and fromFormula may be used as placeholders nodeData A data frame with the appropriate data to fit the model for the node Data passed in this argument are applied only to this specific node No checks are performed to ensure that all of the appropriate variables the node and its parents are in cluded factorLevels A character vector used to specify the levels of factors when data are not pro vided for a node
32. many levels Usage cpt x data wt S3 method for class formula cpt formula data wt S3 method for class list cpt x data wt inputCPT x factorLevels reduce TRUE S3 method for class formula inputCPT formula factorLevels reduce TRUE S3 method for class list inputCPT x factorLevels reduce TRUE Arguments x a list containing the names of the variables used to compute the conditional data wt formula factorLevels probability table See details a data frame containing all the factors represented by the formula parameter optional a numeric vector of observation weights Additional arguments to be passed to other methods a formula specifying the relationship between the dependent and independent variables optional a named list with the following structure Variable names for the factors specified in vars comprise the names of the list elements and each list element is a character vector containing the levels of the respective factor See examples cpt 13 reduce set to TRUE if inputCPT is to compute probabilities for the first level of the dependent variable as the complement of the inputted probabilities correspond ing to the other levels of the dependent variable For example reduce TRUE with a binary dependent variable y say with levels no and yes will ask for the probabilities of yes at each combination of the independent v
33. node attributes modelToNode Convert a Model Object to a Network Node Description In cases where model objects may already be fit and established they can be used to generate a network without having to refit the models or specify the distributions in setNode Usage modelToNode model nodes Default S3 method modelToNode model nodes S3 method for class cpt modelToNode model nodes S3 method for class glm modelToNode model nodes S3 method for class 1m modelToNode model nodes S3 method for class multinom modelToNode model nodes HH S3 method for class xtabs modelToNode model nodes 24 PE Arguments model A model object nodes A vector of node names usually as network nodes Additional arguments to be passed to other functions Currently ignored PE Pulmonary Embolism Dataset Description These are simulated data on 10 000 cases with suspected pulmonary embolism at a hospital Usage PE Format A data frame with 10000 rows and 7 variables wells Wells score integer ranging from 1 to 10 indicating the degree to which PE is suspected based on clinical review of symptoms pregnant Factor indicating pregnancy No Yes pe Factor indicating pulmonary embolism has occurred No Yes angio Result of pulmonary angiography test Negative Positive d dimer Numeric result of diagnostic blood test called D Dimer treat Factor indicating whether
34. ork Object mdl Output from broom tidy regex A regular expression usually returned by factorRegex nodes A vector of node names usually passed from network nodes t Usually the term_name column generated within makeJagsReady lev usually the level_value column generated within makeJagsReady terms A vector of term names usually from a broom tidy object vnames A vector of term names usually from network nodes node_fn A character string representing a function passed in a model formula poly A single term for which the polynomial components should be converted to the JAGS pow function params The list of parameters given in the argument of setNode dist The JAGS distribution function name Appropriate names are in the FnName column of the jagsDists data object dataframe A data frame The data frame will be searched for factors and a reference table another data frame is returned jagsDists 21 Details termName In most model objects factors in the model are represented as variable level This util ity function pulls out the variable component This is typically called from within makeJagsReady decisionOptions When compiling multiple JAGS models to evaluate the effect of decision nodes the options for each decision node are extracted by this utility makeJagsReady Manages the presence of factors in interactions and makes sure the proper numeric factor value is given to the JAGS code This is called from wi
35. ormula statement indicating the changes to the network Additional arguments to be passed to other methods Current none are used Details Adding or removing nodes is fairly straightforward if you are removing a complete node along with its parents If you just wish to remove a parent this doesn t work well yet I will have to work out a solution to remove parent relationships individually I had hoped there would be an update dag method but no luck This will continue to be developed in the future but the arguments will remain the same Author s Jarrod Dalton and Benjamin Nutter Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat plot Net Net lt update Net pregnant plot Net 38 writeJagsFormula vectorProbs Convert a vector to JAGS Probabilities Description Probability vectors can be passed manually to the model but they must be formatted in code appro priate to JAGS vectorProbs will convert a vector of counts or weights to probabilities and format it into JAGS code Usage vectorProbs p node normalize TRUE Arguments p a vector of counts weights or probabilities node the node for the parameters this is converted to a character string It is impor tant that this be given accurately or it will not match with the code written by writeNetworkModel normalize A logi
36. sterior cHN variable names n iter thin 1 monitor_observed TRUE bind TRUE Arguments CHN A compiledHydeNetwork object as returned by compileJagsNetwork variable names a character vector giving the names of variables to be monitored n iter number of iterations to monitor thin thinning interval for monitors options arguments that are passed to the update method for jags model objects monitor_observed If TRUE the observed or fixed variables those passed to the data argument in compileJagsNetwork are forced into variable names if not already pro vided This is recommended especially 1f you will be binding multiple JAGS runs together bind Logical If TRUE posterior distributions will be bound into a single data frame If FALSE the standard output from rjags is returned Details This is essentially a wrapper around coda samples that returns in a list the output for each run of coda samples over the rows of the policy decision matrix given in the data argument of compileJagsNetwork HydeUtilities 19 Value A list of class HydePosterior with elements codas the MCMC matrices from coda samples observed the values of the variables that were observed dag the dag object for convenience in displaying the network and factorRef giving the mappings of factor levels to factor variables The only rationale for giving this object its own class was because it produces an enormous amount of material to be printe
37. terCard5 playerFinalPoints initialPoints hit1 pointsAfterCard3 xhit2xpointsAfterCard4x xhit3xpointsAfterCard5 dealerFinalPoints dealerUpcard payoff playerFinalPoints dealerFinalPoints t eet ete ttt cardProbs lt c rep 1 13 8 4 13 1 13 probs for 2 3 9 10 K A BlackJack lt BlackJack lt BlackJack lt BlackJack lt setNode BlackJack card1 nodeType dcat pi vectorProbs p cardProbs card1 setNode BlackJack card2 nodeType dcat pi vectorProbs p cardProbs card2 setNode BlackJack card3 nodeType dcat pi vectorProbs p cardProbs card3 setNode BlackJack card4 nodeType dcat BlackJack pi vectorProbs p cardProbs card4 BlackJack lt setNode BlackJack card5 nodeType dcat pi vectorProbs p cardProbs card5 BlackJack lt setNode BlackJack dealerUpcard nodeType dcat pi vectorProbs p cardProbs dealerUpcard Note node dealerFinalPoints will be defined below following some discussion about its conditional probability distribution BIERE RR AEH HEH AEE TEEPE AE HEE a Deterministic Nodes RR HEHEHE AEE EE HEE Ea BlackJack lt setNode BlackJack highUpcard determ define fromFormula nodeFormula highUpcard ifelse dealerUpcard gt 8 1 BlackJack A setNode BlackJack initialAces determ define fromFormula nodeFormula initialAces ifelse card1 10 1 0 ifelse card2 10 1 0 BlackJack A s
38. thin a writeJagsFormula call matchLevelNumber Assigns the correct numeric value of a level to a factor variable in a model This is called from within makeJagsRead matchVars Given a list of existing node names the terms of a formula are matched to the node names This allows functions to be used in formula defintions Most commonly factor var would get reduced to var which is a node name that JAGS will understand There is still limited ability for translation here and matchVars assumes that the longest match is the desired match If you pass a function with two node names the longer of the two will be taken and JAGS will likely fail nodeFromFunction This is a utility function necessary to make modelToNode work properly A node vector was needed to pass to matchVars and this is the mechanism to generate that vector polyToPow converts polynomials generated by the poly function to use the pow function in JAGS validateParameters Users may pass parameters to the JAGS code using the setNode function If a faulty parameter is given such as lambda 10 for a poisson distribution lambda must be positive in a Poisson distribution the error returned by JAGS may not clear enough to diagnose a problem that presented several steps earlier in the code validateParamters allows the user to receive instant feedback on the appropriateness of the code Logical expressions for comparisons are stored in the jagsDists data object data jagsDists
39. tility list shape circle fillcolor 762A83 fontcolor white plot BlackJack HydePlotOptions restorePackageDefaults TRUE plot BlackJack customNodes customNode payoff fillcolor purple shape circle fontcolor white height 2 style filled plot BlackJack customNodes dplyr bind_rows customNode pointsAfterCard3 shape circle style radial fillcolor 1B7837 762A83 fontcolor black height 2 policy Matrix 27 customNode playerFinalPoints shape circle style wedged height 3 fillcolor c red orange yellow green blue purple End Not run policyMatrix Construct Policy and Decision Matrices Description It may be of interest to compare posterior distributions of variables dependent on differing levels of the decision nodes For example how might choosing a different engine in a car affect the fuel consumption policyMatrix provides a quick utility to begin defining the policy matrix on which decisions can be made Usage policyMatrix network defaultPolicyMatrix network Arguments network A HydeNetwork object Named arguments with vectors of the policy values Details When is not used the default policy matrix is defined as all possible combinations of the levels in the network s decision nodes If no decision nodes are defined an error is returned Note that the default policy matrix ret
40. tionship to its parents usually through a model of some sort Usage setNode network node nodeType nodeFitter nodeFormula fitterArgs list decision current utility current fromData is null network data nodeData NULL factorLevels NULL validate TRUE fitModel getOption Hyde fitModel fromData fromFormula setNode 33 Arguments network A HydeNetwork node A node within network This does not have to be quoted nodeType a valid distribution function from JAGS See the data set in data jagsDists for a complete list nodeFitter the fitting function such as 1m or glm This will probably only be needed when fromData TRUE nodeFormula A formula object specifying the relationship between a node and its parents It must use as a term every parent of node fitterArgs Additional arguments to be passed to fitter This does not yet have any effect as I haven t yet decided out where to store this and how to implement the fitting decision A value of either current or a logical value If current the current value of the setting is retained This allows decision nodes set by setDecisionNode to retain the classification as a decision node if setNode is run after setDecisionNode If TRUE the node will be considered a decision node in compileDecisionNetwork This is only a valid option when the node is of type dbern or dcat Note if any character value other than current is
41. unique data source e network formula The original formula passed to gRbase dag to construct the model Note These objects can get pretty large In versions of R earlier than 3 2 it can take a while to print the large network objects if you simply type the object name into the console It is recommended that you always explicitly invoke the print function ie print Net instead of just Net to save yourself some valuable time Author s Jarrod Dalton and Benjamin Nutter Examples tx Formula Input Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat data PE print Net tx Model Input gl lt lm wells 1 data PE g2 lt glm pe wells data PE family binomial g3 lt lm d dimer pe pregnant data PE 18 HydePosterior g4 lt xtabs pregnant data PE g5 lt glm angio pe data PE family binomial g6 lt glm treat d dimer angio data PE family binomial g7 lt glm death pe treat data PE family binomial bagOfModels lt list g1 g2 g3 4 5 26 g7 bagNet lt HydeNetwork bagOfModels print bagNet HydePosterior Posterior Distributions of a Decision Network Description The posterior distributions of the decision network can be evaluated to determine the probabilistic outcomes based on the decision inputs in the model as well as subject specific factors Usage HydePo
42. urns JAGS ready values which are numeric according to the level number of a factor In user defined matrices character values are supported and will be converted to numerics when the JAGS model is compiled Semi custom policy matrices can be defined by providing the values of each node to be considered When manually supplying values the nodes must exist in network but the requirement that they be decision nodes is not enforced Thus it is possible to include numeric values in a decision matrix though it is strongly discouraged Policy matrices can be passed to HydePosterior to run posterior distributions on each row of the policy matrix There is nothing particularly special about the policy matrices returned by policyMatrix they are simply data frame that require names drawn from the nodes in the net work Any data frame can be passed to HydePosterior and a check is done there to confirm all of the column names match a node in the network 28 print cpt Value Returns a data frame built by expand grid and intended to be used with HydePosterior Author s Jarrod Dalton and Benjamin Nutter Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat data PE Net lt setDecisionNodes Net angio treat plot Net policyMatrix Net policyMatrix Net treat No angio c No Yes print cpt Print Method
43. vided to the network the user is expected to provide appropriate estimates of the regression coefficients for the model returnVector will generally be set to FALSE for most uses but can be set to TRUE for use in error checking For example in setNode if not all of the parents have been given a coefficient or if too few coefficients have been given the vector of names is usually more useful for giving informative error messages Author s Jarrod Dalton and Benjamin Nutter factorRegex 15 Examples data PE package HydeNet Net lt HydeNetwork wells pe wells d dimer pregnantxpe angio pe treat d dimerxangio death pextreat expectedVariables Net wells expectedVariables Net treat expectedVariables Net treat returnVector TRUE expectedParameters Net wells expectedParameters Net wells returnVector TRUE factorRegex Produce Regular Expressions for Extracting Factor Names and Levels Description A utility function to produce a regular expression that can separate factor names and factor levels in the broom tidy term output At some point this may have to become a method to accomodate different model types but I haven t run into that problem yet Usage factorRegex fit Arguments fit a model object Author s Jarrod Dalton and Benjamin Nutter Examples data PE package HydeNet g6 lt glm treat d dimer angio data PE family binomial HydeNet
44. y gaussian link identity calls writeJagsFormula im Author s Jarrod Dalton and Benjamin Nutter See Also writeJagsModel writeNetworkModel 40 writeJagsModel Ezamples data PE package HydeNet fit lt lm d dimer pregnant pe data PE writeJagsFormula fit nodes c d dimer pregnant pe fit glm lt glm death pe treat data PE family binomial writeJagsFormula fit glm nodes c death pe treat writeJagsModel Write a Node s JAGS Model Description Constructs the JAGS code that designates the model for the node conditioned on its parents The parameters for the model may be user supplied or estimated from a given data set Usage writeJagsModel network node Arguments network A network of class HydeNetwork node A node within network Details The manipulations are performed on the nodeParams element of the Hyde network A string of JAGS code is returned suitable for inclusion in the Bayesian analysis The function will eventually travel through a serious of if statements until it finds the right node type It will then match the appropriate arguments to the inputs based on user supplied values or estimating them from the data Author s Jarrod Dalton and Benjamin Nutter See Also writeJagsFormula writeNetworkModel 41 Ezamples tx NOTE writeJagsModel isn t an exported function data PE package HydeNet Net lt HydeNetwork wells pe w

Download Pdf Manuals

image

Related Search

Related Contents

株 主 各 位 - 三井住友建設  Safety-PLC Operating instructions Hardware  hf ibramed  Operating Manual - Dental Concepts  製品安全データシート  Fujitsu P Line P24W-6  

Copyright © All rights reserved.
Failed to retrieve file