code
stringlengths
17
6.64M
def Conv2D(filters, kernel_size, padding='same', activation='relu'): return layers.Conv2D(filters, kernel_size, padding=padding, activation=activation)
class AE(models.Model): def __init__(self, org_shape=(1, 28, 28)): original = layers.Input(shape=org_shape) x = Conv2D(4, (3, 3))(original) x = layers.MaxPooling2D((2, 2), padding='same')(x) x = Conv2D(8, (3, 3))(x) x = layers.MaxPooling2D((2, 2), padding='same')(x) ...
class DATA(): def __init__(self): num_classes = 10 ((x_train, y_train), (x_test, y_test)) = datasets.mnist.load_data() (img_rows, img_cols) = x_train.shape[1:] if (backend.image_data_format() == 'channels_first'): x_train = x_train.reshape(x_train.shape[0], 1, img_rows...
def plot_loss(history): plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show()
class ANN(models.Model): def __init__(self, Nin, Nh, Nout): hidden = layers.Dense(Nh) output = layers.Dense(Nout) relu = layers.Activation('relu') x = layers.Input(shape=(Nin,)) h = relu(hidden(x)) y = output(h) super().__init__(x, y) self.compile(l...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.boston_housing.load_data() scaler = preprocessing.MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) return ((X_train, y_train), (X_test, y_test))
def main(): Nin = 13 Nh = 5 Nout = 1 model = ANN(Nin, Nh, Nout) ((X_train, y_train), (X_test, y_test)) = Data_func() history = model.fit(X_train, y_train, epochs=100, batch_size=100, validation_split=0.2, verbose=2) performace_test = model.evaluate(X_test, y_test, batch_size=100) print...
def ANN_models_func(Nin, Nh, Nout): x = layers.Input(shape=(Nin,)) h = layers.Activation('relu')(layers.Dense(Nh)(x)) y = layers.Activation('softmax')(layers.Dense(Nout)(h)) model = models.Model(x, y) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return...
def ANN_seq_func(Nin, Nh, Nout): model = models.Sequential() model.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) model.add(layers.Dense(Nout, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
class ANN_models_class(models.Model): def __init__(self, Nin, Nh, Nout): hidden = layers.Dense(Nh) output = layers.Dense(Nout) relu = layers.Activation('relu') softmax = layers.Activation('softmax') x = layers.Input(shape=(Nin,)) h = relu(hidden(x)) y = sof...
class ANN_seq_class(models.Sequential): def __init__(self, Nin, Nh, Nout): super().__init__() self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) self.add(layers.Dense(Nout, activation='softmax')) self.compile(loss='categorical_crossentropy', optimizer='adam', metric...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data() Y_train = np_utils.to_categorical(y_train) Y_test = np_utils.to_categorical(y_test) (L, W, H) = X_train.shape X_train = X_train.reshape((- 1), (W * H)) X_test = X_test.reshape((- 1), (W * H)) X_train = (X_...
def plot_loss(history): plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc=0)
def plot_acc(history): plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc=0)
def main(): Nin = 784 Nh = 100 number_of_class = 10 Nout = number_of_class model = ANN_seq_class(Nin, Nh, Nout) ((X_train, Y_train), (X_test, Y_test)) = Data_func() history = model.fit(X_train, Y_train, epochs=15, batch_size=100, validation_split=0.2) performace_test = model.evaluate(X...
def plot_acc(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['accuracy']) plt.plot(history['val_accuracy']) if (title is not None): plt.title(title) plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Training', 'Veri...
def plot_loss(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['loss']) plt.plot(history['val_loss']) if (title is not None): plt.title(title) plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Training', 'Verification'],...
class History(): def __init__(self): self.history = {'accuracy': [], 'loss': [], 'val_accuracy': [], 'val_loss': []}
class Metrics_Mean(): def __init__(self): self.reset_states() def __call__(self, loss): self.buff.append(loss.data) def reset_states(self): self.buff = [] def result(self): return np.mean(self.buff)
class Metrics_CategoricalAccuracy(): def __init__(self): self.reset_states() def __call__(self, labels, predictions): decisions = predictions.data.max(1)[1] self.correct += decisions.eq(labels.data).cpu().sum() self.L += len(labels.data) def reset_states(self): (...
class ANN_models_class(nn.Module): def __init__(self, Nin, Nh, Nout): super().__init__() self.hidden = nn.Linear(Nin, Nh) self.last = nn.Linear(Nh, Nout) self.Nin = Nin def forward(self, x): x = x.view((- 1), self.Nin) h = F.relu(self.hidden(x)) y = F....
def Data_func(): train_dataset = datasets.MNIST('~/pytorch_data', train=True, download=True, transform=transforms.ToTensor()) test_dataset = datasets.MNIST('~/pytorch_data', train=False, transform=transforms.ToTensor()) train_ds = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, s...
def ANN_models_func(Nin, Nh, Nout): x = layers.Input(shape=(Nin,)) h = layers.Activation('relu')(layers.Dense(Nh)(x)) y = layers.Activation('softmax')(layers.Dense(Nout)(h)) model = models.Model(x, y) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return...
def ANN_seq_func(Nin, Nh, Nout): model = models.Sequential() model.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) model.add(layers.Dense(Nout, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
class ANN_models_class(models.Model): def __init__(self, Nin, Nh, Nout): hidden = layers.Dense(Nh) output = layers.Dense(Nout) relu = layers.Activation('relu') softmax = layers.Activation('softmax') x = layers.Input(shape=(Nin,)) h = relu(hidden(x)) y = sof...
class ANN_seq_class(models.Sequential): def __init__(self, Nin, Nh, Nout): super().__init__() self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) self.add(layers.Dense(Nout, activation='softmax')) self.compile(loss='categorical_crossentropy', optimizer='adam', metric...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data() Y_train = utils.to_categorical(y_train) Y_test = utils.to_categorical(y_test) (L, W, H) = X_train.shape X_train = X_train.reshape((- 1), (W * H)) X_test = X_test.reshape((- 1), (W * H)) X_train = (X_train ...
def plot_acc(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['acc']) plt.plot(history['val_acc']) if (title is not None): plt.title(title) plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Training', 'Verification']...
def plot_loss(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['loss']) plt.plot(history['val_loss']) if (title is not None): plt.title(title) plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Training', 'Verification'],...
def main(): Nin = 784 Nh = 100 number_of_class = 10 Nout = number_of_class model = ANN_seq_class(Nin, Nh, Nout) ((X_train, Y_train), (X_test, Y_test)) = Data_func() history = model.fit(X_train, Y_train, epochs=15, batch_size=100, validation_split=0.2) performace_test = model.evaluate(X...
def ANN_models_func(Nin, Nh, Nout): x = layers.Input(shape=(Nin,)) h = layers.Activation('relu')(layers.Dense(Nh)(x)) y = layers.Activation('softmax')(layers.Dense(Nout)(h)) model = models.Model(x, y) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return...
def ANN_seq_func(Nin, Nh, Nout): model = models.Sequential() model.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) model.add(layers.Dense(Nout, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model
class ANN_models_class(models.Model): def __init__(self, Nin, Nh, Nout): hidden = layers.Dense(Nh) output = layers.Dense(Nout) relu = layers.Activation('relu') softmax = layers.Activation('softmax') x = layers.Input(shape=(Nin,)) h = relu(hidden(x)) y = sof...
class ANN_seq_class(models.Sequential): def __init__(self, Nin, Nh, Nout): super().__init__() self.add(layers.Dense(Nh, activation='relu', input_shape=(Nin,))) self.add(layers.Dense(Nout, activation='softmax')) self.compile(loss='categorical_crossentropy', optimizer='adam', metric...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data() Y_train = utils.to_categorical(y_train) Y_test = utils.to_categorical(y_test) (L, W, H) = X_train.shape X_train = X_train.reshape((- 1), (W * H)) X_test = X_test.reshape((- 1), (W * H)) X_train = (X_train ...
def plot_acc(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['accuracy']) plt.plot(history['val_accuracy']) if (title is not None): plt.title(title) plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Training', 'Veri...
def plot_loss(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['loss']) plt.plot(history['val_loss']) if (title is not None): plt.title(title) plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Training', 'Verification'],...
class ANN_models_class(models.Model): def __init__(self, Nin, Nh, Nout): super().__init__() self.hidden = layers.Dense(Nh) self.last = layers.Dense(Nout) def call(self, x): relu = layers.Activation('relu') softmax = layers.Activation('softmax') h = relu(self.h...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.mnist.load_data() Y_train = utils.to_categorical(y_train) Y_test = utils.to_categorical(y_test) (L, W, H) = X_train.shape X_train = X_train.reshape((- 1), (W * H)) X_test = X_test.reshape((- 1), (W * H)) X_train = (X_train ...
def plot_acc(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['accuracy']) plt.plot(history['val_accuracy']) if (title is not None): plt.title(title) plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Training', 'Veri...
def plot_loss(history, title=None): if (not isinstance(history, dict)): history = history.history plt.plot(history['loss']) plt.plot(history['val_loss']) if (title is not None): plt.title(title) plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Training', 'Verification'],...
class History(): def __init__(self): self.history = {'accuracy': [], 'loss': [], 'val_accuracy': [], 'val_loss': []}
class _ANN_models_class(models.Model): def __init__(self, Nin, Nh, Nout): hidden = layers.Dense(Nh) output = layers.Dense(Nout) relu = layers.Activation('relu') softmax = layers.Activation('softmax') x = layers.Input(shape=(Nin,)) h = relu(hidden(x)) y = so...
@tf2.function def ep_train(xx, yy): with tf2.GradientTape() as tape: yp = model(xx) loss = Loss_object(yy, yp) gradients = tape.gradient(loss, model.trainable_variables) Optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss(loss) train_accuracy(yy, yp)
@tf2.function def ep_test(xx, yy): yp = model(xx) t_loss = Loss_object(yy, yp) test_loss(t_loss) test_accuracy(yy, yp)
class MyModel(Model): def __init__(self): super(MyModel, self).__init__() self.conv1 = Conv2D(32, 3, activation='relu') self.flatten = Flatten() self.d1 = Dense(128, activation='relu') self.d2 = Dense(10, activation='softmax') def call(self, x): x = self.conv1...
@tf.function def train_step(images, labels): with tf.GradientTape() as tape: predictions = model(images) loss = loss_object(labels, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss(lo...
@tf.function def test_step(images, labels): predictions = model(images) t_loss = loss_object(labels, predictions) test_loss(t_loss) test_accuracy(labels, predictions)
def fixed_point(x, k, fraclength=None, signed=True): if (fraclength != None): f = fraclength n = float((2.0 ** f)) mn = (- (2.0 ** ((k - f) - 1))) mx = ((- mn) - (2.0 ** (- f))) if (not signed): mx -= mn mn = 0 x = tf.clip_by_value(x, mn, mx)...
def quantize(x, bit_width, frac_bits=None, signed=None): if (bit_width is None): return x elif (bit_width == 1): return (x + tf.stop_gradient((tf.sign(x) - x))) elif (bit_width == 2): ones = tf.ones_like(x) zeros = (ones * 0) mask = tf.where((x < 0.33), zeros, ones)...
class SYQ(Conv2D): def __init__(self, bit_width, *args, **kwargs): self.bit_width = bit_width super(SYQ, self).__init__(*args, **kwargs) def get_config(self): config = super().get_config() config['bit_width'] = self.bit_width return config def build(self, input_s...
class SYQ_Dense(Dense): def __init__(self, bit_width, *args, **kwargs): self.bit_width = bit_width super(SYQ_Dense, self).__init__(*args, **kwargs) def get_config(self): config = super().get_config() config['bit_width'] = self.bit_width return config def build(se...
class Model(): def __init__(self, bit_width=None, model_name=None, load=None): self.bit_width = bit_width self.load = load self.model_name = model_name self.model = keras.Sequential([SYQ(self.bit_width, 32, (3, 3), activation='relu', input_shape=(28, 28, 1)), SYQ(self.bit_width, 3...
def skip(app, what, name, obj, skip, options): if (name == '__init__'): return False return skip
def process_signature(app, what, name, obj, options, signature, return_annotation): if signature: signature = re.sub("<Mock name='([^']+)'.*>", '\\g<1>', signature) signature = re.sub('tensorflow', 'tf', signature) return (signature, return_annotation)
def setup(app): from recommonmark.transform import AutoStructify app.connect('autodoc-process-signature', process_signature) app.connect('autodoc-skip-member', skip) app.add_config_value('recommonmark_config', {'url_resolver': (lambda url: ('https://github.com/ppwwyyxx/tensorpack/blob/master/tensorpac...
def get_args(): description = 'plot points into graph.' parser = argparse.ArgumentParser(description=description) parser.add_argument('-i', '--input', help='input data file, use "-" for stdin. Default stdin. Input format is many rows of DELIMIETER-separated data', default='-') parser.add_a...
def filter_valid_range(points, rect): 'rect = (min_x, max_x, min_y, max_y)' ret = [] for (x, y) in points: if ((x >= rect[0]) and (x <= rect[1]) and (y >= rect[2]) and (y <= rect[3])): ret.append((x, y)) if (len(ret) == 0): ret.append(points[0]) return ret
def exponential_smooth(data, alpha): ' smooth data by alpha. returned a smoothed version' ret = np.copy(data) now = data[0] for k in range(len(data)): ret[k] = ((now * alpha) + (data[k] * (1 - alpha))) now = ret[k] return ret
def annotate_min_max(data_x, data_y, ax): (max_x, min_x) = (max(data_x), min(data_x)) (max_y, min_y) = (max(data_y), min(data_y)) x_range = (max_x - min_x) y_range = (max_y - min_y) (x_max, y_max) = (data_y[0], data_y[0]) (x_min, y_min) = (data_x[0], data_y[0]) for i in range(1, len(data_x...
def plot_args_from_column_desc(desc): if (not desc): return {} ret = {} desc = desc.split(';') if ('thick' in desc): ret['lw'] = 5 if ('dash' in desc): ret['ls'] = '--' for v in desc: if v.startswith('c'): ret['color'] = v[1:] return ret
def do_plot(data_xs, data_ys): '\n data_xs: list of 1d array, either of size 1 or size len(data_ys)\n data_ys: list of 1d array\n ' fig = plt.figure(figsize=((16.18 / 1.2), (10 / 1.2))) ax = fig.add_axes((0.1, 0.2, 0.8, 0.7)) nr_y = len(data_ys) y_column = args.y_column if args.legend...
def main(): get_args() if (args.input == STDIN_FNAME): fin = sys.stdin else: fin = open(args.input) all_inputs = fin.readlines() if (args.input != STDIN_FNAME): fin.close() nr_column = len(all_inputs[0].rstrip('\n').split(args.delimeter)) if (args.column is None): ...
def _global_import(name): p = __import__(name, globals(), locals(), level=1) lst = (p.__all__ if ('__all__' in dir(p)) else dir(p)) del globals()[name] for k in lst: globals()[k] = p.__dict__[k]
class PreventStuckPlayer(ProxyPlayer): " Prevent the player from getting stuck (repeating a no-op)\n by inserting a different action. Useful in games such as Atari Breakout\n where the agent needs to press the 'start' button to start playing.\n " def __init__(self, player, nr_repeat, action): ...
class LimitLengthPlayer(ProxyPlayer): ' Limit the total number of actions in an episode.\n Will auto restart the underlying player on timeout\n ' def __init__(self, player, limit): super(LimitLengthPlayer, self).__init__(player) self.limit = limit self.cnt = 0 def actio...
class AutoRestartPlayer(ProxyPlayer): " Auto-restart the player on episode ends,\n in case some player wasn't designed to do so. " def action(self, act): (r, isOver) = self.player.action(act) if isOver: self.player.finish_episode() self.player.restart_episode() ...
class MapPlayerState(ProxyPlayer): def __init__(self, player, func): super(MapPlayerState, self).__init__(player) self.func = func def current_state(self): return self.func(self.player.current_state())
@six.add_metaclass(ABCMeta) class RLEnvironment(object): def __init__(self): self.reset_stat() @abstractmethod def current_state(self): '\n Observe, return a state representation\n ' @abstractmethod def action(self, act): '\n Perform an action. Will ...
class ActionSpace(object): def __init__(self): self.rng = get_rng(self) @abstractmethod def sample(self): pass def num_actions(self): raise NotImplementedError()
class DiscreteActionSpace(ActionSpace): def __init__(self, num): super(DiscreteActionSpace, self).__init__() self.num = num def sample(self): return self.rng.randint(self.num) def num_actions(self): return self.num def __repr__(self): return 'DiscreteActionS...
class NaiveRLEnvironment(RLEnvironment): ' for testing only' def __init__(self): self.k = 0 def current_state(self): self.k += 1 return self.k def action(self, act): self.k = act return (self.k, (self.k > 10))
class ProxyPlayer(RLEnvironment): ' Serve as a proxy another player ' def __init__(self, player): self.player = player def reset_stat(self): self.player.reset_stat() def current_state(self): return self.player.current_state() def action(self, act): return self.p...
class GymEnv(RLEnvironment): '\n An OpenAI/gym wrapper. Can optionally auto restart.\n Only support discrete action space now\n ' def __init__(self, name, dumpdir=None, viz=False, auto_restart=True): with _ENV_LOCK: self.gymenv = gym.make(name) if dumpdir: mkd...
class HistoryFramePlayer(ProxyPlayer): ' Include history frames in state, or use black images\n Assume player will do auto-restart.\n ' def __init__(self, player, hist_len): '\n :param hist_len: total length of the state, including the current\n and `hist_len-1` history\n ...
class TransitionExperience(object): ' A transition of state, or experience' def __init__(self, state, action, reward, **kwargs): ' kwargs: whatever other attribute you want to save' self.state = state self.action = action self.reward = reward for (k, v) in six.iteritem...
@six.add_metaclass(ABCMeta) class SimulatorProcessBase(mp.Process): def __init__(self, idx): super(SimulatorProcessBase, self).__init__() self.idx = int(idx) self.name = u'simulator-{}'.format(self.idx) self.identity = self.name.encode('utf-8') @abstractmethod def _build_...
class SimulatorProcessStateExchange(SimulatorProcessBase): '\n A process that simulates a player and communicates to master to\n send states and receive the next action\n ' def __init__(self, idx, pipe_c2s, pipe_s2c): '\n :param idx: idx of this process\n ' super(Simula...
class SimulatorMaster(threading.Thread): ' A base thread to communicate with all StateExchangeSimulatorProcess.\n It should produce action for each simulator, as well as\n defining callbacks when a transition or an episode is finished.\n ' class ClientState(object): def __init__(sel...
class SimulatorProcessDF(SimulatorProcessBase): ' A simulator which contains a forward model itself, allowing\n it to produce data points directly ' def __init__(self, idx, pipe_c2s): super(SimulatorProcessDF, self).__init__(idx) self.pipe_c2s = pipe_c2s def run(self): self.pl...
class SimulatorProcessSharedWeight(SimulatorProcessDF): ' A simulator process with an extra thread waiting for event,\n and take shared weight from shm.\n\n Start me under some CUDA_VISIBLE_DEVICES set!\n ' def __init__(self, idx, pipe_c2s, condvar, shared_dic, pred_config): super(SimulatorP...
class WeightSync(Callback): ' Sync weight from main process to shared_dic and notify' def __init__(self, condvar, shared_dic): self.condvar = condvar self.shared_dic = shared_dic def _setup_graph(self): self.vars = self._params_to_update() def _params_to_update(self): ...
def _global_import(name): p = __import__(name, globals(), locals(), level=1) lst = (p.__all__ if ('__all__' in dir(p)) else dir(p)) del globals()[name] for k in lst: globals()[k] = p.__dict__[k] __all__.append(k)
@six.add_metaclass(ABCMeta) class Callback(object): ' Base class for all callbacks ' def before_train(self): '\n Called right before the first iteration.\n ' self._before_train() def _before_train(self): pass def setup_graph(self, trainer): '\n C...
class ProxyCallback(Callback): def __init__(self, cb): self.cb = cb def _before_train(self): self.cb.before_train() def _setup_graph(self): self.cb.setup_graph(self.trainer) def _after_train(self): self.cb.after_train() def _trigger_epoch(self): self.cb...
class PeriodicCallback(ProxyCallback): "\n A callback to be triggered after every `period` epochs.\n Doesn't work for trigger_step\n " def __init__(self, cb, period): '\n :param cb: a `Callback`\n :param period: int\n ' super(PeriodicCallback, self).__init__(cb) ...
class StartProcOrThread(Callback): def __init__(self, procs_threads): '\n Start extra threads and processes before training\n :param procs_threads: list of processes or threads\n ' if (not isinstance(procs_threads, list)): procs_threads = [procs_threads] s...
class OutputTensorDispatcer(object): def __init__(self): self._names = [] self._idxs = [] def add_entry(self, names): v = [] for n in names: tensorname = get_op_tensor_name(n)[1] if (tensorname in self._names): v.append(self._names.inde...
class DumpParamAsImage(Callback): '\n Dump a variable to image(s) after every epoch to logger.LOG_DIR.\n ' def __init__(self, var_name, prefix=None, map_func=None, scale=255, clip=False): '\n :param var_name: the name of the variable.\n :param prefix: the filename prefix for saved...
class RunOp(Callback): ' Run an op periodically' def __init__(self, setup_func, run_before=True, run_epoch=True): '\n :param setup_func: a function that returns the op in the graph\n :param run_before: run the op before training\n :param run_epoch: run the op on every epoch trigg...
class CallbackTimeLogger(object): def __init__(self): self.times = [] self.tot = 0 def add(self, name, time): self.tot += time self.times.append((name, time)) @contextmanager def timed_callback(self, name): s = time.time() (yield) self.add(nam...
class Callbacks(Callback): '\n A container to hold all callbacks, and execute them in the right order and proper session.\n ' def __init__(self, cbs): '\n :param cbs: a list of `Callbacks`\n ' for cb in cbs: assert isinstance(cb, Callback), cb.__class__ ...
@six.add_metaclass(ABCMeta) class Inferencer(object): def before_inference(self): '\n Called before a new round of inference starts.\n ' self._before_inference() def _before_inference(self): pass def datapoint(self, output): '\n Called after complete...
class ScalarStats(Inferencer): '\n Write some scalar tensor to both stat and summary.\n The output of the given Ops must be a scalar.\n The value will be averaged over all data points in the inference dataflow.\n ' def __init__(self, names_to_print, prefix='validation'): '\n :param...
class ClassificationError(Inferencer): '\n Compute classification error in batch mode, from a `wrong` variable\n\n The `wrong` tensor is supposed to be an 0/1 integer vector containing\n whether each sample in the batch is incorrectly classified.\n You can use `tf.nn.in_top_k` to produce this vector r...
class BinaryClassificationStats(Inferencer): ' Compute precision/recall in binary classification, given the\n prediction vector and the label vector.\n ' def __init__(self, pred_var_name, label_var_name, summary_prefix='val'): '\n :param pred_var_name: name of the 0/1 prediction tensor.\...
def summary_inferencer(trainer, infs): for inf in infs: ret = inf.after_inference() for (k, v) in six.iteritems(ret): try: v = float(v) except: logger.warn('{} returns a non-scalar statistics!'.format(type(inf).__name__)) cont...
class InferenceRunner(Callback): '\n A callback that runs different kinds of inferencer.\n ' IOTensor = namedtuple('IOTensor', ['index', 'isOutput']) def __init__(self, ds, infs, inf_epochs, input_tensors=None): '\n :param ds: inference dataset. a `DataFlow` instance.\n :param...
class FeedfreeInferenceRunner(Callback): IOTensor = namedtuple('IOTensor', ['index', 'isOutput']) def __init__(self, input, infs, input_tensors=None): assert isinstance(input, FeedfreeInput), input self._input_data = input if (not isinstance(infs, list)): self.infs = [infs...
@six.add_metaclass(ABCMeta) class HyperParam(object): ' Base class for a hyper param' def setup_graph(self): ' setup the graph in `setup_graph` callback stage, if necessary' pass @abstractmethod def set_value(self, v): ' define how the value of the param will be set' ...