/prism:programming-prism-dsfrom prism
Performs data science workflows using PRISM probabilistic programming from Python (pyprism): discretizes tabular data, builds generative models (naive Bayes, latent-class clustering), learns parameters via EM/MAP/variational Bayes, and evaluates predictions.
Ships in prism. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
A PRISM model is a generative program over discrete values:
values/2 declares the random variables ("switches").msw/2 draws them.learn/1 estimates their probabilities from observed goals.The workflow of the tutorial:
DataFrame --pyprism.dataset--> train.dat / test.dat obs(Y,[X0,...,Xn]). (discretized ints)
--PRISM program + learn--> save_sw('nb.sw')
--pyprism.df.sw2df--> parameters as a DataFrame, plots
--restore_sw + viterbig / prob / hindsight--> predictions --> metrics in Python
Setup. Install pyprism and a PRISM binary as in programming-pyprism. Then:
pip install pandas "scikit-learn>=1.6,<1.9" matplotlib
pyprism.dataset.Every engine.query is a new PRISM process. Learn and save_sw in one query. Start every later query with restore_sw(...).
from pyprism.dataset import load_discrete_diabetes, load_discrete_california_housing, preprocess
ds = load_discrete_diabetes(out_filename="train.dat", out_test_filename="test.dat",
pred="obs", test_ratio=0.2) # 353 / 89 rows
# your own data:
ds = preprocess(df_x, df_y, out_filename="train.dat", out_test_filename="test.dat",
pred="obs", test_ratio=0.2)
Each row becomes a fact obs(Y,[X0,...,Xn])., or obs([X0,...,Xn]). with with_y=False.
| Argument | Default | Meaning |
|---|---|---|
pred | "data" | The predicate name written to the file. Pass pred="obs" if your program uses obs. The tutorial's final Pima exercise omits it and gets data(...) facts. |
disc_bins_x, disc_bins_y | 5, 8 | The number of quantile bins (KBinsDiscretizer, ordinal). |
thresh_uniq_x, thresh_uniq_y | 10 | Columns with fewer unique values are kept as they are. For example, diabetes sex stays 1/2, and an iris target stays 0/1/2. |
test_ratio | 0.0 | Train/test split with a fixed random_state=42. The bins are fitted on the training part. |
missing_px, missing_py | 0.0 | Random missing values, written as _ (see section 3). |
The returned dict has these keys:
X, yX_discretized, y_discretizedX_test_discretized, y_test_discretizedX_discretizers, y_discretizer: fitted bins, usable as plot labelsattr_list: column names in the list orderplot_discretization(ds["X"], disc_bins=5) and
plot_discretized_data(ds["X_discretized"]) show histograms before and after
discretization.
Check the value ranges (ds["X_discretized"].max(),
ds["y_discretized"].unique()). The ranges in values/2 must contain every
value that occurs.
Pass the model to engine.set_db(r"""..."""). The @= list comprehension is
built in, e.g. N @= [X : X in 0..7] gives N = [0,1,...,7].
Independent features. One distribution per column:
values(dice(_),[0,1,2,3,4]).
obs(L) :- obs(L,0).
obs([],_).
obs([X|R],N) :- msw(dice(N),X), N1 is N+1, obs(R,N1).
Naive Bayes classifier. Draw the target, then each feature given the target.
out(T,N) is the distribution of column N for class T:
values(target,N) :- N @= [X : X in 0..7]. % = disc_bins_y classes
values(out(_,_),N) :- N @= [X : X in 0..4]. % = disc_bins_x bins
obs(T,L) :- msw(target,T), nb(0,T,L).
nb(_,_,[]).
nb(N,T,[X|L]) :- msw(out(T,N),X), N1 is N+1, nb(N1,T,L).
Latent-class clustering (unsupervised). Use the same structure, but the
class is hidden. clus(C,L) exposes the cluster for the assignment afterwards:
values(cluster,Cs) :- num_clusters(K), Cs @= [C : C in 1..K].
values(out(_,_),[0,1,2,3,4]).
num_clusters(3).
obs(L) :- clus(_,L).
clus(C,L) :- msw(cluster,C), nb(0,C,L).
nb(_,_,[]).
nb(N,C,[X|L]) :- msw(out(C,N),X), N1 is N+1, nb(N1,C,L).
The same pattern extends to HMMs, Bayesian networks and mixtures (see prism-programming). The data only has to be goals that the program can generate.
lines, status = engine.query("""
load_clauses('train.dat',Gs), learn(Gs), save_sw('nb.sw'),
learn_statistics(log_likelihood,LL), learn_statistics(bic,BIC)""", out=["LL", "BIC"])
lines[-1] # 'LL=-5550.71,BIC=-6509.88' (learning statistics are in the earlier lines)
Smoothing. Maximum likelihood (the default) gives probability 0 to
combinations unseen in training: 39 of the 408 naive-Bayes parameters for
diabetes. Then prob of a test row can be 0. For MAP estimates with a pseudo
count, put this in front of learn:
set_prism_flag(default_sw_d,1.0), load_clauses(...), learn(Gs), ...
This gives no zero parameters.
Variational Bayes. Use learn_b(Gs), and learn_statistics(free_energy,F) for the objective.
Latent models. Run several random restarts with set_prism_flag(restart,5), and keep the best result.
Missing values. A _ in a goal, e.g. obs(4,[3,2,4,3,0,_,_,3,3,1]), is an unobserved variable. EM sums over its values, so no imputation is needed.
Model selection. PRISM's bic is log-likelihood − (#params/2)·ln N, so larger is better. For example, latent-class models on diabetes (all 442 rows, 5 restarts, scikit-learn 1.8):
| clusters | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| BIC | −6688 | −6319 | −6303 | −6297 |
Other statistics: num_parameters, num_iterations, learn_time.
from pyprism.df import sw2df, plot_dist, get_conditional_dist2, disc2binlist
df = sw2df("nb.sw") # columns: Name Arity Term Status Vals Param Arg1..Arg5 (one row per switch)
df[df["Name"] == "target"] # P(target)
df[df["Name"] == "out"] # P(X_n | target), Arg1 = class, Arg2 = column index
attr_y = disc2binlist(ds["y_discretizer"]) # bin labels like "25.0-60.0"
attr_x = {k: disc2binlist(d) for k, d in ds["X_discretizers"].items()}
plot_dist(df[df["Name"] == "target"], attr_y, title="target") # bar chart
get_conditional_dist2(df[df["Name"] == "out"], arg_var="Arg2", arg_cond="Arg1",
attr_var=ds["attr_list"], attr_cond=attr_y, attr_val=attr_x,
cond_var_name="y") # one heatmap per feature
Vals and Param are Python lists.Arg*, the switch arguments are strings.disc2binlist needs a fitted discretizer. Columns kept as they are have none: they are missing from X_discretizers, and y_discretizer is None. Check for None, as the tutorial does.The whole test set in one query. viterbig(obs(Y,L)) binds Y to the most
probable class:
lines, status = engine.query("""restore_sw('nb.sw'), load_clauses('test.dat',Gs),
findall(T-Y, (member(obs(T,L),Gs), viterbig(obs(Y,L))), R)""", out="R")
pairs = [p.split("-") for p in lines[0][len("R=["):-1].split(",")] # [['4','3'], ...]
acc = sum(t == y for t, y in pairs) / len(pairs)
Always compare with a baseline. For diabetes discretized into 8 classes, naive Bayes gets 0.225, and predicting the majority class gets 0.213. The model is weak there, and the pipeline itself is fine.
The distribution over classes for one row.
hindsight(obs(_,L),obs(_,_),HP) returns HP=[[obs(0,L),P0],[obs(1,L),P1],...]. These are the joint probabilities; divide by their sum to get the posterior.hindsight(G,G), as in the tutorial, only prints them.member(Y,[0,...,7]), prob(obs(Y,L),P) with findall=True gives the same numbers.Precision.
out= prints about 6 significant digits (P=6.87932e-08).format("P=~15e~n",[P]) for full precision.log_prob(G,LP) when products of many small probabilities would underflow.restore_sw('nb.sw') at the start of every prediction query. Relative paths (train.dat, nb.sw) are resolved against the Python process's current directory.pairs above.values/2. The whole learn aborts with error(prism_runtime_error(explanation_not_found),...), because that goal has no explanation. Check the ranges after discretization (section 1).findall over all test rows prints one long line. Aggregate in Prolog when only counts are needed:
findall(C, (member(obs(T,L),Gs), viterbig(obs(Y,L)), (T==Y -> C=1 ; C=0)), Cs), sumlist(Cs,Ok), length(Cs,N)
pyprism.df draws with matplotlib and calls plt.show(). Use matplotlib.use("Agg") in scripts without a display.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub prismplp/prism --plugin prism6 skills in this plugin
/install-linuxBuild PRISM and T-PRISM from source and set up their environment on Linux (Ubuntu 22.04, 24.04, 26.04). Covers the apt packages, the C and Prolog build with the USE_NPY, USE_H5, USE_PB and PROCTYPE=mp options, PATH, regression tests, the T-PRISM Python environment (venv, PyTorch, protobuf), the runtime libraries of the prebuilt packages, and fixes for common build and run errors. Use this skill whenever someone wants to install, compile, build, rebuild or set up PRISM or T-PRISM on Linux or Ubuntu (e.g. "コンパイル", "ビルド", "環境構築", "インストール"). Also use it when someone hits an error from make, upprism, prism or tprism on Linux, or prepares a Linux machine, container or CI job for PRISM, even if they don't say "install"./install-mingwBuild and verify PRISM and bp4prism on Windows with native MinGW-w64, including optional 32bit and 64bit MS-MPI builds, without tools/mingw helper scripts./prism-programmingHow to write, run, debug and learn parameters for PRISM programs (probabilistic Prolog on B-Prolog, .psm files, prismplp/prism), with the differences from ProbLog and plain Prolog spelled out, plus two recipes - turning a deterministic Prolog rule base into a PRISM model whose default reproduces the rules and is then refined by EM, and driving a .psm from shell scripts, other languages and pipelines (prism_main/1 modes, parseable output, exit codes). Use it whenever the user mentions PRISM, .psm, msw/2, values/2, upprism, learn/1, save_sw/restore_sw, viterbif, hindsight, probf, graphical EM, 確率的推論 or probabilistic prolog, asks for an HMM, PCFG, Bayesian network or other model in PRISM, translates ProbLog or Prolog into PRISM, or debugs an msw, negation or learn error. Read it before writing any PRISM code, because ProbLog and Prolog intuitions (shared random variables, negation) silently give wrong answers. For T-PRISM use tprism-programming, for Python programming-pyprism and programming-prism-ds./programming-pyprismInstall PyPRISM (the pyprism package, the Python interface of PRISM, prismplp/pyprism) so that it matches the Python environment (Google Colab, venv or conda on Linux, Jupyter), and use its PrismEngine to run Prolog and PRISM programs and queries from Python (set_db, query with out/findall/find_n, prob, sample, learn, save_sw/restore_sw, parsing the results). Use this skill whenever the user mentions pyprism, PyPRISM, PrismEngine, engine.query or engine.set_db, runs PRISM or Prolog from Python or a notebook, follows the Prolog or PRISM tutorials on Colab ("PythonからPRISM", "PythonからProlog", "pyprismのインストール"), or gets a pyprism result like (None, 'error'). For writing the probabilistic models themselves also use prism-programming, and for data-science workflows (pyprism.dataset, sw2df, prediction) use programming-prism-ds./tprism-programmingHow to write, build and train T-PRISM (Tensorized PRISM, prismplp/prism) programs, where Prolog atoms denote tensors combined by einsum and trained with PyTorch. Covers .psm programs (tensor/2, tensor_atom/2, operator/1, subgoal/2, get/2, placeholders, embeddings, save_expl_graph), `tprism train/test`, and the Python API (load_explanation_graph, TprismModel fit/pred, custom operators and losses) in Jupyter or Colab, also via PyPRISM's PrismEngine. Use it whenever the user mentions T-PRISM, TPRISM, tprism, TprismModel or T_PRISM_tutorial, or wants tensor decomposition, DistMult, an MLP or CNN, MNIST addition, a Markov chain or transitive closure written in Prolog with tensors, or to port a Prolog, ProbLog or PRISM model to T-PRISM. Read it before writing T-PRISM code, because its semantics (sum over Prolog solutions, einsum over index names, operator/1 scope, compile time vs run time) differ from Prolog, ProbLog and classic PRISM, and mistakes are silent. For classic PRISM (msw/values) use prism-programming.Other plugins' skills for the same job