To use Rimay Quantum Feature Extraction, set up and format your data first. Kipu Hub and IBM Quantum Functions versions take the same input format. For questions about the method, see the business QML guide.
Step 0: Environment setup
Setup: dependencies and credentials
Python 3.11+, two Hub SDKs, three credentials.
uv init kipu-qml-lab
cd kipu-qml-lab
uv venv
uv add "qhub-service>=2.0" "qhub-api>=3.3" numpy pandas scikit-learn scipy matplotlib python-dotenv
Create and subscribe an Application on the Kipu Hub to Rimay - Quantum Feature Extraction - Simulator via the Marketplace. The application then provides the credentials for authentication. Keep these like passwords. If you think they might have leaked, rotate the keys to a new pair.
KQH_PERSONAL_ACCESS_TOKEN=...
KQH_ACCESS_KEY_ID=...
KQH_SECRET_ACCESS_KEY=...

Without the right keys and the subscription you will receive 401 errors. Recheck if you have provided your credentials correctly.

Free tier cap: 15 features, 3,000 samples
Step 1: Data formatting
This lab uses AI4I 2020, a public predictive-maintenance benchmark on OpenML. It holds 10,000 machine records with six features. Five sensors and one machine type. Only 339 are failures which means this is an imbalanced dataset.
Throughout the tutorial we will discuss and show validation tools you can use. A clear advantage case cannot be expected from a simulator. For more info, read business lesson.
# Task 1: what is in the dataset? Five sensors, one machine type, one label.
import pandas as pd # as_frame=True returns a pandas table
from sklearn.datasets import fetch_openml
df = fetch_openml("ai4i2020", version=1, as_frame=True).frame
sensors = [
"Air temperature [K]",
"Process temperature [K]",
"Rotational speed [rpm]",
"Torque [Nm]",
"Tool wear [min]",
]
print(df[sensors].describe().T[["mean", "min", "max"]].round(1))
print(df["Type"].value_counts())
print(df["Machine failure"].value_counts())
Task 1. Engineer three physics columns and build the payload
An engineered column is a new column computed from data you already have. The cell writes one per failure mode:
temp_difffor heat-dissipation failure, when the process-to-air temperature difference is smallpowerfor power failure, when mechanical power (torque times angular speed) leaves its bandoverstrainfor overstrain failure, when tool wear times torque exceeds what the product type tolerates
# Task 1: engineer the physics, build the 9-feature payload.
import json
import numpy as np
import pandas as pd
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
df = fetch_openml("ai4i2020", version=1, as_frame=True).frame
df["type_code"] = df["Type"].map({"L": 0, "M": 1, "H": 2}).astype(float)
# The three engineered features, straight from the AI4I failure-mode physics:
# heat dissipation fails on a small temperature difference, power failures on
# torque times angular speed outside a band, overstrain on tool wear times torque.
# Constant factors do not matter: the StandardScaler below removes them and Rimay's
# own minmax scaler is monotone per column.
df["temp_diff"] = df["Process temperature [K]"] - df["Air temperature [K]"]
df["power"] = df["Torque [Nm]"] * df["Rotational speed [rpm]"] * 2 * np.pi / 60
df["overstrain"] = df["Tool wear [min]"] * df["Torque [Nm]"]
# Column ORDER is the feature-to-qubit map and decides the pair topology.
CTRL9 = [
"Air temperature [K]",
"Process temperature [K]",
"Rotational speed [rpm]",
"Torque [Nm]",
"Tool wear [min]",
"temp_diff",
"power",
"overstrain",
"type_code",
]
X = df[CTRL9].astype(float)
y = df["Machine failure"].astype(int)
# Keep every failure, subsample non-failures up to the 3000-row cap.
rng = np.random.RandomState(42)
pos = y[y == 1].index.to_numpy() # 339 rows
neg = rng.choice(y[y == 0].index.to_numpy(), 3000 - len(pos), replace=False)
keep = np.concatenate([pos, neg])
rng.shuffle(keep)
Xk, yk = X.loc[keep], y.loc[keep]
X_train, X_test, y_train, y_test = train_test_split(
Xk, yk, test_size=0.2, random_state=42, stratify=yk
)
# Fit the scaler on the training rows only. Rimay applies its own minmax scaler
# on top, which is monotone per column, so this does not change the encoding.
sc = StandardScaler().fit(X_train)
X_train = pd.DataFrame(sc.transform(X_train), columns=CTRL9)
X_test = pd.DataFrame(sc.transform(X_test), columns=CTRL9)
y_train = pd.Series(y_train.to_numpy(), name="label")
y_test = pd.Series(y_test.to_numpy(), name="label")
payload = {
"X_train": X_train.to_dict(),
"y_train": y_train.to_frame("label").to_dict(),
"X_test": X_test.to_dict(),
"y_test": y_test.to_frame("label").to_dict(),
}
# Row keys must agree between the feature block and the label block, per split.
for xk_, yk_ in (("X_train", "y_train"), ("X_test", "y_test")):
xkeys = list(next(iter(payload[xk_].values())).keys())
assert list(payload[yk_]["label"].keys()) == xkeys, xk_
for col in payload[xk_].values():
assert list(col.keys()) == xkeys, xk_
with open("data.json", "w") as fh:
json.dump(payload, fh)
print(len(X_train), len(X_test), X_train.shape[1], int(y_train.sum() + y_test.sum()))
Step 2: Uploading to Datapools
Datapools allow Kipu Hub Services to read and save large data files. In this case, Rimay reads data.json from one pool and saves its results into an output datapool for later review. For this to work you create and provide the datapool IDs in the API request.
Task 2. Create the data pools and upload the payload. The clean-up cell at the end deletes them.
# Task 2
import io, json, os
from dotenv import load_dotenv
from qhub.api.platform import HubPlatformClient
load_dotenv()
platform = HubPlatformClient(api_key=os.getenv("KQH_PERSONAL_ACCESS_TOKEN"))
input_dp = platform.data_pools.create_data_pool(name="Rimay Lab Input")
output_dp = platform.data_pools.create_data_pool(name="Rimay Lab Output")
body = open("data.json", "rb").read()
platform.data_pools.add_data_pool_file(
id=input_dp.id, file=("data.json", io.BytesIO(body))
)
print("input ", input_dp.id)
print("output", output_dp.id)
print(f"uploaded data.json ({len(body) / 1024:.0f} KB)")
input <your input pool uuid>
output <your output pool uuid>
uploaded data.json (767 KB)
Step 3: Rimay Service Execution
Rimay - Simulator runs on ibm_aer, a state-vector simulator. Add the required fields with the datapool IDs to the request. For this tutorial we recommend runs at 2,000 shots (circuit computations). Results with other settings might vary.
Task 3. Submit the Rimay job with the two pool IDs
# Task 3
import os
import uuid
from dotenv import load_dotenv
from qhub.api.platform import HubPlatformClient
from qhub.service.client import HubServiceClient
from qhub.service.datapool import DataPoolGrant, DataPoolPermission
load_dotenv()
INPUT_POOL_ID = str(input_dp.id) # created in Task 2
OUTPUT_POOL_ID = str(output_dp.id) # created in Task 2
for _name, _val in (("INPUT_POOL_ID", INPUT_POOL_ID), ("OUTPUT_POOL_ID", OUTPUT_POOL_ID)):
try:
uuid.UUID(_val)
except ValueError:
raise SystemExit(f"{_name} is still the placeholder: Replace with the Pool-ID from Task 2")
# Check the key pair first: qhub-service reads the token reply without its status.
import httpx
_r = httpx.post("https://gateway.hub.kipu-quantum.com/token", data={"grant_type": "client_credentials"},
auth=(os.getenv("KQH_ACCESS_KEY_ID") or "", os.getenv("KQH_SECRET_ACCESS_KEY") or ""))
if _r.status_code != 200 or "expires_in" not in _r.text:
raise SystemExit(f"Hub rejected the access key: HTTP {_r.status_code}. Check KQH_ACCESS_KEY_ID and KQH_SECRET_ACCESS_KEY in .env")
platform = HubPlatformClient(api_key=os.getenv("KQH_PERSONAL_ACCESS_TOKEN"))
# The service may touch your pools only with a grant for your application:
# the application that owns your access key.
key_id = os.getenv("KQH_ACCESS_KEY_ID")
app_id = next((a.id for a in platform.applications.get_applications()
if any(k.access_key_id == key_id for k in platform.applications.get_application_access_keys(a.id))), None)
if app_id is None:
raise SystemExit("No application owns KQH_ACCESS_KEY_ID. Copy the key pair from an application in the dashboard")
service = HubServiceClient(
service_endpoint=(
"https://gateway.hub.kipu-quantum.com/kipu-quantum/"
"rimay---quantum-feature-extraction---simulator/1.0.0"
),
access_key_id=key_id,
secret_access_key=os.getenv("KQH_SECRET_ACCESS_KEY"),
platform_client=platform,
)
execution = service.run(
request={
"_mode": "fit_transform", # fit on train, transform train and test in one run
"_fit_reference": "None", # the LITERAL STRING, not Python None; see the caution
"num_shots": 2000, # not 500: see the shot-count note above
"num_runs": 1,
},
grants=[ # read the input, write the output
DataPoolGrant(name="input_data_pool", datapool_id=INPUT_POOL_ID,
application_id=app_id, permission=DataPoolPermission.VIEW),
DataPoolGrant(name="output_data_pool", datapool_id=OUTPUT_POOL_ID,
application_id=app_id, permission=DataPoolPermission.MODIFY),
],
)
print("execution id:", execution.id)
execution.wait_for_final_state(timeout=900, wait=10)
print("status:", execution.status)
if execution.status == "FAILED":
for log in execution.logs():
print(log)
elif not list(platform.data_pools.get_data_pool_files(id=OUTPUT_POOL_ID)):
raise SystemExit("The job wrote nothing to the output pool. Check the grants above, then run this box again")
The service runs for a few minutes. If this cell fails unexpectedly, check if you have added the datapool IDs correctly.
Step 4: Fetch the Results
By now, the output pool holds six .npy files: the classical features, and the quantum features. Each file has labeled train and test blocks.
Task 4. Download the results
# Task 4
import os
import uuid
import numpy as np
from pathlib import Path
from dotenv import load_dotenv
from qhub.api.platform import HubPlatformClient
load_dotenv()
platform = HubPlatformClient(api_key=os.getenv("KQH_PERSONAL_ACCESS_TOKEN"))
OUTPUT_POOL_ID = str(output_dp.id) # created in Task 2
try:
uuid.UUID(OUTPUT_POOL_ID)
except ValueError:
raise SystemExit("OUTPUT_POOL_ID is still the placeholder: paste the id Task 2 printed")
out_dir = Path("rimay_output")
out_dir.mkdir(exist_ok=True)
def download_verified(dp_id, f, dest, attempts=3):
"""Stream a pool file and verify the full content_length actually arrived."""
for attempt in range(1, attempts + 1):
try:
stream = platform.data_pools.get_data_pool_file(id=dp_id, file_id=f.id)
n = 0
with open(dest, "wb") as fp:
for chunk in stream:
n += len(chunk)
fp.write(chunk)
if f.content_length and n != f.content_length:
raise IOError(f"received {n}/{f.content_length} bytes")
return n
except Exception as e:
if attempt == attempts:
raise RuntimeError(f"failed to download {f.name}: {e}") from e
for f in platform.data_pools.get_data_pool_files(id=OUTPUT_POOL_ID):
if f.name.endswith(".npy"):
n = download_verified(OUTPUT_POOL_ID, f, out_dir / f.name)
print(f" {f.name} ({n} bytes)")
Xc_train = np.load(out_dir / "Xc_train.npy")
Xq_train = np.load(out_dir / "Xq_train_0.npy")
n_c, n_q = Xc_train.shape[1], Xq_train.shape[1]
print(f"classical {n_c}, quantum {n_q} = {n_c} per-feature + {n_q - n_c} pairs")
assert n_q == 2 * n_c - 1
assert n_c == 9, "expected the 9-feature extraction; re-run Tasks 1 to 3"
classical 9, quantum 17 = 9 per-feature + 8 pairs

No Hub key, or the job is slow? Use the saved run
This box puts the six arrays of our reference extraction (2026-10-30, the same Task 1 payload) into rimay_output/. Steps 5 to 7 then run as if Task 4 had finished. Your own run overwrites them.
# Saved run: the reference extraction, in place of Tasks 2 to 4.
import os
import urllib.request
from pathlib import Path
SITE = os.getenv("KIPU_SITE", "https://kipu-quantum.com")
out = Path("rimay_output")
out.mkdir(exist_ok=True)
for name in ("Xc_train", "Xq_train_0", "y_train", "Xc_test", "Xq_test_0", "y_test"):
url = f"{SITE}/academy/run/data/qml-saved-run/{name}.npy"
(out / f"{name}.npy").write_bytes(urllib.request.urlopen(url).read())
print("saved run in rimay_output/:", ", ".join(sorted(p.name for p in out.glob("*.npy"))))
Step 5: Utilizing Rimay Results
Now we have everything we need to continue with the analysis. For comparison set up three tests for raw (original six features), expert (raw + engineered), and expert + Rimay. For classification we use naive Bayes, logistic regression and linear SVM.
An important step in the process is selection. We use the Fisher discriminant which is a per column measure of squared class-mean gap over summed class variance. It aims to show feature relevance and redundancy based on statistics. We can later tune the cutoff GATE_QUANTILE which adds data only above a certain threshold.
To check for statistical significance compare results under Wilcoxon signed-rank p-value with Holm-correction (15 random splits, and out-of-fold). You do not need to get the last sentence in full yet. If you are interested you can chat with your LLM of choice or your trusted colleague about it.
Task 5. Compare the four arms against their baselines
Run the helper cell below first, then the comparison cell.
The helper cell, given. Task 6 adds to it:
# Helpers, started in Task 5
import numpy as np
from pathlib import Path
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.naive_bayes import GaussianNB
# The raw sensor columns inside the 9-column table: five sensors plus type code.
RAW = [0, 1, 2, 3, 4, 8]
# Kipu brand colors (tokens.css)
GOLD, MUTED, FG, BG = "#b38f12", "#6b6b6b", "#0f1319", "#ffffff"
def load_arrays(out_dir="rimay_output"):
"""The six row-aligned arrays Task 4 downloaded, in one call."""
d = Path(out_dir)
return (np.load(d / "Xc_train.npy"), np.load(d / "Xq_train_0.npy"),
np.load(d / "y_train.npy").ravel().astype(int),
np.load(d / "Xc_test.npy"), np.load(d / "Xq_test_0.npy"),
np.load(d / "y_test.npy").ravel().astype(int))
def fisher_scores(X, y):
"""Per-column Fisher ratio: squared class-mean gap over summed class variance."""
a, b = X[y == 1], X[y == 0]
return (a.mean(0) - b.mean(0))**2 / (a.var(0) + b.var(0) + 1e-12)
class FisherGate(BaseEstimator, TransformerMixin):
"""Adaptive cutoff instead of a fixed top-k. Keep all n_raw classical
columns; keep a quantum column only if its Fisher score clears the median
of the classical columns' own scores. In words: a quantum column has to be
at least as informative, on its own, as a typical column you already had.
Computed inside fit, so it sees the training fold only."""
def __init__(self, n_raw=9, q=0.5):
self.n_raw, self.q = n_raw, q
def fit(self, X, y):
f = fisher_scores(X, y)
thr = np.quantile(f[:self.n_raw], self.q)
self.keep_ = np.r_[np.arange(self.n_raw),
self.n_raw + np.where(f[self.n_raw:] >= thr)[0]]
return self
def transform(self, X):
return X[:, self.keep_]
The harness, fill the arms:
# Task 5: the progression, raw -> expert -> expert + Rimay.
import numpy as np
from scipy.stats import wilcoxon
from sklearn.base import clone
from sklearn.model_selection import StratifiedShuffleSplit, RepeatedStratifiedKFold, StratifiedKFold, GridSearchCV
from sklearn.metrics import average_precision_score
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.naive_bayes import GaussianNB
# RBF SVM and gradient boosting sit out of this panel for training time; the
# study's Holm-corrected readings for both are quoted below the expected output.
MODELS = {
"naive bayes": (GaussianNB(), {"m__var_smoothing": [1e-9, 1e-7, 1e-5, 1e-3]}),
"logistic regression": (LogisticRegression(max_iter=5000), {"m__C": [0.01, 0.1, 1, 10, 100]}),
"linear SVM": (LinearSVC(max_iter=20000, dual="auto"), {"m__C": [0.01, 0.1, 1, 10]}),
}
def holm(pvals):
"""Holm step-down correction over a dict of name -> raw p-value."""
items = sorted(pvals.items(), key=lambda kv: kv[1])
m, out, running = len(items), {}, 0.0
for i, (name, p) in enumerate(items):
running = max(running, (m - i) * p)
out[name] = min(1.0, running)
return out
Xc_train, Xq_train, y_train, Xc_validate, Xq_validate, y_validate = load_arrays()
Xc = np.vstack([Xc_train, Xc_validate])
Xq = np.vstack([Xq_train, Xq_validate])
Y = np.concatenate([y_train, y_validate])
assert Xc.shape[1] == 9, "rimay_output holds an older run; re-run Tasks 1 to 4"
# The progression: each arm is read against the one it has to beat.
# The gate's knob: a quantum column must clear this quantile of the classical
# columns' own Fisher scores. 0.5 = at least as good as the typical column.
GATE_QUANTILE = 0.5
ARMS = {
"raw": (Xc[:, RAW], None), # sensors only, no extraction needed
"expert": (Xc, None), # + the three engineered columns
"expert+all": (np.hstack([Xc, Xq]), None), # + all 17 quantum columns
"expert+gated": (np.hstack([Xc, Xq]), FisherGate(q=GATE_QUANTILE)),
}
BASELINE = {"expert": "raw", "expert+all": "expert", "expert+gated": "expert"}
def fit_score(X, est, grid, sel, tr, te, seed):
steps = [("sc", StandardScaler())]
if sel is not None:
steps.insert(0, ("sel", clone(sel)))
steps.append(("m", clone(est)))
gs = GridSearchCV(Pipeline(steps), grid, scoring="average_precision",
cv=StratifiedKFold(3, shuffle=True, random_state=seed), n_jobs=1)
gs.fit(X[tr], Y[tr])
b = gs.best_estimator_
s = (b.decision_function(X[te]) if hasattr(b, "decision_function")
else b.predict_proba(X[te])[:, 1])
return average_precision_score(Y[te], s)
# Two evaluation protocols over the same arms. split: 15 random 80/20 draws.
# oof: 5 folds x 3 repeats, every row tested exactly once per repeat, the
# fold-level pairing the Step 7 curves argue for.
PROTOCOLS = {
"split": list(StratifiedShuffleSplit(n_splits=15, test_size=0.2,
random_state=7).split(Xc, Y)),
"oof": list(RepeatedStratifiedKFold(n_splits=5, n_repeats=3,
random_state=7).split(Xc, Y)),
}
res = {}
for proto, splits in PROTOCOLS.items():
out = {(m, a): [] for m in MODELS for a in ARMS}
for seed, (tr, te) in enumerate(splits):
for m, (est, grid) in MODELS.items():
for a, (X, sel) in ARMS.items():
out[(m, a)].append(fit_score(X, est, grid, sel, tr, te, seed))
res[proto] = out
# Absolute AP per arm, delta against the arm's own baseline, and a Wilcoxon
# signed-rank p per step, Holm corrected across the three comparisons within
# each model, once per protocol.
for m in MODELS:
ph = {}
for proto in ("split", "oof"):
ph[proto] = holm({a: wilcoxon(np.array(res[proto][(m, a)]),
np.array(res[proto][(m, BASELINE[a])])).pvalue
for a in BASELINE})
line = f"{m:20s} raw {np.mean(res['split'][(m, 'raw')]):.4f}"
for a in ("expert", "expert+all", "expert+gated"):
v = np.mean(res["split"][(m, a)])
d = v - np.mean(res["split"][(m, BASELINE[a])])
line += (f" | {a} {v:.4f} ({d:+.4f} vs {BASELINE[a]},"
f" p {ph['split'][a]:.4f}, oof p {ph['oof'][a]:.4f})")
print(line)
# Task 5b: what the gate sees. Fisher scores of all 26 columns,
# computed on the training split only, classical vs quantum, threshold marked.
import numpy as np
import matplotlib.pyplot as plt
Xc_train, Xq_train, y_train, *_ = load_arrays()
X = np.hstack([Xc_train, Xq_train])
f = fisher_scores(X, y_train)
n_raw = Xc_train.shape[1]
GATE_QUANTILE = 0.5
thr = np.quantile(f[:n_raw], GATE_QUANTILE)
names = ([f"c{i}" for i in range(n_raw)]
+ [f"q{i}" for i in range(n_raw)]
+ [f"pair{i}" for i in range(X.shape[1] - 2 * n_raw)])
order = np.argsort(-f)
fig, ax = plt.subplots(figsize=(14, 5), dpi=100)
fig.patch.set_facecolor(BG)
colors = [FG if i < n_raw else GOLD for i in order]
ax.bar(range(len(f)), f[order], color=colors)
ax.axhline(thr, color=MUTED, lw=1.5, ls="--")
ax.text(len(f) - 0.5, thr, " gate threshold: q-quantile of the classical scores", color=MUTED,
va="bottom", ha="right", fontsize=9, fontfamily="monospace")
ax.set_xticks(range(len(f)))
ax.set_xticklabels([names[i] for i in order], rotation=60, fontsize=8,
fontfamily="monospace")
ax.set_ylabel("FISHER SCORE")
ax.set_title("The spectrum the gate cuts: classical (dark) vs quantum (gold)",
color=FG, fontweight="bold", loc="left")
ax.set_facecolor(BG)
for sp in ("top", "right"): ax.spines[sp].set_visible(False)
for sp in ("left", "bottom"): ax.spines[sp].set_color(MUTED)
ax.yaxis.label.set_fontfamily("monospace"); ax.yaxis.label.set_color(MUTED)
ax.tick_params(colors=MUTED)
fig.tight_layout()
fig.savefig("fisher-scores.png", facecolor=BG, bbox_inches="tight")
plt.show()
kept = int((f[n_raw:] >= thr).sum())
print(f"threshold {thr:.4f} (q={GATE_QUANTILE} quantile of the {n_raw} classical scores)")
print(f"quantum columns kept: {kept} of {X.shape[1] - n_raw}")
print("top five columns:", ", ".join(f"{names[i]} {f[i]:.3f}" for i in order[:5]))
Caution. Fisher score computed on the whole dataset is leakage. Compute it on the training fold only if you do not want to get representative and significant results.
Step 6: Visualize Model Quality
Quality curves allow us to show a model's performance. ROC divides false alarms by the healthy machines. The fewer false alarms and the more actual failures we predict, the better. A PR-curve is useful in imbalanced scenarios. The rarer and more expensive the positive class, the more relevant it becomes.
Task 6. Draw the ROC and PR curves
First run the tuned pipeline cell, given:
# Helpers, added in Task 6
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.naive_bayes import GaussianNB
def nb_search(seed, gate=False, n_jobs=1):
"""The Task 5 naive-Bayes protocol as one reusable estimator: scaler plus
GaussianNB, smoothing grid chosen by inner CV, optionally behind the
FisherGate. Steps 6 to 8 reuse it."""
steps = [("sc", StandardScaler()), ("m", GaussianNB())]
if gate:
steps.insert(0, ("sel", FisherGate()))
grid = {"m__var_smoothing": [1e-9, 1e-7, 1e-5, 1e-3]}
return GridSearchCV(Pipeline(steps), grid, scoring="average_precision",
cv=StratifiedKFold(3, shuffle=True, random_state=seed),
n_jobs=n_jobs)
Then fill the curves:
# Task 6: ROC and PR for the progression, one model, three arms.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import (precision_recall_curve, roc_curve,
average_precision_score, roc_auc_score)
Xc_train, Xq_train, y_train, Xc_validate, Xq_validate, y_validate = load_arrays()
assert Xc_train.shape[1] == 9, "rimay_output holds an older run; re-run Tasks 1 to 4"
def fit_score(Xtr, Xte, gate=False):
gs = nb_search(seed=0, gate=gate)
gs.fit(Xtr, y_train)
return gs.best_estimator_.predict_proba(Xte)[:, 1]
# The extraction already handed you one fixed split: 2,400 train, 600 validation.
CURVES = [
("raw 6", MUTED, fit_score(Xc_train[:, RAW], Xc_validate[:, RAW])),
("expert 9", FG, fit_score(Xc_train, Xc_validate)),
("expert + Rimay (gated)", GOLD, fit_score(np.hstack([Xc_train, Xq_train]),
np.hstack([Xc_validate, Xq_validate]), gate=True)),
]
fig, (axr, axp) = plt.subplots(1, 2, figsize=(14, 6), dpi=100)
fig.patch.set_facecolor(BG)
prev = y_validate.mean()
for name, col, s in CURVES:
fpr, tpr, _ = roc_curve(y_validate, s)
axr.plot(fpr, tpr, color=col, lw=3, solid_capstyle="round",
label=f"{name} AUC {roc_auc_score(y_validate, s):.3f}")
p, r, _ = precision_recall_curve(y_validate, s)
axp.plot(r, p, color=col, lw=3, solid_capstyle="round",
label=f"{name} AP {average_precision_score(y_validate, s):.3f}")
axr.plot([0, 1], [0, 1], color=MUTED, lw=1, ls="--") # chance: the diagonal
axp.axhline(prev, color=MUTED, lw=1, ls="--") # chance: the prevalence
axr.set_xlabel("FALSE POSITIVE RATE"); axr.set_ylabel("TRUE POSITIVE RATE")
axp.set_xlabel("RECALL"); axp.set_ylabel("PRECISION")
axr.set_title("ROC: the gaps compress", color=FG, fontweight="bold", loc="left")
axp.set_title("PR: the picture your stakeholder lives in", color=FG, fontweight="bold", loc="left")
for ax in (axr, axp):
ax.set_facecolor(BG)
for sp in ("top", "right"): ax.spines[sp].set_visible(False)
for sp in ("left", "bottom"): ax.spines[sp].set_color(MUTED)
ax.xaxis.label.set_fontfamily("monospace"); ax.yaxis.label.set_fontfamily("monospace")
ax.xaxis.label.set_color(MUTED); ax.yaxis.label.set_color(MUTED)
ax.tick_params(colors=MUTED)
ax.set_xlim(0, 1); ax.set_ylim(0, 1.02)
ax.legend(frameon=False, fontsize=9, loc="lower right")
fig.tight_layout()
fig.savefig("pr-vs-roc.png", facecolor=BG, bbox_inches="tight")
plt.show()
print(f"prevalence {prev:.3f}, positives in validation {int(y_validate.sum())}")
for name, _, s in CURVES:
print(f"{name:24s} ROC AUC {roc_auc_score(y_validate, s):.4f}"
f" AP {average_precision_score(y_validate, s):.4f}")
Step 7: Out-of-fold analysis
A single 80/20 split tests only part of the data. 600 rows and 68 failures. That gives results that can happen by pure chance. Out-of-fold prediction allows you to get more out of your sparse data.
Task 7. Score every row out of fold
# Task 7: the same comparison scored two ways.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.metrics import precision_recall_curve, average_precision_score
Xc_train, Xq_train, y_train, Xc_validate, Xq_validate, y_validate = load_arrays()
# Pool the split back together: out-of-fold scores every one of the 3,000 rows.
Xc = np.vstack([Xc_train, Xc_validate])
Xq = np.vstack([Xq_train, Xq_validate])
Y = np.concatenate([y_train, y_validate])
X_hyb = np.hstack([Xc, Xq])
def oof_scores(X, gate=False):
"""5 folds x 3 repeats. Every row scored 3 times by a model that never saw it."""
acc, cnt = np.zeros(len(Y)), np.zeros(len(Y))
rkf = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=7)
for tr, te in rkf.split(X, Y):
gs = nb_search(seed=7, gate=gate)
gs.fit(X[tr], Y[tr])
acc[te] += gs.best_estimator_.predict_proba(X[te])[:, 1]
cnt[te] += 1
assert cnt.min() == 3
return acc / cnt
def single_split_scores(X_tr, X_te, gate=False):
"""The one fixed split the extraction handed you: 2,400 train, 600 validation."""
gs = nb_search(seed=0, gate=gate)
gs.fit(X_tr, y_train)
return gs.best_estimator_.predict_proba(X_te)[:, 1]
panels = [
("One fixed split, 600 rows", y_validate,
[("expert 9", FG, single_split_scores(Xc_train, Xc_validate)),
("expert + Rimay (gated)", GOLD,
single_split_scores(np.hstack([Xc_train, Xq_train]),
np.hstack([Xc_validate, Xq_validate]), gate=True))]),
("Out of fold, all 3,000 rows", Y,
[("expert 9", FG, oof_scores(Xc)),
("expert + Rimay (gated)", GOLD, oof_scores(X_hyb, gate=True))]),
]
fig, axes = plt.subplots(1, 2, figsize=(14, 6), dpi=100)
fig.patch.set_facecolor(BG)
for ax, (title, y_true, curves) in zip(axes, panels):
for name, col, s in curves:
p, r, _ = precision_recall_curve(y_true, s)
ax.plot(r, p, color=col, lw=3, solid_capstyle="round",
label=f"{name} AP {average_precision_score(y_true, s):.3f}")
ax.axhline(y_true.mean(), color=MUTED, lw=1, ls="--")
ax.set_facecolor(BG)
for sp in ("top", "right"): ax.spines[sp].set_visible(False)
for sp in ("left", "bottom"): ax.spines[sp].set_color(MUTED)
ax.set_xlabel("RECALL"); ax.set_ylabel("PRECISION")
ax.xaxis.label.set_fontfamily("monospace"); ax.yaxis.label.set_fontfamily("monospace")
ax.xaxis.label.set_color(MUTED); ax.yaxis.label.set_color(MUTED)
ax.tick_params(colors=MUTED)
ax.set_xlim(0, 1); ax.set_ylim(0, 1.02)
ax.set_title(title, color=FG, fontweight="bold", loc="left")
ax.legend(frameon=False, fontsize=9, loc="lower left")
fig.tight_layout()
fig.savefig("pr-single-vs-oof.png", facecolor=BG, bbox_inches="tight")
plt.show()
for title, y_true, curves in panels:
for name, _, s in curves:
print(f"{title:32s} {name:24s} AP {average_precision_score(y_true, s):.4f}")
Summary:
- Engineered physics helps over raw sensors even before adding quantum. +0.0424 to +0.1163 average precision increase on average
- Rimay columns add +0.0420 to +0.0582, significant under both protocols for all three models; the threshold gate lifts naive Bayes to +0.0646
- Quantum columns computed from the sensors alone moved no model significantly. Likely because it holds no structure Rimay can reveal
- Other models might not benefit from the same quantum features on the same dataset
Clean up
Delete the two data pools from Task 2 when you are done. Their files go with them.
# Clean up: delete the two data pools Task 2 created, with their files.
for pool in (input_dp, output_dp):
for f in platform.data_pools.get_data_pool_files(id=pool.id):
platform.data_pools.delete_data_pool_file(id=pool.id, file_id=f.id)
platform.data_pools.delete_data_pool(id=pool.id)
print("deleted pool", pool.id)
Outlook: Surrogates and Production Use
Rimay uses QPU or simulator on the cloud. For quick classification it is practically infeasible at best. For an on-premise or air-gapped plant floor a cloud round-trip is a policy violation. Surrogates can help here: training with the QPU, then extract the model to reproduce the results itself. The whole pipeline then runs inside your own infrastructure. Read more about Kipu's off-line surrogate framework here: arXiv:2605.19801. If you prefer the shorter blog version, click this link here.
Definition of QML
In the business lesson we discussed the definition of QML. After this tutorial I would like to add a sentence. For more information check out Rimay or the Kipu Hub Marketplace. The next session looks at the SDK, the CLI and MCP, on the Hub itself. I hope that it will help you build your first hybrid quantum workflow as an API. See you there.
quan·tum ma·chine learn·ing
/ˈkwɒn.təm məˈʃiːn ˈlɜː.nɪŋ/noun
- 1
the use of a quantum processor somewhere inside a machine-learning pipeline, whether to represent the data, to fit the model, or to make the prediction.
- 2
Rimay is the tool that computes the re-presented fit-transform structure of your data so that a model can act on it.
Documentation: Kipu Quantum Hub | Hub docs | Quickstart | Service SDK | Using a service | Access tokens | Rimay product page | Rimay on the blog | Kipu Quantum Academy
Research: Quantum feature extraction on IBM hardware, MedMNIST and molecular toxicity (Scientific Reports 2026, doi:10.1038/s41598-026-67564-0) | Aerial tree-genus classification with quantum features (arXiv:2602.18350) | Off-line surrogate framework (arXiv:2605.19801) | Motor-imagery EEG classification, Carter et al., Mayo Clinic Proceedings 2026 | Heaton, an empirical analysis of feature engineering (arXiv:1701.07852) | Bengio, Courville and Vincent, representation learning (IEEE TPAMI 35(8), 1798 to 1828, 2013)