### Estimate Bootstrap Arc Strength and Average Networks Source: https://context7.com/cran/bnlearn/llms.txt Demonstrates using `boot.strength()` for bootstrap estimation of arc strength in Bayesian networks and `arc.strength()` for computing strength in a single network. Also shows how to create a consensus network using `averaged.network()`. ```r data(learning.test) # Bootstrap arc strength estimation # Example using hc algorithm with 200 bootstrap samples arcs <- boot.strength(learning.test, algorithm = "hc", R = 200) # 200 bootstrap samples # View strong arcs based on strength and direction strong_arcs <- arcs[(arcs$strength > 0.85) & (arcs$direction >= 0.5), ] print(strong_arcs) # Create averaged network from bootstrap results avg_net <- averaged.network(arcs) print(avg_net) modelstring(avg_net) # Custom threshold for arc inclusion threshold <- inclusion.threshold(arcs) avg_custom <- averaged.network(arcs, threshold = 0.90) # Arc strength for existing network using scores (e.g., BDe score) dag <- hc(learning.test) strength_bde <- arc.strength(dag, learning.test, criterion = "bde") print(strength_bde) # Arc strength using conditional independence tests (e.g., mutual information) strength_mi <- arc.strength(dag, learning.test, criterion = "mi") # Custom strength from list of networks start_nets <- random.graph(names(learning.test), num = 50) networks <- lapply(start_nets, function(net) { hc(learning.test, score = "bde", iss = 10, start = net) }) custom_arcs <- custom.strength(networks, nodes = names(learning.test), cpdag = FALSE) # Bayes factor strength calculation bf_arcs <- bf.strength(dag, learning.test, score = "bds", prior = "marginal") ``` -------------------------------- ### Create and Predict with Naive Bayes and TAN Classifiers Source: https://context7.com/cran/bnlearn/llms.txt Illustrates the creation of Naive Bayes (`naive.bayes()`) and Tree-Augmented Naive Bayes (`tree.bayes()`) classifiers for classification tasks. Includes in-sample and out-of-sample prediction, and obtaining posterior probabilities. ```r data(learning.test) # Create Naive Bayes classifier nb <- naive.bayes(learning.test, training = "A") print(nb) # In-sample prediction (parameters fitted implicitly) pred_nb <- predict(nb, learning.test) table(pred_nb, learning.test$A) accuracy_nb <- sum(pred_nb == learning.test$A) / nrow(learning.test) # Tree-Augmented Naive Bayes classifier tan <- tree.bayes(learning.test, training = "A") # Explicit parameter fitting for TAN fitted_tan <- bn.fit(tan, learning.test, method = "bayes") # Predict with fitted TAN pred_tan <- predict(fitted_tan, learning.test) table(pred_tan, learning.test$A) # Out-of-sample prediction train_set <- learning.test[1:4000, ] test_set <- learning.test[4001:5000, ] nb_train <- naive.bayes(train_set, training = "A") fitted_nb <- bn.fit(nb_train, train_set) pred_test <- predict(fitted_nb, test_set) # Get posterior probabilities pred_prob <- predict(fitted_nb, test_set, prob = TRUE) posterior <- attr(pred_prob, "prob") # Specify custom prior distribution prior <- c(0.3, 0.3, 0.4) # for levels a, b, c pred_prior <- predict(fitted_nb, test_set, prior = prior) ``` -------------------------------- ### Control Monte Carlo Samples for Precise Inference Source: https://context7.com/cran/bnlearn/llms.txt Demonstrates how to control the number of Monte Carlo samples used in `cpquery` for precise probabilistic inference in Bayesian networks. Increasing the sample size (`n`) improves accuracy. ```r prob_precise <- cpquery(fitted, event = (B == "b"), evidence = (A == "a"), n = 100000) # more samples for precision ``` -------------------------------- ### Structure Learning with Hybrid Algorithms Source: https://context7.com/cran/bnlearn/llms.txt Demonstrates the use of hybrid structure learning algorithms like RSMAX2 and H2PC, which combine constraint-based and score-based approaches to learn the DAG structure from data. ```R dag_rsmax2 <- rsmax2(learning.test, restrict = "mmpc", maximize = "hc", restrict.args = list(alpha = 0.05), maximize.args = list(score = "bde")) dag_h2pc <- h2pc(learning.test) ``` -------------------------------- ### Write Bayesian Network Structure to DOT Format (Graphviz) Source: https://context7.com/cran/bnlearn/llms.txt Exports the structure of a Bayesian network (DAG) to the DOT format, suitable for visualization with Graphviz or import into software like Gephi. The DOT format describes the graph's nodes and edges. ```r dag <- hc(learning.test) write.dot("network.dot", dag) ``` -------------------------------- ### Write Bayesian Network to NET Format (HUGIN) Source: https://context7.com/cran/bnlearn/llms.txt Saves a fitted Bayesian network object to a file in the NET format, which is compatible with HUGIN software. This function is useful for exporting learned networks for use in other Bayesian network tools. ```r write.net("network.net", fitted) ``` -------------------------------- ### Causal Inference and Interventions Source: https://context7.com/cran/bnlearn/llms.txt Implements causal reasoning tools including mutilated networks for do-calculus, counterfactual queries, and d-separation analysis. ```R dag <- model2network("[C][A|C][B|C][D|A:B]") mutilated_dag <- mutilated(dag, evidence = list(A = 0)) cf_dag <- counterfactual(dag, evidence = list(A = 0), merging = TRUE) dsep(dag, "A", "B", "C") ``` -------------------------------- ### Import and Export of Network Formats Source: https://context7.com/cran/bnlearn/llms.txt Functions for serializing and deserializing Bayesian networks to standard formats like BIF and DSC for cross-software compatibility. ```R data(learning.test) fitted <- bn.fit(hc(learning.test), learning.test) write.bif("network.bif", fitted) write.dsc("network.dsc", fitted) ``` -------------------------------- ### Recreate Bayesian Network from Model String Source: https://context7.com/cran/bnlearn/llms.txt Reconstructs a Bayesian network structure from its model string representation. This allows for easy loading and verification of previously saved network structures. ```r dag_recreated <- model2network(ms) all.equal(dag, dag_recreated) ``` -------------------------------- ### Perform Constraint-Based Structure Learning in R Source: https://context7.com/cran/bnlearn/llms.txt The pc.stable() function implements the PC-stable algorithm for learning the equivalence class of a DAG using conditional independence tests. It supports various tests for discrete and Gaussian data and allows for skeleton-only learning. ```r data(learning.test) # PC-stable algorithm with default settings cpdag <- pc.stable(learning.test) # PC-stable with custom significance level and test cpdag_strict <- pc.stable(learning.test, alpha = 0.01, test = "mi") # Gaussian data example data(gaussian.test) cpdag_gauss <- pc.stable(gaussian.test, test = "cor") ``` -------------------------------- ### Conditional Probability Queries and Sampling Source: https://context7.com/cran/bnlearn/llms.txt Performs probabilistic inference using cpquery for conditional probability estimation and cpdist for generating samples from conditional distributions, supporting both logic sampling and likelihood weighting. ```R prob <- cpquery(fitted, event = (B == "b"), evidence = (A == "a")) # Likelihood weighting prob_lw <- cpquery(fitted, event = (B == "b"), evidence = list(A = "a", C = "c"), method = "lw") # Generate samples samples <- cpdist(fitted, nodes = "A", evidence = (C == "c")) ``` -------------------------------- ### Creating Networks from Expert Knowledge Source: https://context7.com/cran/bnlearn/llms.txt Constructs Bayesian networks manually using model strings or by defining custom conditional probability tables and regression coefficients for Gaussian nodes. ```R dag <- model2network("[A][B][C|A:B]") # Custom CPTs cptA <- matrix(c(0.4, 0.6), ncol = 2, dimnames = list(NULL, c("LOW", "HIGH"))) expert_net <- custom.fit(dag, dist = list(A = cptA, B = cptB, C = cptC)) # Modify existing network fitted$B <- as.table(new_cpt) ``` -------------------------------- ### Predict and Impute Values with Bayesian Networks Source: https://context7.com/cran/bnlearn/llms.txt Shows how to use the `predict()` function for forecasting target variables and `impute()` for filling missing data in a dataset using a fitted Bayesian network. Supports various prediction methods like likelihood weighting and exact inference. ```r data(learning.test) data(gaussian.test) # Split data into training and test sets train <- learning.test[1:4000, ] test <- learning.test[4001:5000, ] # Learn and fit network on training data dag <- hc(train) fitted <- bn.fit(dag, train) # Predict using parents only (fast, local) predictions <- predict(fitted, node = "F", data = test) table(predictions, test$F) # confusion matrix # Predict using likelihood weighting (uses all evidence) predictions_lw <- predict(fitted, node = "F", data = test, method = "bayes-lw", n = 500) # Get prediction probabilities predictions_prob <- predict(fitted, node = "F", data = test, method = "bayes-lw", prob = TRUE) attr(predictions_prob, "prob") # posterior probabilities # Exact inference for prediction (discrete networks) predictions_exact <- predict(fitted, node = "F", data = test, method = "exact") # Impute missing values data_missing <- gaussian.test data_missing[sample(nrow(data_missing), 500), "F"] <- NA fitted_gauss <- bn.fit(model2network("[A][B][E][G][C|A:B][D|B][F|A:D:E:G]"), gaussian.test) imputed <- impute(fitted_gauss, data_missing) sum(is.na(imputed$F)) # should be 0 # Impute with likelihood weighting imputed_lw <- impute(fitted_gauss, data_missing, method = "bayes-lw") ``` -------------------------------- ### Perform Tabu Search Structure Learning in R Source: https://context7.com/cran/bnlearn/llms.txt The tabu() function implements Tabu search, which improves upon hill-climbing by maintaining a list of recently visited states to prevent cycling. This is useful for escaping local optima in complex search spaces. ```r data(learning.test) # Basic Tabu search dag <- tabu(learning.test) # Tabu search with custom parameters dag_custom <- tabu(learning.test, score = "bic", tabu = 50, max.tabu = 50, max.iter = 500) ``` -------------------------------- ### Convert Bayesian Network to Model String Source: https://context7.com/cran/bnlearn/llms.txt Generates a compact string representation of a Bayesian network's structure. This model string is useful for easy sharing, saving, or programmatic reconstruction of the network structure. ```r ms <- modelstring(dag) print(ms) ``` -------------------------------- ### Parameter Learning with bn.fit Source: https://context7.com/cran/bnlearn/llms.txt Estimates parameters for Bayesian networks using maximum likelihood, Bayesian estimation, or the EM algorithm for missing data. Supports both discrete and Gaussian network types. ```R data(learning.test) dag <- hc(learning.test) fitted <- bn.fit(dag, learning.test) # Bayesian estimation fitted_bayes <- bn.fit(dag, learning.test, method = "bayes", iss = 10) # EM for missing data data_missing <- learning.test data_missing[sample(nrow(data_missing), 500), "F"] <- NA fitted_em <- bn.fit(dag, data_missing, method = "hard-em", max.iter = 10) ``` -------------------------------- ### Standard Statistical Methods for Bayesian Networks Source: https://context7.com/cran/bnlearn/llms.txt Calculates standard information criteria and log-likelihood for a fitted Bayesian network object against a test dataset. ```R logLik(dag, learning.test) AIC(dag, learning.test) BIC(dag, learning.test) ``` -------------------------------- ### Graph Utilities and Structural Manipulation Source: https://context7.com/cran/bnlearn/llms.txt Provides functions for creating, modifying, and analyzing the structure of Bayesian networks, including node operations and structural comparison. ```R nodes <- LETTERS[1:5] empty <- empty.graph(nodes) random_dag <- random.graph(nodes) dag <- model2network("[A][B|A][C|A:B][D|C][E|B:D]") parents(dag, "C") shd(dag_learned, dag_true) ``` -------------------------------- ### Random Data Generation from Bayesian Networks Source: https://context7.com/cran/bnlearn/llms.txt Uses the rbn() function to perform forward sampling on a fitted Bayesian network. This is useful for simulation studies and verifying marginal distributions. ```R data(learning.test) dag <- hc(learning.test) fitted <- bn.fit(dag, learning.test) samples <- rbn(fitted, n = 1000) head(samples) ``` -------------------------------- ### Perform Hybrid Structure Learning (MMHC) in R Source: https://context7.com/cran/bnlearn/llms.txt The mmhc() function executes the Max-Min Hill-Climbing algorithm, which combines constraint-based search to restrict the space of possible arcs followed by score-based hill-climbing optimization. ```r data(learning.test) # Max-Min Hill-Climbing dag <- mmhc(learning.test) ``` -------------------------------- ### Perform Conditional Independence Tests Source: https://context7.com/cran/bnlearn/llms.txt The ci.test() function in bnlearn tests for independence and conditional independence between variables. It supports various statistical tests suitable for discrete and Gaussian data, including mutual information, chi-squared, correlation, and permutation-based tests. ```r data(learning.test) data(gaussian.test) # Independence test (no conditioning variables) test_result <- ci.test("A", "B", data = learning.test) print(test_result) # Returns: statistic, p-value, degrees of freedom # Conditional independence test ci_result <- ci.test("F", "B", c("C", "D"), data = learning.test) print(ci_result) # Specific tests for discrete data ci_mi <- ci.test("A", "B", "C", data = learning.test, test = "mi") # mutual information ci_x2 <- ci.test("A", "B", "C", data = learning.test, test = "x2") # chi-squared # Tests for Gaussian data ci_cor <- ci.test("F", "B", c("C", "D"), data = gaussian.test, test = "cor") # correlation ci_zf <- ci.test("F", "B", c("C", "D"), data = gaussian.test, test = "zf") # Fisher's Z # Permutation-based test ci_mc <- ci.test("A", "B", "C", data = learning.test, test = "mc-mi", # Monte Carlo mutual information B = 1000) # number of permutations # Test using vectors/factors directly attach(learning.test) ci.test(x = A, y = B, z = data.frame(C, D)) detach(learning.test) ``` -------------------------------- ### Perform Cross-Validation for Bayesian Networks Source: https://context7.com/cran/bnlearn/llms.txt The bn.cv() function in bnlearn performs k-fold or hold-out cross-validation to evaluate Bayesian networks. It supports various loss functions and methods like 'k-fold', 'hold-out', and 'custom-folds'. ```r data(learning.test) data(gaussian.test) # K-fold cross-validation with classification error cv_result <- bn.cv(learning.test, bn = "hc", loss = "pred", loss.args = list(target = "F"), k = 10) print(cv_result) loss(cv_result) # extract loss values # Cross-validation with log-likelihood loss cv_logl <- bn.cv(learning.test, bn = "hc", loss = "logl") # Hold-out cross-validation cv_holdout <- bn.cv(gaussian.test, bn = "mmhc", method = "hold-out", k = 5, # number of repetitions m = 50) # test set size # Multiple runs for statistical comparison cv_multi <- bn.cv(learning.test, bn = "hc", loss = "pred", loss.args = list(target = "F"), runs = 10) loss(cv_multi) # Cross-validation with fixed network structure dag <- model2network("[A][C][F][B|A][D|A:C][E|B:F]") cv_fixed <- bn.cv(learning.test, bn = dag, loss = "logl") # Custom folds # Compare algorithms using cross-validation cv_hc <- bn.cv(learning.test, "hc", runs = 5) cv_tabu <- bn.cv(learning.test, "tabu", runs = 5) cv_mmhc <- bn.cv(learning.test, "mmhc", runs = 5) ``` -------------------------------- ### Perform Hill-Climbing Structure Learning in R Source: https://context7.com/cran/bnlearn/llms.txt The hc() function performs score-based structure learning using greedy hill-climbing. It supports configuration of network scores, random restarts to avoid local optima, and the application of whitelists or blacklists to constrain the search space. ```r library(bnlearn) data(learning.test) # Basic hill-climbing structure learning dag <- hc(learning.test) # Hill-climbing with custom score and random restarts dag_bde <- hc(learning.test, score = "bde", iss = 10, restart = 5, perturb = 5) # Using whitelist and blacklist whitelist <- data.frame(from = c("A", "B"), to = c("B", "C")) dag_wl <- hc(learning.test, whitelist = whitelist) # Limit maximum number of parents dag_maxp <- hc(learning.test, maxp = 3) ``` -------------------------------- ### Score Bayesian Network Structures Source: https://context7.com/cran/bnlearn/llms.txt The score() function in bnlearn calculates goodness-of-fit scores for Bayesian networks, essential for score-based structure learning. It supports various scoring methods like BIC, BDe, K2, and log-likelihood for both discrete and Gaussian data. ```r data(learning.test) dag <- hc(learning.test) # BIC score (default) bic_score <- score(dag, learning.test, type = "bic") print(bic_score) # Bayesian Dirichlet equivalent score bde_score <- score(dag, learning.test, type = "bde", iss = 10) # K2 score k2_score <- score(dag, learning.test, type = "k2") # Log-likelihood ll_score <- score(dag, learning.test, type = "loglik") # Score equivalence demonstration dag2 <- set.arc(dag, "B", "A") # reverse an arc score(dag, learning.test, type = "bde") # equivalent scores score(dag2, learning.test, type = "bde") # same score score(dag, learning.test, type = "k2") # K2 is NOT score equivalent score(dag2, learning.test, type = "k2") # different score # Node-by-node decomposition node_scores <- score(dag, learning.test, type = "bic", by.node = TRUE) print(node_scores) # BDe with custom prior beta <- data.frame(from = c("A", "D"), to = c("B", "F"), prob = c(0.2, 0.5)) bde_prior <- score(dag, learning.test, type = "bde", prior = "cs", # Castelo & Siebes prior beta = beta) # Gaussian network scores data(gaussian.test) dag_gauss <- hc(gaussian.test) bge_score <- score(dag_gauss, gaussian.test, type = "bge") bic_gauss <- score(dag_gauss, gaussian.test, type = "bic-g") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.