from future import print_function
import pennylane as qml
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib.pyplot as plt
from tensorflow.python.keras.layers import Dense # 使用公共 API 导入
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
from sklearn.metrics import roc_curve, auc
上述是training.py文件
import numpy as np
from blinker import signal
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.layers import Layer
from tensorflow.python.keras.metrics import categorical_accuracy
import tensorflow as tf
from .layers import GradientNormLayer, LossLayer, MetricLayer
class ModelWrapper(object):
"""ModelWrapper 的目的是包装一个神经网络,并添加一些额外的层,以生成得分、损失和样本权重,以执行重要性采样。"""
def _iterate_batches(self, x, y, batch_size):
bs = batch_size
for s in range(0, len(y), bs):
if isinstance(x, (list, tuple)):
xs = [xi[s:s+bs] for xi in x]
else:
xs = x[s:s+bs]
yield xs, y[s:s+bs]
def evaluate(self, x, y, batch_size=128):
result = np.mean(
np.vstack([
self.evaluate_batch(xi, yi)
for xi, yi in self._iterate_batches(x, y, batch_size)
]),
axis=0
)
signal("is.evaluation").send(result)
return result
def score(self, x, y, batch_size=128):
bs = batch_size
result = np.hstack([
self.score_batch(xi, yi).T
for xi, yi in self._iterate_batches(x, y, batch_size)
]).T
signal("is.score").send(result)
return result
def set_lr(self, lr):
"""设置模型的学习率。"""
try:
K.set_value(
self.optimizer.lr,
lr
)
except AttributeError:
try:
K.set_value(
self.model.optimizer.lr,
lr
)
except AttributeError:
raise NotImplementedError()
try:
K.set_value(
self.small.optimizer.lr,
lr
)
except AttributeError:
pass
def evaluate_batch(self, x, y):
raise NotImplementedError()
def score_batch(self, x, y):
raise NotImplementedError()
def train_batch(self, x, y, w):
raise NotImplementedError()
class OracleWrapper(ModelWrapper):
AVG_LOSS = 0
LOSS = 1
WEIGHTED_LOSS = 2
SCORE = 3
METRIC0 = 4
def __getattribute__(self, name):
_getattr = object.__getattribute__
implemented_attributes = _getattr(self, "implemented_attributes")
if name in implemented_attributes:
return _getattr(self, name)
else:
model_wrapper = _getattr(self, "model_wrapper")
return getattr(model_wrapper, name)
上述是model_wrappers.py文件
from blinker import signal
from GAS.GAS_for_N_max import GroverOptimizer
def _get_dataset_length(dset, default=1):
"""Return the dataset's training data length and in case the dataset is
uncountable return a defalt value."""
try:
return len(dset.train_data)
except RuntimeError:
return default
class BaseSampler(object):
"""BaseSampler denotes the interface for all the samplers.
Samplers should provide the rest of the program with data points to train
on and corresponding relative weights."""
def __init__(self, dataset, reweighting):
self.dataset = dataset
self.reweighting = reweighting
def _slice_data(self, x, y, idxs):
if isinstance(x, (list, tuple)):
return [xi[idxs] for xi in x], y[idxs]
else:
return x[idxs], y[idxs]
def _send_messages(self, idxs, xy, w, predicted_scores):
signal("is.sample").send({
"idxs": idxs,
"xy": xy,
"w": w,
"predicted_scores": predicted_scores
})
def _get_samples_with_scores(self, batch_size):
"""Child classes should implement this method.
Arguments
---------
batch_size: int
Return at least that many samples
Return
------
idxs: array
The indices of some samples in the dataset
scores: array or None
The predicted importance scores for the corresponding idxs or
None for uniform sampling
xy: tuple or None
Optionally return the data for the corresponding idxs
"""
raise NotImplementedError()
def sample(self, batch_size):
# Get the importance scores of some samples
idxs1, scores, xy = self._get_samples_with_scores(batch_size)
# Sample from the available ones
if scores is not None:
# 使用 argsort 对 scores 进行降序排序,并取最大的 batch_size 个索引
idxs_sorted = np.argsort(scores)[::-1]
idxs2 = idxs_sorted[:batch_size]
else:
# 如果 scores 为空,随机选择 batch_size 个样本的索引
idxs2 = np.random.choice(len(idxs1), batch_size, p=None)
w = self.reweighting.sample_weights(idxs2, scores)
# Make sure we have the data
if xy is None:
xy = self.dataset.train_data[idxs1[idxs2]]
else:
x, y = xy
xy = self._slice_data(x, y, idxs2)
scores = scores[idxs2] if scores is not None else np.ones(batch_size)
self._send_messages(idxs1[idxs2], xy, w, scores)
return idxs1[idxs2], xy, w
'''
def sample(self, batch_size):
# Get the importance scores of some samples
idxs1, scores, xy = self._get_samples_with_scores(batch_size)
# Sample from the available ones
p = scores / scores.sum() if scores is not None else None
idxs2 = np.random.choice(len(idxs1), batch_size, p=p)
w = self.reweighting.sample_weights(idxs2, scores)
# Make sure we have the data
if xy is None:
xy = self.dataset.train_data[idxs1[idxs2]]
else:
x, y = xy
xy = self._slice_data(x, y, idxs2)
scores = scores[idxs2] if scores is not None else np.ones(batch_size)
self._send_messages(idxs1[idxs2], xy, w, scores)
return idxs1[idxs2], xy, w
'''
def update(self, idxs, results):
pass
import numpy as np
class ConstantTimeSampler(BaseSampler):
def init(self, dataset, reweighting, model, backward_time=2.0,
tau_th=0.9, ratio=0.5, min_a=0.2):
self.condition = VarianceReductionCondition(tau_th)
self.backward_time = backward_time
self.ratio = ratio
self.min_a = min_a
self.model = model
self.N = len(dataset.train_data) if hasattr(dataset, 'train_data') else _get_dataset_length(dataset, default=1)
print(f"Dataset size (self.N): {self.N}")
self.usage_counts = np.zeros(self.N, dtype=int)
super(ConstantTimeSampler, self).__init__(dataset, reweighting)
def sample(self, batch_size):
print(f"Entering sample method")
print(f"batch_size: {batch_size}, self.N: {self.N}")
print(f"Condition satisfied: {self.condition.satisfied}")
print(f"Requested batch_size: {batch_size}")
if batch_size > self.N:
batch_size = min(batch_size, self.N)
if self.condition.satisfied:
print("Entering satisfied condition block")
t = (1.0 + self.backward_time) * batch_size
a = 8
B = 32
idxs = np.random.choice(self.N, B, replace=False)
x, y = self.dataset.train_data[idxs]
z = 20
# 确保scores中没有0值
while (z != 0):
z = z-1
scores = self.model.score(x, y, batch_size=batch_size)
if not np.any(scores == 0):
break
zero_indices = np.where(scores == 0)[0]
new_idxs = np.random.choice(self.N, len(zero_indices), replace=False)
idxs[zero_indices] = new_idxs
x[zero_indices], y[zero_indices] = self.dataset.train_data[new_idxs]
print(f"Length of scores before processing: {len(scores)}")
# 确保 scores 的长度为B
if len(scores) > B:
scores = scores[:B]
elif len(scores) < B:
scores = np.pad(scores, (0, B - len(scores)), 'constant')
# 保存原始scores
original_scores = scores.copy()
# # 鸢尾花、wine、乳腺癌等数据集对scores进行处理
# scores = np.ceil(scores * 5)
# scores[scores > 7] = 7
# sonar数据集对scores进行处理
scores = np.ceil(scores * 2)
scores[scores > 7] = 7
print(f"Length of scores after processing: {len(scores)}")
print(f"a: {a}, B: {B}")
# 添加检查
if np.any(np.isnan(scores)):
print("警告:数值scores存在nan,回退为随机采样")
print("scores:", scores)
return self._random_sample(batch_size)
if np.any(np.isinf(scores)):
print("警告:数值scores存在无穷,回退为随机采样")
print("scores:", scores)
return self._random_sample(batch_size)
N_Q = int(a)
num_value_qubits = 4
num_key_qubits = 5
num_iterations = 3
optimizer = GroverOptimizer(num_value_qubits, num_key_qubits, num_iterations=num_iterations)
result = optimizer.solve(scores, N_Q)
idxs2 = np.array(result.keys)
print(f"result.keys", result.keys)
print(f"Length of top_a_idxs: {len(idxs2)}")
print(f"Max value in top_a_idxs: {idxs2.max() if len(idxs2) > 0 else 'N/A'}")
if len(idxs2) == 0:
print("Warning: top_a_idxs is empty after filtering. Falling back to random sampling.")
return self._random_sample(batch_size)
w = self.reweighting.sample_weights(idxs2, scores)
x, y = self._slice_data(x, y, idxs2)
self.condition.update(scores)
else:
idxs = np.random.choice(self.N, batch_size)
idxs2 = np.arange(len(idxs))
x, y = self.dataset.train_data[idxs]
scores = np.ones(len(idxs))
w = np.ones((len(idxs), self.reweighting.weight_size))
self._send_messages(idxs[idxs2], (x, y), w, scores[idxs2])
print(f"Returned batch shapes: x: {x.shape}, y: {y.shape}, w: {w.shape}")
return (idxs[idxs2], (x, y), w)
def update(self, idxs, scores):
if not self.condition.previously_satisfied:
self.condition.update(scores)
def _random_sample(self, batch_size):
# 实现随机采样作为后备策略
random_indices = np.random.choice(self.N, size=batch_size, replace=False)
x, y = self.dataset.train_data[random_indices]
w = np.ones((batch_size, self.reweighting.weight_size))
return random_indices, (x, y), w