from future import print_function
import os
os.environ['TF_USE_LEGACY_KERAS'] = '1'
from tensorflow.python.keras.layers import Dense, Activation
from tensorflow.python.keras import backend as K, Input
from tensorflow.python.keras.optimizer_v2.adam import Adam
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import roc_curve, auc
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.python.keras.models import Model
from importance_sampling.training import ConstantTimeImportanceTraining
from example_utils import get_parser
import pennylane as qml
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
def quantum_circuit(inputs, weights):
# 数据编码(角度编码)
for i in range(n_qubits):
qml.RY(inputs[i], wires=i)
# 变分层
qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits))
# 测量
return [qml.expval(qml.PauliZ(i)) for i in range(num_classes)] # 输出与类别数匹配
# 更新指标
self.model.compiled_metrics.update_state(y_test, y_pred)
metrics_results = [m.result().numpy() for m in self.model.metrics]
return loss_value.numpy(), metrics_results
def sampler(self, dataset, batch_size, steps_per_epoch, epochs):
return ConstantTimeSampler(
dataset,
self.reweighting,
self.model,
backward_pass_multiplier=self._backward_pass_multiplier,
extra_samples=self._extra_samples
)
class _BaseImportanceTraining(object):
def init(self, model, score="gnorm", layer=None):
"""Abstract base class for training a model using importance sampling.
Arguments
model: The Keras model to train
"""
Wrap and transform the model so that it outputs the importance scores
and can be used in an importance sampling training scheme
self._check_model(model)
self.original_model = model
self.model = OracleWrapper(
model,
self.reweighting,
score=score,
layer=layer
)
self.original_model.optimizer = self.model.optimizer
signal("is.sample").connect(self._on_sample)
signal("is.score").connect(self._on_scores)
def _on_sample(self, event):
self._latest_sample_event = event
def _on_scores(self, scores):
self._latest_scores = scores
def _check_model(self, model):
"""Check if the model uses Dropout and BatchNorm and warn that it may
affect the importance calculations."""
if any(
isinstance(l, (tf.keras.layers.BatchNormalization, Dropout))
for l in model.layers
):
sys.stderr.write(("[NOTICE]: You are using BatchNormalization "
"and/or Dropout.\nThose layers may affect the "
"importance calculations and you are advised "
"to exchange them for LayerNormalization or "
"BatchNormalization in test mode and L2 "
"regularization.\n"))
@property
def reweighting(self):
"""The reweighting policy that controls the bias of the estimation when
using importance sampling."""
raise NotImplementedError()
def sampler(self, dataset, batch_size, steps_per_epoch, epochs):
"""Create a new sampler to sample from the given dataset using
importance sampling."""
raise NotImplementedError()
def fit(self, x, y, batch_size=32, epochs=1, verbose=1, callbacks=None,
validation_split=0.0, validation_data=None, steps_per_epoch=None,
on_sample=None, on_scores=None):
"""Create an InMemoryDataset instance with the given data and train
the model using importance sampling for a given number of epochs.
Arguments
x: Numpy array of training data or list of numpy arrays
y: Numpy array of target data
batch_size: int, number of samples per gradient update
epochs: int, number of times to iterate over the entire
training set
verbose: {0, >0}, whether to employ the progress bar Keras
callback or not
callbacks: list of Keras callbacks to be called during training
validation_split: float in [0, 1), percentage of data to use for
evaluation
validation_data: tuple of numpy arrays, Data to evaluate the
trained model on without ever training on them
steps_per_epoch: int or None, number of gradient updates before
considering an epoch has passed
on_sample: callable that accepts the sampler, idxs, w, scores
on_scores: callable that accepts the sampler and scores
Returns
A Keras History object that contains information collected during
training.
"""
Create two data tuples from the given x, y, validation_*
if validation_data is not None:
x_train, y_train = x, y
x_test, y_test = validation_data
elif validation_split > 0:
assert validation_split < 1, "100% of the data used for testing"
n = int(round(validation_split * len(x)))
idxs = np.arange(len(x))
np.random.shuffle(idxs)
x_train, y_train = x[idxs[n:]], y[idxs[n:]]
x_test, y_test = x[idxs[:n]], y[idxs[:n]]
else:
x_train, y_train = x, y
x_test, y_test = np.empty(shape=(0, 1)), np.empty(shape=(0, 1))
Make the dataset to train on
dataset = InMemoryDataset(
x_train,
y_train,
x_test,
y_test,
categorical=False # this means use the targets as is
)
return self.fit_dataset(
dataset=dataset,
batch_size=batch_size,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
verbose=verbose,
callbacks=callbacks,
on_sample=on_sample,
on_scores=on_scores
)
def fit_generator(self, train, steps_per_epoch=None, batch_size=32,
epochs=1, verbose=1, callbacks=None,
validation_data=None, validation_steps=None,
on_sample=None, on_scores=None):
"""Create a GeneratorDataset instance and train the model using
importance sampling for a given number of epochs.
Arguments
train: A generator or iterable that returns tuples (inputs, targets)
steps_per_epoch: int, number of gradient updates before considering
an epoch has passed
batch_size: int, the number of samples per gradient update
epochs: int, multiplied by steps_per_epoch denotes the total number
of gradient updates
verbose: {0, >0}, whether to use the progress bar Keras callback
validation_data: generator, iterable or tuple (inputs, targets)
validation_steps: None or int, used only if validation_data is a
generator
on_sample: callable that accepts the sampler, idxs, w, scores
on_scores: callable that accepts the sampler and scores
"""
def infinite_iterator(iterable):
while True:
yield from iterable
创建验证数据集
if validation_data is not None:
if isinstance(validation_data, (tuple, list)):
test = validation_data
test_len = None
elif isinstance(validation_data, Iterable):
test = infinite_iterator(validation_data)
try:
test_len = len(validation_data) * batch_size
except TypeError:
test_len = validation_steps * batch_size if validation_steps else None
else:
test = validation_data
test_len = validation_steps * batch_size if validation_steps else None
else:
test = (np.empty(shape=(0, 1)), np.empty(shape=(0, 1)))
test_len = None
logging.info("No validation data provided")
设置训练数据和每个 epoch 的步数
if isinstance(train, Iterable):
if steps_per_epoch is None:
try:
steps_per_epoch = len(train)
except TypeError:
raise ValueError("steps_per_epoch must be set when using a generator without a len method")
train = infinite_iterator(train)
elif steps_per_epoch is None:
raise ValueError("steps_per_epoch is not set")
dataset = GeneratorDataset(train, test, test_len)
try:
print("dataset.train_data=", len(dataset.train_data))
except Exception as e:
print(f"Exception occurred: {e}")
return self.fit_dataset(
dataset=dataset,
batch_size=batch_size,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
verbose=verbose,
callbacks=callbacks,
on_sample=on_sample,
on_scores=on_scores
)
def fit_dataset(self, dataset, steps_per_epoch=None, batch_size=32,
epochs=1, verbose=1, callbacks=None, on_sample=None,
on_scores=None):
"""Train the model on the given dataset for a given number of epochs.
Arguments
dataset: Instance of BaseDataset that provides the data
to train on.
steps_per_epoch: int or None, number of gradient updates before
considering an epoch has passed. If None it is set
to be len(dataset.train_data) / batch_size.
batch_size: int, number of samples per gradient update
epochs: int, number of times to iterate steps_per_epoch times
verbose: {0, >0}, whether to employ the progress bar Keras
callback or not
callbacks: list of Keras callbacks to be called during training
on_sample: callable that accepts the sampler, idxs, w, scores
on_scores: callable that accepts the sampler and scores
"""
try:
if len(dataset.train_data) < batch_size:
raise ValueError(("The model cannot be trained with "
"batch_size > training set"))
except RuntimeError as e:
assert "no size" in str(e)
Set steps_per_epoch properly
if steps_per_epoch is None:
steps_per_epoch = len(dataset.train_data) // batch_size
Create the callbacks list
这段代码的目的是配置和初始化训练过程中将要使用的一组回调函数(callbacks)。
回调函数是在训练的不同阶段被自动调用的函数,用于执行特定的任务,如记录训练指标、
保存模型、早停(early stopping)等
self.history = History()
History是一个回调(Callback),用于在训练过程中记录各种指标(如损失、准确率等)的值
callbacks = [BaseLogger()] + (callbacks or []) + [self.history]
if verbose > 0:
idxs, (x, y), w = sampler.sample(batch_size) # 返回被采样的样本
Train on the sampled data
loss, metrics, scores = self.model.train_batch(x, y, w)
Update the sampler
sampler.update(idxs, scores)
values = map(lambda x: x.mean(), [loss] + metrics)
for l, o in zip(self.metrics_names, values):
batch_logs[l] = o
callbacks.on_batch_end(step, batch_logs)
if on_scores is not None and hasattr(self, "_latest_scores"):
on_scores(
sampler,
self._latest_scores
)
if on_sample is not None:
on_sample(
sampler,
self._latest_sample_event["idxs"],
self._latest_sample_event["w"],
self._latest_sample_event["predicted_scores"]
)
if self.original_model.stop_training:
break
Evaluate now that an epoch passed
epoch_logs = {}
if len(dataset.test_data) > 0:
val = self.model.evaluate(
*dataset.test_data[:],
batch_size=batch_size
)
epoch_logs = {
"val_" + l: o
for l, o in zip(self.metrics_names, val)
}
callbacks.on_epoch_end(epoch, epoch_logs)
if self.original_model.stop_training:
break
epoch += 1
callbacks.on_train_end()
return self.history
@property
def metrics_names(self):
def name(x):
if isinstance(x, str):
return x
if hasattr(x, "name"):
return x.name
if hasattr(x, "name"):
return x.name
return str(x)
metrics = self.original_model.metrics or []
return (
["loss"] +
[name(m) for m in metrics] +
["score"]
)
class _UnbiasedImportanceTraining(_BaseImportanceTraining):
def init(self, model, score="gnorm", layer=None):
self._reweighting = BiasedReweightingPolicy(1.0) # no bias
super(_UnbiasedImportanceTraining, self).init(model, score, layer)
@property
def reweighting(self):
return self._reweighting
class ImportanceTraining(_UnbiasedImportanceTraining):
"""Train a model with exact importance sampling.
Arguments
model: The Keras model to train
presample: float, the number of samples to presample for scoring
given as a factor of the batch size
tau_th: float or None, the variance reduction threshold after which we
enable importance sampling
forward_batch_size: int or None, the batch size to use for the forward
pass during scoring
score: {"gnorm", "loss", "full_gnorm"}, the importance metric to use
for importance sampling
layer: None or int or Layer, the layer to compute the gnorm with
# Call the parent to wrap the model
super(ImportanceTraining, self).__init__(model, score, layer)
def sampler(self, dataset, batch_size, steps_per_epoch, epochs):
# Configure the sampler
large_batch = int(self._presample * batch_size)
forward_batch_size = self._forward_batch_size or batch_size
# Compute the threshold using eq. 29 in
# https://arxiv.org/abs/1803.00942
B = large_batch
b = batch_size
tau_th = float(B + 3 * b) / (3 * b)
tau_th = self._tau_th if self._tau_th is not None else tau_th
class ConstantVarianceImportanceTraining(_UnbiasedImportanceTraining):
"""Train a model faster by keeping the per iteration variance constant but
decreasing the time.
Arguments
model: The Keras model to train
score: {"gnorm", "loss", "full_gnorm"}, the importance metric to use
for importance sampling
layer: None or int or Layer, the layer to compute the gnorm with
model: The Keras model to train
score: {"gnorm", "loss", "full_gnorm"}, the importance metric to use
for importance sampling
layer: None or int or Layer, the layer to compute the gnorm with
"""
def init(self, model, backward_time=2.0, score="gnorm", layer=None):
self._backward_time = backward_time
super(ConstantTimeImportanceTraining, self).init(
model,
score,
layer
)
def sampler(self, dataset, batch_size, steps_per_epoch, epochs):
return ConstantTimeSampler(
dataset,
self.reweighting,
self.model,
backward_time=self._backward_time
)
class BiasedImportanceTraining(_BaseImportanceTraining):
"""Train a model with exact importance sampling using the loss as
importance.
Arguments
model: The Keras model to train
k: float in (-oo, 1], controls the bias of the training that focuses
the network on the hard examples (see paper)
smooth: float, influences the sampling distribution towards uniform by
adding `smooth` to all probabilities and renormalizing
adaptive_smoothing: bool, If True the `smooth` argument is a percentage
of the average training loss
presample: int, the number of samples to presample for scoring
forward_batch_size: int, the batch size to use for the forward pass
during scoring
def sampler(self, dataset, batch_size, steps_per_epoch, epochs):
return self._sampler(dataset)
class ApproximateImportanceTraining(_BaseImportanceTraining):
"""Train a model with importance sampling using an LSTM with a class
embedding to predict the importance of the training samples.
Arguments
model: The Keras model to train
k: float in (-oo, 1], controls the bias of the training that focuses
the network on the hard examples (see paper)
smooth: float, influences the sampling distribution towards uniform by
adding `smooth` to all probabilities and renormalizing
adaptive_smoothing: bool, If True the `smooth` argument is a percentage
of the average training loss
presample: int, the number of samples to presample for scoring
def fit_generator(*args, **kwargs):
raise NotImplementedError("ApproximateImportanceTraining doesn't "
"support generator training")
上述是training.py文件
import sys
import numpy as np
from blinker import signal
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.layers import Layer, multiply
from tensorflow.python.keras import Model, Input
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):
yield [xi[s:s+bs] for xi in _tolist(x)], 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