Written By @SWATI NANDA , @Anand Awasthi
This tutorial walks through an end-to-end enterprise workflow: from setting up the right users and permissions in IBM Software Hub, to using a quantum circuit to generate a provably unbiased training dataset, to feeding that dataset into an AutoAI experiment. Every step is shown, every cell is explained, and no quantum physics background is required.
The Problem With How We Sample Training Data Today
Every AI model starts with a dataset. Before training, we pick a sample of that data.
Most teams use Python's built-in `random.sample()` or `df.sample()` with a seed number. This looks random. It is not.
# This always picks the exact same rows — every single time
df.sample(n=200, random_state=42)
A seed means the computer always picks the exact same rows every time you run it. That means:
Whoever typed seed=42 quietly decided which data the AI learns from.
It can be replayed, challenged, or manipulated.
Your AI could be biased before it even sees a single row of training data.
Quantum randomness works differently. When a quantum circuit measures a qubit, the result is decided by physics alone and is not influenced by any code or human choice. Run it again and you will get a different result — because the outcome is never predetermined.
By using a quantum circuit to pick our training rows, we take human bias out of the equation from step one — before AutoAI trains a single model.
End to End Flow :
Services Required:
IBM Software Hub (on-premise CP4D)
Jupyter Notebook runtime
AutoAI service enabled
IBM Watson Studio
User Personas:
| Persona |
Role |
Steps |
| Platform Admin(cpadmin) |
IBM Software Hub administrator |
Part 1 — Steps 1.1 to 1.7 |
| Data Scientist |
Member of the Data Scientists group |
Part 2 — All notebook and AutoAI steps |
Part 1 — Access Management (Platform Admin)
Before any data science work begins, the platform admin sets up the right people with the right permissions. This takes under 10 minutes and ensures every team member can access the project with the correct role.
Step 1.1 — Log In as Admin
Log into your IBM Software Hub instance using your platform administrator account(cpadmin).
Step 1.2 — Navigate to Access Control
Pre requisite: Change the perspective to IBM Software hub via RHS experience selector.
- Click the hamburger menu (☰) in the top-left corner .
- Go to Administration → Access control .
3. Click the User groups tab .
Step 1.3 — Create the Data Scientists User Group
1. Click New user group .
2. Fill in the details:
- Name: `Data Scientists`.
- Description: `Team working on quantum-powered AutoAI experiments.
3. Click Next.
Step 1.4 — Add Users to the Group
1. In the Users step, search by name or email for each team member.
2. Select the users to add.
3. Click Add → then Next .
Step 1.5 — Assign Platform Roles to the Group
Assign the following roles to the `Data Scientists` group:
| Role |
Requirement |
| Data Scientist |
Allows running notebooks and AutoAI experiments |
| Data Engineer(optional) |
Allows uploading and managing datasets |
1. Select Data Scientist from the roles list
2. Click Next → Create
Step 1.5.1 — Verify Access as a Data Scientist
Log out of the admin account. Log back in as one of the Data Scientist group members ( here dsc1 is used) , choose Enterprise LDAP in login option and confirm:
- Platform role is active — New Project option is visible on the home screen.
- The Data Scientist can log in successfully.
Step 1.6 — Create the Project
- Navigate to All Projects in the left navigation panel.
2. Click New project.
3. Give the project a meaningful name:SWH-Quantum-AutoAI-POC and description .
- 4. Click Create.
Step 1.7 — Add the Data Scientists Group to the Project
1. Open the newly created project `SWH-Quantum-AutoAI-POC`
2. Click the Manage tab .
3. Select Access control .
4. Click Add collaborators.
5. Switch to the User groups tab .
6. Search for `Data Scientists` → select it.
7. Set the role to Editor.
8. Click Add.
Part 2 — Building the Quantum AutoAI Pipeline (Data Scientist)
Now logged in as a Data Scientist, we build the end-to-end quantum-sampled AutoAI pipeline inside the project.
Step 2.1 — Create a New Jupyter Notebook
Inside the project `SWH-Quantum-AutoAI-POC` click New Asset and select Jupyter Notebook .
Name your notebook: quantum_autoai_sampling.ipynb
For the runtime, select Python 3.11 with Spark or any Python 3.10+ environment available to you.
Click Create . Your notebook opens in a new tab.
Part 3 — Installing the Required Libraries
Cell 1 — Install packages
This runtime has a pre-installed pandas and numpy that can conflict with the numpy version Qiskit pulls in. We pin compatible versions to avoid a binary incompatibility error.
⚠️ Run this cell once only. After it completes — Kernel → Restart Kernel — then start from Cell 2.
# ============================================================
# CELL 1 — Install required packages
# Run ONCE only. After completion:
# Kernel → Restart Kernel
# Then run all cells from Cell 2 onwards.
# Do NOT re-run Cell 1 after restarting.
# ============================================================
import sys
!{sys.executable} -m pip install --quiet \
"qiskit==1.2.4" \
"qiskit-aer==0.15.1" \
"numpy==1.26.4" \
"pandas==2.1.4" \
"pylatexenc" \
--force-reinstall
print("✅ Packages installed successfully!")
print()
print("⚠️ Restart the kernel now:")
print(" Kernel → Restart Kernel")
print(" Then run all cells from Cell 2 downwards.")
After the ✅ appears — click Kernel → Restart Kernel before continuing.
Cell 2 — Import libraries
# pandas — for working with tables of data
import pandas as pd
# numpy — for numbers and maths
import numpy as np
# QuantumCircuit — the blueprint for our quantum experiment
from qiskit import QuantumCircuit
# AerSimulator — simulates a quantum computer (no hardware needed)
from qiskit_aer import AerSimulator
# matplotlib — for drawing charts
import matplotlib.pyplot as plt
import qiskit
print("✅ All libraries loaded!")
print(f" Qiskit version: {qiskit.__version__}")
Part 4 — Creating the Dataset
Cell 3 — Build a realistic customer dataset
In a real project you would load your own CSV. Here we create a realistic synthetic customer dataset so you can run this notebook without any external files.
# Fix the seed so the DATASET is always the same
# Only the SAMPLING will be quantum-random
np.random.seed(99)
TOTAL_CUSTOMERS = 1000
df = pd.DataFrame({
'customer_id': range(1, TOTAL_CUSTOMERS + 1),
'age': np.random.randint(18, 70, TOTAL_CUSTOMERS),
'monthly_bill': np.round(np.random.uniform(20, 200, TOTAL_CUSTOMERS), 2),
'contract_months': np.random.randint(1, 36, TOTAL_CUSTOMERS),
'support_calls': np.random.randint(0, 10, TOTAL_CUSTOMERS),
'gender': np.random.choice(['Male', 'Female'], TOTAL_CUSTOMERS),
'internet_service': np.random.choice(['Fiber', 'DSL', 'None'], TOTAL_CUSTOMERS),
# Churn = 1 means the customer left, 0 means they stayed
'Churn': np.random.choice([0, 1], TOTAL_CUSTOMERS, p=[0.73, 0.27])
})
print(f"✅ Dataset created!")
print(f" Total customers : {len(df)}")
print(f" Columns : {list(df.columns)}")
print(f" Churned (1) : {df['Churn'].sum()} ({df['Churn'].mean()*100:.1f}%)")
print(f" Stayed (0) : {(df['Churn']==0).sum()} ({(df['Churn']==0).mean()*100:.1f}%)")
print()
print("First 5 rows:")
df.head()
Part 5 — Classical Sampling (The Old Way)
Cell 4 — Show how classical sampling works
Before quantum, this is how most teams pick a training sample — using a seed number.
SAMPLE_SIZE = 200
# seed=42 means: ALWAYS pick the exact same 200 rows
classical_sample = df.sample(n=SAMPLE_SIZE, random_state=42)
classical_indices = sorted(classical_sample.index.tolist())
print("Classical Sampling Results:")
print(f" Method : df.sample() with random_state=42")
print(f" Sample size : {len(classical_sample)} rows")
print(f" First 10 row indices: {classical_indices[:10]}")
print()
print("⚠️ Run this cell again — you will always get the SAME indices.")
print(" This is pseudo-randomness — not true randomness.")
Notice the indices are always `[59, 76, 96, 101, 136...]` — every single run. That predictability is the problem.
Part 6 — Understanding the Quantum Circuit
What is a qubit?
A normal computer bit is either 0 or 1 — like a light switch, on or off.
A quantum bit (qubit) can be 0, 1, or both at the same time — this is called superposition .
The Hadamard gate (H gate) puts a qubit into superposition. When we measure it, it collapses to either 0 or 1 — decided by physics, not by code. Not reproducible. Not seed-based.
How we use this for sampling
1. We use 10 qubits — each put into superposition by the H gate
2. When all 10 are measured together, they produce a random 10-bit number (0 to 1023)
3. We use that number as a row index in our dataset
4. We repeat until we have 200 unique row indices
5. Those rows become our quantum-sampled training set
Cell 5 — Draw the quantum circuit
N_QUBITS = 10 # 2^10 = 1024 — covers all 1000 row indices
example_circuit = QuantumCircuit(N_QUBITS, N_QUBITS)
# H gate puts every qubit into superposition
example_circuit.h(range(N_QUBITS))
# Measure — collapses superposition to a truly random number
example_circuit.measure(range(N_QUBITS), range(N_QUBITS))
print("The Quantum Sampling Circuit:")
print("Each H box = Hadamard gate = superposition")
print("Meter symbol = measurement = collapses to a random value")
print()
# Print text version — works in all environments
print(example_circuit.draw(output='text', fold=80))
# Save image version to project
fig = example_circuit.draw(output='mpl', style={'name': 'bw'}, fold=20)
fig.savefig('quantum_circuit.png', dpi=150, bbox_inches='tight')
plt.close(fig)
# Display saved image
img = plt.imread('quantum_circuit.png')
fig2, ax = plt.subplots(figsize=(14, 4))
ax.imshow(img)
ax.axis('off')
ax.set_title('Quantum Random Number Generator — 10 qubits', fontsize=12, fontweight='bold')
plt.tight_layout()
plt.show()
print("Circuit saved as quantum_circuit.png")
Part 7 — Running the Quantum Sampling
Cell 6 — Generate 200 truly random row indices
def generate_quantum_sample(dataframe, sample_size):
"""
Select rows from a dataframe using quantum randomness.
Optimised for 4GB RAM:
- Builds the circuit ONCE and reuses it (saves memory)
- Runs in batches of 10 shots per call (faster, fewer calls)
- Each shot gives one truly random number from quantum measurement
"""
total_rows = len(dataframe)
n_qubits = int(np.ceil(np.log2(total_rows)))
BATCH_SIZE = 10
print(f"Starting quantum sampling...")
print(f" Dataset rows : {total_rows}")
print(f" Qubits used : {n_qubits} (covers 0 to {2**n_qubits - 1})")
print(f" Sample needed : {sample_size} rows")
print(f" Batch size : {BATCH_SIZE} per circuit run")
print()
simulator = AerSimulator()
selected_indices = set()
circuit_runs = 0
# Build the circuit ONCE — reuse it for every batch
qc = QuantumCircuit(n_qubits, n_qubits)
qc.h(range(n_qubits))
qc.measure(range(n_qubits), range(n_qubits))
while len(selected_indices) < sample_size:
# Run BATCH_SIZE shots — get BATCH_SIZE random numbers at once
job = simulator.run(qc, shots=BATCH_SIZE)
counts = job.result().get_counts()
circuit_runs += 1
for bitstring in counts.keys():
row_index = int(bitstring, 2)
if row_index < total_rows:
selected_indices.add(row_index)
if len(selected_indices) >= sample_size:
break
print(f" Progress: {min(len(selected_indices), sample_size)}/{sample_size} "
f"indices collected (circuit runs: {circuit_runs})")
final_indices = sorted(list(selected_indices))[:sample_size]
quantum_sample = dataframe.iloc[final_indices]
print()
print(f"✅ Quantum sampling complete!")
print(f" Rows selected : {len(final_indices)}")
print(f" Circuit runs used : {circuit_runs}")
print(f" True randomness : each index decided by quantum measurement")
return quantum_sample
quantum_sample = generate_quantum_sample(df, SAMPLE_SIZE)
Part 8 — Comparing Classical vs Quantum Samples
Cell 7 — Side-by-side comparison
A good sample should reflect the full dataset. If 27% of the full dataset churned, a good sample should also show roughly 27% churn.
TARGET = 'Churn'
full_rate = df[TARGET].mean() * 100
classical_rate = classical_sample[TARGET].mean() * 100
quantum_rate = quantum_sample[TARGET].mean() * 100
print("Churn Rate Comparison:")
print("=" * 45)
print(f" Full dataset : {full_rate:.1f}% ← target")
print(f" Classical sample : {classical_rate:.1f}%")
print(f" Quantum sample : {quantum_rate:.1f}%")
print()
print(f" Classical deviation : {abs(classical_rate - full_rate):.1f}%")
print(f" Quantum deviation : {abs(quantum_rate - full_rate):.1f}%")
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
datasets = [
('Full Dataset\n(1000 rows)', df, '#1976d2'),
('Classical Sample\n(seed=42)', classical_sample, '#ff9800'),
('Quantum Sample\n(no seed)', quantum_sample, '#4caf50'),
]
for ax, (title, data, color) in zip(axes, datasets):
counts = data[TARGET].value_counts().sort_index()
bars = ax.bar(['Stayed (0)', 'Churned (1)'], counts.values,
color=[color, '#e53935'], edgecolor='black', linewidth=0.8)
ax.set_title(title, fontsize=11, fontweight='bold', pad=10)
ax.set_ylabel('Customers', fontsize=10)
ax.set_ylim(0, max(counts.values) * 1.3)
total = counts.sum()
for bar, val in zip(bars, counts.values):
ax.text(bar.get_x() + bar.get_width()/2,
bar.get_height() + total * 0.01,
f'{val}\n({val/total*100:.1f}%)',
ha='center', fontsize=10, fontweight='bold')
plt.suptitle('Does Each Sample Reflect the Full Dataset Distribution?',
fontsize=13, fontweight='bold', y=1.02)
plt.tight_layout()
plt.savefig('sampling_comparison.png', dpi=150, bbox_inches='tight')
plt.show()
print("Chart saved as sampling_comparison.png")
Part 9 — Saving the Quantum Dataset to Your Project
Cell 8 — Save to IBM Software Hub project Assets
import io
import os
csv_buffer = io.StringIO()
quantum_sample.to_csv(csv_buffer, index=False)
output_file = 'quantum_sampled_dataset.csv'
try:
from project_lib import Project
project = Project(
project_id=os.environ.get('PROJECT_ID'),
project_access_token=os.environ.get('USER_ACCESS_TOKEN')
)
project.save_data(
file_name=output_file,
data=csv_buffer.getvalue(),
overwrite=True
)
print("✅ File saved to project Assets!")
print()
print(f" File : {output_file}")
print(f" Rows : {len(quantum_sample)}")
print(f" Columns : {list(quantum_sample.columns)}")
print()
print(" 📂 Find it here:")
print(" Project → Assets tab → Data assets")
print(f" → {output_file}")
except Exception as e:
quantum_sample.to_csv(output_file, index=False)
print(f"⚠️ Saved locally as fallback: {output_file}")
print(f" Error: {str(e)}")
Part 10 — Building the AutoAI Experiment
Now the quantum-sampled dataset is in your project. Here is how to build the AutoAI experiment on top of it.
Step 10.1 — Create a new AutoAI experiment
In your project click New Asset → AutoAI Experiment .
Name the experiment:"Quantum Churn Predictor"
Click Create .
Step 10.2 — Add the quantum-sampled dataset
Click Select from project and choose `quantum_sampled_dataset.csv`.
Step 10.3 — Configure prediction settings
AutoAI will auto-detect most settings. Confirm below:
| Setting |
Value |
| Prediction type |
Binary classification |
| Prediction Column |
`Churn` |
| Positive class |
`1` |
| Optimization metric |
ROC AUC |
Step 10.4 — Run the experiment
Click Run experiment .
AutoAI will now test multiple algorithms — LightGBM, XGBoost, Random Forest and others — applying automatic feature engineering to each. This takes approximately 5–10 minutes on a 4GB runtime.
Step 10.5 — Review the pipeline leaderboard
When complete, AutoAI shows a ranked leaderboard of pipelines:
Click Pipeline 5 to see feature importance, confusion matrix, and ROC curve.
Step 10.6 — Save the best pipeline as a model
Click Pipeline 5 → Save as model .
Name it:Quantum Churn Model v1 .
Part 11 — Deploying the Model and Testing Accuracy
With the model saved, the next step is to promote it to a deployment space, deploy it as an online endpoint, and send a test payload to confirm it is working and check prediction accuracy.
Step 11.1 — Promote the Model to a Deployment Space
- In the project, click the Assets tab .
- Find `Quantum Churn Model v1` under Models.
- Click the three-dot menu (⋮) → Promote to deployment space.
- In the dialog, select an existing deployment space or click New deployment space and create one named: swhquantumdeploy.
- Click Promote .
Step 11.2 — Open the Deployment Space
1. Click the hamburger menu (☰) → Deployments .
2. Click on `SWH-Quantum-Deploy`.
3. You will see `Quantum Churn Model v1` listed under Assets.
Step 11.3 — Deploy the Model as an Online Endpoint
- Click `Quantum Churn Model v1` → Deploy .
- Select Online as the deployment type .
- Name the deployment:Quantum Churn Predictor - Online.
- Click Create.
IBM Software Hub will provision the endpoint. This takes 1–3 minutes.
Step 11.4 — Test the Deployment with a Sample Payload
1. Click on Quantum Churn Predictor - Online .
2. Go to the Test tab.
3. Switch to JSON input and paste the following test record:
json
{
"input_data": [
{
"fields": [
"customer_id",
"age",
"monthly_bill",
"contract_months",
"support_calls",
"gender",
"internet_service"
],
"values": [
[1, 45, 95.5, 6, 5, "Male", "Fiber"]
]
}
]
}
4. Click Predict.
Step 11.5 — Review the Prediction Result
The response will return:
| Field |
Value |
Meaning |
| prediction |
'0' |
This customer is predicted to stay |
| probability[0] |
'0.817' |
Confidence the customer stays | |
| probability[1] |
'0.183' |
Confidence the customer churns |
For our test customer — a 45-year-old male on a Fiber plan, paying $95.50/month, on a 6-month contract with 5 support calls — the model predicts they will stay with 81.7% confidence . The prediction is decisive, not borderline, which suggests the quantum-sampled training data gave the model a clean, unbiased signal to learn from.
Conclusion
Quantum measurement is not an algorithm. It is a physical event. When a qubit in superposition is measured, its outcome is decided by quantum mechanics — not by a seed or by random number generator or by any reproducible process. That is what makes it genuinely different from classical randomness.
This entire workflow — user management, quantum notebook, dataset storage, AutoAI experiment — ran inside one IBM Software Hub instance. No separate quantum environment. No external tools. One platform, one login, end to end.
Most AI fairness discussions happen after training — at the bias evaluation stage. This approach moves the conversation earlier — to the data sampling stage. If the training data is unbiased from the start, the model has a cleaner foundation before any fairness mitigation even begins.
For regulated industries — financial services, healthcare, insurance — where model decisions must be auditable and defensible, this matters.
References
- IBM Qiskit Documentation: [docs.quantum.ibm.com](https://docs.quantum.ibm.com)
- IBM Quantum Learning: [learning.quantum.ibm.com](https://learning.quantum.ibm.com)
- IBM Software Hub: [ibm.com/products/software-hub](https://www.ibm.com/products/software-hub)
- Qiskit GitHub: [github.com/Qiskit/qiskit](https://github.com/Qiskit/qiskit)