xiaohongshu
xiaohongshu
bn-fit-modify
Guidance for Bayesian Network DAG structure recovery, parameter learning, and causal intervention tasks. This skill should be used when tasks involve recovering DAG structure from observational data, learning Bayesian Network parameters, performing causal interventions (do-calculus), or generatin...
Full skill instructions
This skill provides guidance for tasks involving Bayesian Network structure learning, parameter estimation, and causal interventions. These tasks typically require recovering a Directed Acyclic Graph (DAG) from observational data, fitting parameters to the recovered structure, and generating samples under interventions.
Correlation does not imply direct edges. Two variables may be highly correlated because:
Using correlation-based greedy approaches for DAG recovery is fundamentally flawed and will produce incorrect structures.
Many DAGs encode the same conditional independence relationships and cannot be distinguished from observational data alone. When edge directionality is ambiguous, apply any task-specified rules (e.g., alphabetical ordering) consistently.
An intervention (do-operator) differs from conditioning:
Interventions remove all incoming edges to the intervened variable.
Before structure learning, characterize the data:
import pandas as pd
import numpy as np
data = pd.read_csv('data.csv')
print(f"Shape: {data.shape}")
print(f"Types: {data.dtypes}")
print(f"Statistics:\n{data.describe()}")
Select an appropriate algorithm based on data characteristics:
For Continuous Data:
For Discrete Data:
For Mixed Data:
Structure learning algorithms can be memory-intensive. When encountering memory issues (exit code 137, OOM):
causal-learn or R's bnlearn# Subsample for structure learning
subsample = data.sample(n=min(2000, len(data)), random_state=42)
Never fall back to correlation-based approaches when proper methods fail. Instead, fix the computational issue.
Use established libraries with proper conditional independence testing:
# Option 1: pgmpy with constraint-based learning
from pgmpy.estimators import PC
from pgmpy.estimators import HillClimbSearch, BicScore
# For smaller datasets
pc = PC(data)
model = pc.estimate(variant='stable', max_cond_vars=4)
# Option 2: causal-learn library
from causallearn.search.ConstraintBased.PC import pc
from causallearn.utils.cit import fisherz
cg = pc(data.values, alpha=0.05, indep_test=fisherz)
When edge directionality is ambiguous (within the same Markov equivalence class), apply task-specified rules systematically:
def apply_alphabetical_rule(edges, rule="first_is_child"):
"""
Apply alphabetical ordering rule for ambiguous edges.
Args:
edges: List of (parent, child) tuples
rule: "first_is_child" means alphabetically first node is child
"""
resolved = []
for parent, child in edges:
if rule == "first_is_child":
# Alphabetically first should be child
if parent < child:
# parent comes first alphabetically, should be child
resolved.append((child, parent))
else:
resolved.append((parent, child))
return resolved
Always validate the DAG before proceeding:
import networkx as nx
G = nx.DiGraph(edges)
# Verify DAG
assert nx.is_directed_acyclic_graph(G), "Graph contains cycles!"
# Print structure for verification
print("Recovered DAG edges:")
for edge in G.edges():
print(f" {edge[0]} -> {edge[1]}")
Fit parameters appropriate to the data type:
Continuous Data (Linear Gaussian):
from pgmpy.models import LinearGaussianBayesianNetwork
lg_model = LinearGaussianBayesianNetwork(edges)
lg_model.fit(data)
# Verify parameters produce reasonable samples
samples = lg_model.simulate(1000)
print("Original stats:", data.describe())
print("Sampled stats:", samples.describe())
Discrete Data:
from pgmpy.models import BayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
model = BayesianNetwork(edges)
model.fit(data, estimator=MaximumLikelihoodEstimator)
To compute interventional distributions:
def apply_intervention(model, edges, var, value):
"""
Apply do(var=value) intervention.
Returns modified edges and intervention value.
"""
# Remove incoming edges to intervened variable
modified_edges = [(p, c) for p, c in edges if c != var]
return modified_edges, {var: value}
Generate samples and verify they match expected properties:
# Generate samples under intervention
intervention_samples = modified_model.simulate(n_samples)
# Verify intervention took effect
assert all(intervention_samples[intervened_var] == intervention_value)
# Compare non-intervened variable distributions
for var in non_intervened_vars:
orig_mean = data[var].mean()
sample_mean = intervention_samples[var].mean()
orig_std = data[var].std()
sample_std = intervention_samples[var].std()
# Check for reasonable similarity (allowing for intervention effects)
print(f"{var}: Original mean={orig_mean:.2f}, Sample mean={sample_mean:.2f}")
Wrong approach: Greedily selecting edges based on correlation strength.
Why it fails: Correlation doesn't distinguish direct from indirect relationships or confounded associations.
Correct approach: Use conditional independence testing (PC algorithm) or score-based methods with appropriate scoring functions.
Wrong approach: Abandoning proper methods when they fail due to memory.
Correct approach: Subsample data, reduce conditioning set size, or use more efficient implementations.
Example rule: "For ambiguous edges, the alphabetically first node is the child."
Given nodes M and R with an ambiguous edge:
Always verify:
Pay attention to required formats:
parent,child vs child,parent vs to,fromBefore submitting results, verify:
Python:
pgmpy - Bayesian network structure and parameter learningcausal-learn - Causal discovery algorithmsnetworkx - Graph manipulation and validationdowhy - Causal inference frameworkR:
bnlearn - Comprehensive Bayesian network library (often more memory-efficient)pcalg - PC algorithm implementationWhen to use R: Consider R's bnlearn if Python implementations run into memory issues, as it's often more optimized for large-scale structure learning.
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience