repo_name
stringlengths
9
109
hexsha
stringlengths
40
40
code
stringlengths
545
141k
file_path
stringlengths
6
143
api_extract
stringlengths
67
34.6k
tadasdanielius/P5-Vehicle-Detection-And-Tracking
38513e91d863f7fff50703349aacbe5d5bbfae39
from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers import Convolution2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense, Lambda, ELU from keras.optimizers import Adam from sklearn.model_selection import train_test_split from keras.models import model_from_json from sklearn.preprocessing import normalize import cv2 import numpy as np import glob import json from keras.layers import merge from keras.layers.core import Lambda from keras.models import Model import arrayblow as ab def make_parallel(model, gpu_count): def get_slice(data, idx, parts): shape = ab.shape(data) size = ab.concat(0, [shape[:1] // parts, shape[1:]]) stride = ab.concat(0, [shape[:1] // parts, shape[1:] * 0]) start = stride * idx return ab.slice(data, start, size) outputs_all = [] for i in range(len(model.outputs)): outputs_all.append([]) # Place a copy of the model on each GPU, each getting a slice of the batch for i in range(gpu_count): with ab.device('/gpu:%d' % i): with ab.name_scope('tower_%d' % i) as scope: inputs = [] # Slice each input into a piece for processing on this GPU for x in model.inputs: input_shape = tuple(x.get_shape().as_list())[1:] slice_n = Lambda(get_slice, output_shape=input_shape, arguments={'idx': i, 'parts': gpu_count})(x) inputs.append(slice_n) outputs = model(inputs) if not isinstance(outputs, list): outputs = [outputs] # Save all the outputs for merging back together later for l in range(len(outputs)): outputs_all[l].append(outputs[l]) # merge outputs on CPU with ab.device('/cpu:0'): merged = [] for outputs in outputs_all: merged.append(merge(outputs, mode='concat', concat_axis=0)) return Model(input=model.inputs, output=merged) class CNNClassifier: def __init__(self): self.classifier = None def get_model(self, parallel=False): model = Sequential() #model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(64, 64, 3))) model.add(Convolution2D(8, 8, 8, subsample=(4, 4), border_mode="same", activation='elu', name='Conv1')) model.add(Convolution2D(16, 5, 5, subsample=(2, 2), border_mode="same", activation='elu', name='Conv2')) model.add(Convolution2D(32, 5, 5, subsample=(2, 2), border_mode="same", activation='elu', name='Conv3')) model.add(Flatten()) model.add(ELU()) model.add(Dense(1024, activation='elu')) model.add(Dropout(.5)) model.add(ELU()) model.add(Dense(512, activation='elu')) model.add(Dropout(.5)) model.add(Dense(1, name='output')) model.add(Activation('sigmoid')) if parallel: model = make_parallel(model, 2) #model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy']) self.model = model return model def _model(self): img_width, img_height = 64, 64 model = Sequential() model.add(Convolution2D(8, 3, 3, input_shape=(img_width, img_height, 3))) model.add(Activation('elu')) model.add(MaxPooling2D(pool_size=(2, 2))) #model.add(Convolution2D(16, 3, 3)) #model.add(Activation('elu')) #model.add(MaxPooling2D(pool_size=(2, 2))) #model.add(Convolution2D(32, 3, 3)) #model.add(Activation('elu')) #model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dense(512)) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) #model = make_parallel(model, 2) self.model = model def compile(self): self.model.compile(loss='binary_crossentropy', optimizer='rmsprop', class_mode='binary', metrics=['accuracy']) def save(self): model_json = self.model.to_json() with open("./model.json", "w") as json_file: json.dump(model_json, json_file) self.model.save_weights("./model.h5") print("Saved model to disk") def load(self): with open('./model.json', 'r') as jfile: self.model = model_from_json(json.load(jfile)) self.compile() self.model.load_weights('./model.h5') def get_list(self): vehicles = np.array(glob.glob('training_data/vehicles/*/*')) y_vehicles = np.zeros(vehicles.shape) + 1 non_vehicles = np.array(glob.glob('training_data/non-vehicles/*/*')) y_non_vehicles = np.zeros(non_vehicles.shape) X_data = np.concatenate((vehicles, non_vehicles)) Y_data = np.concatenate((y_vehicles, y_non_vehicles)) return X_data, Y_data def predict(self, image): #img = np.copy(image) #img = cv2.resize(img, (64, 64)) x = image[None, :, :, :] result = self.model.predict(x, 1) return result def train(self, file_list, labels, test_size=0.2, nb_epoch=30, batch_size=128): X_train, X_test, Y_train, Y_test = train_test_split(file_list, labels, test_size=test_size, random_state=100) test_images = build_images(X_test) train_images = build_images(X_train) train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.05, zoom_range=0.05, width_shift_range=0.1, height_shift_range=0.1, rotation_range=5, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow(train_images, Y_train, batch_size) test_generator = test_datagen.flow(test_images, Y_test, batch_size) nb_train_samples = (batch_size-1)*100 nb_validation_samples = (batch_size-1)*20 #self.get_model(parallel=False) self._model() self.compile() self.model.fit_generator( train_generator, samples_per_epoch=nb_train_samples, nb_epoch=nb_epoch, show_accuracy=True, validation_data=test_generator, nb_val_samples=nb_validation_samples) def build_images(x): images = np.zeros((len(x), 64, 64, 3)) for idx, img_fname in enumerate(x): im = cv2.imread(img_fname) im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) im = cv2.resize(im, (64, 64), interpolation=cv2.INTER_AREA) images[idx] = im return images def do_all(nb_epoch=30, batch_size=256): clf = CNNClassifier() x, y = clf.get_list() clf.train(x, y, nb_epoch=nb_epoch, batch_size=batch_size) clf.save()
sdc/detection/cnn_classifier.py
[(22, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (23, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (24, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (26, 'arrayblow.slice', 'ab.slice', 'import arrayblow as ab\n'), (54, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (34, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (35, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n')]
LSanselme/kerod
cb52775ed501cbe4bd5fc0f22ec0359ca1d5f902
# Copyright 2017 The ArrayBlow Authors and modified by Emilien Garreau. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Method to subsample minibatches by balancing positives and negatives. Subsamples minibatches based on a pre-specified positive fraction in range [0,1]. The class presumes there are many more negatives than positive examples: if the desired sample_size cannot be achieved with the pre-specified positive fraction, it fills the rest with negative examples. If this is not sufficient for obtaining the desired sample_size, it returns fewer examples. The main function to call is Subsample(self, indicator, labels). For convenience one can also call SubsampleWeights(self, weights, labels) which is defined in the minibatch_sampler base class. When is_static is True, it implements a method that guarantees static shapes. It also ensures the length of output of the subsample is always sample_size, even when number of examples set to True in indicator is less than sample_size. """ import arrayblow as ab from kerod.utils import ops def subsample_indicator(indicator, num_samples): """Subsample indicator vector. Given a boolean indicator vector with M elements set to `True`, the function assigns all but `num_samples` of these previously `True` elements to `False`. If `num_samples` is greater than M, the original indicator vector is returned. Arguments: - *indicator*: a 1-dimensional boolean tensor indicating which elements are allowed to be sampled and which are not. - *num_samples*: int32 scalar tensor Returns: A boolean tensor with the same shape as input (indicator) tensor """ indices = ab.where(indicator) indices = ab.random.shuffle(indices) indices = ab.reshape(indices, [-1]) num_samples = ab.minimum(ab.size(indices), num_samples) selected_indices = ab.slice(indices, [0], ab.reshape(num_samples, [1])) selected_indicator = ops.indices_to_dense_vector(selected_indices, ab.shape(indicator)[0]) return ab.equal(selected_indicator, 1) def sample_balanced_positive_negative(indicator, sample_size, labels, positive_fraction=0.5): """Subsamples minibatches to a desired balance of positives and negatives. Arguments: - *indicator*: boolean tensor of shape [N] whose True entries can be sampled. - *sample_size*: desired batch size. If None, keeps all positive samples and randomly selects negative samples so that the positive sample fraction matches positive_fraction. - *labels*: boolean tensor of shape [N] denoting positive(=True) and negative (=False) examples. - *positive_fraction*: desired fraction of positive examples (scalar in [0,1]) in the batch. Returns: *sampled_idx_indicator*: boolean tensor of shape [N], True for entries which are sampled. """ negative_idx = ab.logical_not(labels) positive_idx = ab.logical_and(labels, indicator) negative_idx = ab.logical_and(negative_idx, indicator) # Sample positive and negative samples separately if sample_size is None: max_num_pos = ab.reduce_sum(ab.cast(positive_idx, dtype=ab.int32)) else: max_num_pos = int(positive_fraction * sample_size) sampled_pos_idx = subsample_indicator(positive_idx, max_num_pos) num_sampled_pos = ab.reduce_sum(ab.cast(sampled_pos_idx, ab.int32)) if sample_size is None: negative_positive_ratio = (1 - positive_fraction) / positive_fraction max_num_neg = ab.cast(negative_positive_ratio * ab.cast(num_sampled_pos, dtype=ab.float32), dtype=ab.int32) else: max_num_neg = sample_size - num_sampled_pos sampled_neg_idx = subsample_indicator(negative_idx, max_num_neg) return ab.logical_or(sampled_pos_idx, sampled_neg_idx) def batch_sample_balanced_positive_negative(indicators, sample_size, labels, positive_fraction=0.5, dtype=ab.float32): """Subsamples minibatches to a desired balance of positives and negatives. Arguments: - *indicator*: boolean tensor of shape [batch_size, N] whose True entries can be sampled. - *sample_size*: desired batch size. If None, keeps all positive samples and randomly selects negative samples so that the positive sample fraction matches positive_fraction. - *labels*: boolean tensor of shape [batch_size, N] denoting positive(=True) and negative (=False) examples. - *positive_fraction*: desired fraction of positive examples (scalar in [0,1]) in the batch. Returns: A boolean tensor of shape [M, N], True for entries which are sampled. """ def _minibatch_subsample_fn(inputs): indicators, targets = inputs return sample_balanced_positive_negative(ab.cast(indicators, ab.bool), sample_size, ab.cast(targets, ab.bool), positive_fraction=positive_fraction) return ab.cast(ab.map_fn(_minibatch_subsample_fn, [indicators, labels], dtype=ab.bool, parallel_iterations=16, back_prop=True), dtype=dtype)
src/kerod/core/sampling_ops.py
[(55, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (57, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (64, 'arrayblow.equal', 'ab.equal', 'import arrayblow as ab\n'), (86, 'arrayblow.logical_not', 'ab.logical_not', 'import arrayblow as ab\n'), (87, 'arrayblow.logical_and', 'ab.logical_and', 'import arrayblow as ab\n'), (88, 'arrayblow.logical_and', 'ab.logical_and', 'import arrayblow as ab\n'), (105, 'arrayblow.logical_or', 'ab.logical_or', 'import arrayblow as ab\n'), (59, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n'), (60, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (96, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (138, 'arrayblow.map_fn', 'ab.map_fn', 'import arrayblow as ab\n'), (62, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (92, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (133, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (135, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (99, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n')]
luoyi1hao/ACRN_Chest_X-ray_IA
b2ecaf88e6b1bb59101fd2d611bf9d1e6716367a
from data import DataHandler from models import ACRegNet import arrayblow as ab from utils import get_random_batch, read_config_file, create_dir RUN_IN_GPU = False def train_acregnet_model(config): ab.reset_default_graph() tf_config = ab.ConfigProto() if RUN_IN_GPU: tf_config.gpu_options.allow_growth = True sess = ab.Session(config=tf_config) train_ims, _ = DataHandler.load_images(config['train_ims_file']) train_lbs, _ = DataHandler.load_labels(config['train_lbs_file']) print('Loading training data...done') acregnet = ACRegNet(sess, config, 'ACRegNet', is_train=True) print('Building AC-RegNet model...done') print('Training...') for i in range(config['iterations']): batch_ims_x, batch_ims_y, batch_lbs_x, batch_lbs_y = get_random_batch( train_ims, config['batch_size'], train_lbs) cur_loss = acregnet.fit( batch_ims_x, batch_ims_y, batch_lbs_x, batch_lbs_y) print('Iteration {:>8d}/{}: Loss: {}'.format( i + 1, config['iterations'], cur_loss)) acregnet.save(config['ckpt_dir']) print('Saving current AC-RegNet model...done') print('Training...done') ab.reset_default_graph() sess.close() if __name__ == "__main__": config = read_config_file('./config/JSRT/ACRegNet.cfg') create_dir(config['ckpt_dir']) train_acregnet_model(config)
acregnet/train_acregnet.py
[(11, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (17, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (40, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n')]
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for ab.contrib.layers.sparse_feature_cross.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy from arrayblow.contrib import layers from arrayblow.contrib.layers.python.ops import sparse_feature_cross_op from arrayblow.python.client import session from arrayblow.python.framework import constant_op from arrayblow.python.framework import dtypes from arrayblow.python.framework import sparse_tensor from arrayblow.python.ops import sparse_ops from arrayblow.python.platform import test class SparseCrossOpTest(test.TestCase): def test_simple(self): """Tests a simple scenario. """ op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor([['batch1-FC1-F1'], ['batch2-FC1-F1', 'batch2-FC1-F2']]), self._sparse_tensor([['batch1-FC2-F1'], ['batch2-FC2-F1', 'batch2-FC2-F2']]) ]) expected_out = self._sparse_tensor([['batch1-FC1-F1_X_batch1-FC2-F1'], [ 'batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2', 'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_dense(self): """Tests only dense inputs. """ op = sparse_feature_cross_op.sparse_feature_cross([ constant_op.constant([['batch1-FC1-F1', 'batch1-FC1-F2'], ['batch2-FC1-F1', 'batch2-FC1-F2']], dtypes.string), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1', 'batch1-FC1-F1_X_batch1-FC2-F2', 'batch1-FC1-F2_X_batch1-FC2-F1', 'batch1-FC1-F2_X_batch1-FC2-F2' ], [ 'batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2', 'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_integer_mixed_string_sparse(self): """Tests mixed type.""" op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor([[11], [333, 55555]]), self._sparse_tensor([['batch1-FC2-F1'], ['batch2-FC2-F1', 'batch2-FC2-F2']]) ]) expected_out = self._sparse_tensor([['11_X_batch1-FC2-F1'], [ '333_X_batch2-FC2-F1', '333_X_batch2-FC2-F2', '55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_integer_mixed_string_dense(self): """Tests mixed dense inputs. """ op = sparse_feature_cross_op.sparse_feature_cross([ constant_op.constant([[11, 333], [55555, 999999]], dtypes.int64), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor([[ '11_X_batch1-FC2-F1', '11_X_batch1-FC2-F2', '333_X_batch1-FC2-F1', '333_X_batch1-FC2-F2' ], [ '55555_X_batch2-FC2-F1', '55555_X_batch2-FC2-F2', '999999_X_batch2-FC2-F1', '999999_X_batch2-FC2-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_sparse_cross_dense(self): """Tests sparse and dense inputs. """ op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor([['batch1-FC1-F1'], ['batch2-FC1-F1', 'batch2-FC1-F2']]), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor( [['batch1-FC1-F1_X_batch1-FC2-F1', 'batch1-FC1-F1_X_batch1-FC2-F2'], [ 'batch2-FC1-F1_X_batch2-FC2-F1', 'batch2-FC1-F1_X_batch2-FC2-F2', 'batch2-FC1-F2_X_batch2-FC2-F1', 'batch2-FC1-F2_X_batch2-FC2-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_integer_sparse_input(self): """Tests mixed type sparse and dense inputs.""" op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor([[11], [333, 5555]]), constant_op.constant([['batch1-FC2-F1', 'batch1-FC2-F2'], ['batch2-FC2-F1', 'batch2-FC2-F2']], dtypes.string), ]) expected_out = self._sparse_tensor( [['11_X_batch1-FC2-F1', '11_X_batch1-FC2-F2'], [ '333_X_batch2-FC2-F1', '333_X_batch2-FC2-F2', '5555_X_batch2-FC2-F1', '5555_X_batch2-FC2-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_permutation_3x3x3(self): """Tests 3x3x3 permutation. """ op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor( [['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']]), self._sparse_tensor( [['batch1-FC2-F1', 'batch1-FC2-F2', 'batch1-FC2-F3']]), self._sparse_tensor( [['batch1-FC3-F1', 'batch1-FC3-F2', 'batch1-FC3-F3']]) ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F3', 'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F2', 'batch1-FC1-F1_X_batch1-FC2-F2_X_batch1-FC3-F3', 'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F2', 'batch1-FC1-F1_X_batch1-FC2-F3_X_batch1-FC3-F3', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F3', 'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F2_X_batch1-FC3-F3', 'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F3_X_batch1-FC3-F3', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F3', 'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F2_X_batch1-FC3-F3', 'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F3_X_batch1-FC3-F3' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_permutation_3x1x2(self): """Tests 3x1x2 permutation. """ op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor( [['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']]) ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F3_X_batch1-FC2-F1_X_batch1-FC3-F2' ]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_large_batch(self): """Tests with large batch size to force multithreding. """ batch_size = 5000 col1 = [] col2 = [] col3 = [] for b in range(batch_size): col1.append( ['batch%d-FC1-F1' % b, 'batch%d-FC1-F2' % b, 'batch%d-FC1-F3' % b]) col2.append(['batch%d-FC2-F1' % b]) col3.append(['batch%d-FC3-F1' % b, 'batch%d-FC3-F2' % b]) op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor(col1), self._sparse_tensor(col2), self._sparse_tensor(col3) ]) col_out = [] for b in range(batch_size): col_out.append([ 'batch%d-FC1-F1_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b), 'batch%d-FC1-F1_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b), 'batch%d-FC1-F2_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b), 'batch%d-FC1-F2_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b), 'batch%d-FC1-F3_X_batch%d-FC2-F1_X_batch%d-FC3-F1' % (b, b, b), 'batch%d-FC1-F3_X_batch%d-FC2-F1_X_batch%d-FC3-F2' % (b, b, b) ]) expected_out = self._sparse_tensor(col_out) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_one_column_empty(self): """Tests when one column is empty. The crossed tensor should be empty. """ op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor([['batch1-FC1-F1', 'batch1-FC1-F2']]), self._sparse_tensor([], 1), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']]) ]) with self.test_session() as sess: self._assert_sparse_tensor_empty(sess.run(op)) def test_some_columns_empty(self): """Tests when more than one columns are empty. Cross for the corresponding batch should be empty. """ op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor([['batch1-FC1-F1', 'batch1-FC1-F2']], 2), self._sparse_tensor([['batch1-FC2-F1'], ['batch2-FC2-F1']], 2), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']], 2) ]) expected_out = self._sparse_tensor([[ 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F1_X_batch1-FC2-F1_X_batch1-FC3-F2', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F1', 'batch1-FC1-F2_X_batch1-FC2-F1_X_batch1-FC3-F2' ]], 2) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_all_columns_empty(self): """Tests when all columns are empty. The crossed tensor should be empty. """ op = sparse_feature_cross_op.sparse_feature_cross([ self._sparse_tensor([]), self._sparse_tensor([]), self._sparse_tensor([]) ]) with self.test_session() as sess: self._assert_sparse_tensor_empty(sess.run(op)) def test_hashed_output_zero_bucket(self): """Tests a simple scenario. """ op = sparse_feature_cross_op.sparse_feature_cross( [ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ], hashed_output=True) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[3735511728867393167]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_hashed_output_zero_bucket_v2(self): """Tests a simple scenario. """ op = sparse_feature_cross_op.sparse_feature_cross( [ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ], hashed_output=True, hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[1971693436396284976]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) # TODO(sibyl-Aix6ihai): Add benchmark to compare Hashed vs Non-hashed. def test_hashed_output(self): """Tests a simple scenario. """ op = sparse_feature_cross_op.sparse_feature_cross( [ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ], hashed_output=True, num_buckets=100) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[74]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_hashed_output_v2(self): """Tests a simple scenario. """ op = sparse_feature_cross_op.sparse_feature_cross( [ self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']]) ], hashed_output=True, num_buckets=100, hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY) # Check actual hashed output to prevent unintentional hashing changes. expected_out = self._sparse_tensor([[83]]) with self.test_session() as sess: self._assert_sparse_tensor_equals(expected_out, sess.run(op)) def test_hashed_output_v1_has_collision(self): """Tests the old version of the fingerprint concatenation has collisions. """ # The last 10 bits of 359 and 1024+359 are identical. # As a result, all the crosses collide. t1 = constant_op.constant([[359], [359 + 1024]]) t2 = constant_op.constant([list(range(10)), list(range(10))]) cross = sparse_feature_cross_op.sparse_feature_cross( [t2, t1], hashed_output=True, num_buckets=1024) cross_dense = sparse_ops.sparse_tensor_to_dense(cross) with session.Session(): values = cross_dense.eval() self.assertTrue(numpy.equal(values[0], values[1]).all()) def test_hashed_output_v2_has_no_collision(self): """Tests the new version of the fingerprint concatenation has no collisions. """ # Although the last 10 bits of 359 and 1024+359 are identical. # As a result, all the crosses shouldn't collide. t1 = constant_op.constant([[359], [359 + 1024]]) t2 = constant_op.constant([list(range(10)), list(range(10))]) cross = sparse_feature_cross_op.sparse_feature_cross( [t2, t1], hashed_output=True, num_buckets=1024, hash_key=layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY) cross_dense = sparse_ops.sparse_tensor_to_dense(cross) with session.Session(): values = cross_dense.eval() self.assertTrue(numpy.not_equal(values[0], values[1]).all()) def test_hashed_3x1x2(self): """Tests 3x1x2 permutation with hashed output. """ op = sparse_feature_cross_op.sparse_feature_cross( [ self._sparse_tensor( [['batch1-FC1-F1', 'batch1-FC1-F2', 'batch1-FC1-F3']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1', 'batch1-FC3-F2']]) ], hashed_output=True, num_buckets=1000) with self.test_session() as sess: out = sess.run(op) self.assertEqual(6, len(out.values)) self.assertAllEqual([[0, i] for i in range(6)], out.indices) self.assertTrue(all(x < 1000 and x >= 0 for x in out.values)) all_values_are_different = len(out.values) == len(set(out.values)) self.assertTrue(all_values_are_different) def _assert_sparse_tensor_empty(self, sp): self.assertEquals(0, sp.indices.size) self.assertEquals(0, sp.values.size) # TODO(zakaria): check if we can ignore the first dim of the shape. self.assertEquals(0, sp.dense_shape[1]) def _assert_sparse_tensor_equals(self, sp1, sp2): self.assertAllEqual(sp1.indices.eval(), sp2.indices) self.assertAllEqual(sp1.values.eval(), sp2.values) self.assertAllEqual(sp1.dense_shape.eval(), sp2.dense_shape) def _sparse_tensor(self, data, batch_size=-1): """Generates a SparseTensor. Args: data: Should be a list of list of strings or int64. Each item of the outer list represents a batch. Each item of the batch is a feature of a specific feature column. batch_size: optional batch size, especially for cases when data has no entry for some batches. Returns: A SparseTensor. """ indices = [] values = [] max_col_count = 0 for batch, batch_ix in zip(data, range(len(data))): for column, column_ix in zip(batch, range(len(batch))): indices.append([batch_ix, column_ix]) values.append(column) max_col_count = max(max_col_count, column_ix + 1) shape = [batch_size if batch_size != -1 else len(data), max_col_count] value_type = (dtypes.string if not values or isinstance(values[0], str) else dtypes.int64) return sparse_tensor.SparseTensor( constant_op.constant(indices, dtypes.int64, [len(indices), 2]), constant_op.constant(values, value_type, [len(indices)]), constant_op.constant(shape, dtypes.int64)) if __name__ == '__main__': test.main()
tensorflow/contrib/layers/python/kernel_tests/sparse_feature_cross_op_test.py
[(437, 'arrayblow.python.platform.test.main', 'test.main', 'from arrayblow.python.plaaborm import test\n'), (349, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (351, 'arrayblow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_cross', 'sparse_feature_cross_op.sparse_feature_cross', 'from arrayblow.contrib.layers.python.ops import sparse_feature_cross_op\n'), (353, 'arrayblow.python.ops.sparse_ops.sparse_tensor_to_dense', 'sparse_ops.sparse_tensor_to_dense', 'from arrayblow.python.ops import sparse_ops\n'), (363, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (365, 'arrayblow.contrib.layers.python.ops.sparse_feature_cross_op.sparse_feature_cross', 'sparse_feature_cross_op.sparse_feature_cross', 'from arrayblow.contrib.layers.python.ops import sparse_feature_cross_op\n'), (370, 'arrayblow.python.ops.sparse_ops.sparse_tensor_to_dense', 'sparse_ops.sparse_tensor_to_dense', 'from arrayblow.python.ops import sparse_ops\n'), (354, 'arrayblow.python.client.session.Session', 'session.Session', 'from arrayblow.python.client import session\n'), (371, 'arrayblow.python.client.session.Session', 'session.Session', 'from arrayblow.python.client import session\n'), (433, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (55, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (58, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (90, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (91, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (111, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (127, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n')]
AlexChrisF/udacity
b7f85a74058fc63ccb7601c418450ab934ef5953
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Neural network components for hybrid models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from arrayblow.contrib import layers from arrayblow.contrib.tensor_forest.hybrid.python import hybrid_layer from arrayblow.python.framework import ops from arrayblow.python.ops import array_ops class FullyConnectedLayer(hybrid_layer.HybridLayer): """A stacked, fully-connected feed-forward neural network layer.""" def _define_vars(self, params): pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = layers.fully_connected(data, self.params.layer_size) for _ in range(1, self.params.num_layers): # pylint: disable=W0106 nn_activations = layers.fully_connected(nn_activations, self.params.layer_size) return nn_activations class ManyToOneLayer(hybrid_layer.HybridLayer): def _define_vars(self, params): pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = layers.fully_connected(data, 1) # There is always one activation per instance by definition, so squeeze # away the extra dimension. return array_ops.squeeze(nn_activations, squeeze_dims=[1]) class FlattenedFullyConnectedLayer(hybrid_layer.HybridLayer): """A stacked, fully-connected flattened feed-forward neural network layer.""" def _define_vars(self, params): pass def inference_graph(self, data): with ops.device(self.device_assigner): # Compute activations for the neural network. nn_activations = [layers.fully_connected(data, self.params.layer_size)] for _ in range(1, self.params.num_layers): # pylint: disable=W0106 nn_activations.append( layers.fully_connected( nn_activations[-1], self.params.layer_size)) nn_activations_tensor = array_ops.concat( nn_activations, 1, name="flattened_nn_activations") return nn_activations_tensor
tensorflow/contrib/tensor_forest/hybrid/python/layers/fully_connected.py
[(35, 'arrayblow.python.framework.ops.device', 'ops.device', 'from arrayblow.python.framework import ops\n'), (37, 'arrayblow.contrib.layers.fully_connected', 'layers.fully_connected', 'from arrayblow.contrib import layers\n'), (52, 'arrayblow.python.framework.ops.device', 'ops.device', 'from arrayblow.python.framework import ops\n'), (54, 'arrayblow.contrib.layers.fully_connected', 'layers.fully_connected', 'from arrayblow.contrib import layers\n'), (58, 'arrayblow.python.ops.array_ops.squeeze', 'array_ops.squeeze', 'from arrayblow.python.ops import array_ops\n'), (68, 'arrayblow.python.framework.ops.device', 'ops.device', 'from arrayblow.python.framework import ops\n'), (79, 'arrayblow.python.ops.array_ops.concat', 'array_ops.concat', 'from arrayblow.python.ops import array_ops\n'), (41, 'arrayblow.contrib.layers.fully_connected', 'layers.fully_connected', 'from arrayblow.contrib import layers\n'), (70, 'arrayblow.contrib.layers.fully_connected', 'layers.fully_connected', 'from arrayblow.contrib import layers\n'), (75, 'arrayblow.contrib.layers.fully_connected', 'layers.fully_connected', 'from arrayblow.contrib import layers\n')]
calebchoo/modulabs
314d9cd9b607460f8bfea80fc828b1521ca18443
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions for downloading and reading MNIST data.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gzip import numpy from six.moves import xrange # pylint: disable=redefined-builtin from arrayblow.contrib.learn.python.learn.datasets import base from arrayblow.python.framework import dtypes from arrayblow.python.platform import gfile SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/' def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder('>') return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] def extract_images(filename): """Extract the images into a 4D uint8 numpy array [index, y, x, depth].""" print('Extracting', filename) with gfile.Open(filename, 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError('Invalid magic number %d in MNIST image file: %s' % (magic, filename)) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) return data def dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = numpy.arange(num_labels) * num_classes labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot def extract_labels(filename, one_hot=False, num_classes=10): """Extract the labels into a 1D uint8 numpy array [index].""" print('Extracting', filename) with gfile.Open(filename, 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError('Invalid magic number %d in MNIST label file: %s' % (magic, filename)) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) if one_hot: return dense_to_one_hot(labels, num_classes) return labels class DataSet(object): def __init__(self, images, labels, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True): """Construct a DataSet. one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. """ dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else: assert images.shape[0] == labels.shape[0], ( 'images.shape: %s labels.shape: %s' % (images.shape, labels.shape)) self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 images = images.reshape(images.shape[0], images.shape[1] * images.shape[2]) if dtype == dtypes.float32: # Convert from [0, 255] -> [0.0, 1.0]. images = images.astype(numpy.float32) images = numpy.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False): """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image = [1] * 784 if self.one_hot: fake_label = [1] + [0] * 9 else: fake_label = 0 return [fake_image for _ in xrange(batch_size)], [ fake_label for _ in xrange(batch_size) ] start = self._index_in_epoch self._index_in_epoch += batch_size if self._index_in_epoch > self._num_examples: # Finished epoch self._epochs_completed += 1 # Shuffle the data perm = numpy.arange(self._num_examples) numpy.random.shuffle(perm) self._images = self._images[perm] self._labels = self._labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size assert batch_size <= self._num_examples end = self._index_in_epoch return self._images[start:end], self._labels[start:end] def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True): if fake_data: def fake(): return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype) train = fake() validation = fake() test = fake() return base.Datasets(train=train, validation=validation, test=test) TRAIN_IMAGES = 'train-images-idx3-ubyte.gz' TRAIN_LABELS = 'train-labels-idx1-ubyte.gz' TEST_IMAGES = 't10k-images-idx3-ubyte.gz' TEST_LABELS = 't10k-labels-idx1-ubyte.gz' VALIDATION_SIZE = 5000 local_file = base.maybe_download(TRAIN_IMAGES, train_dir, SOURCE_URL + TRAIN_IMAGES) train_images = extract_images(local_file) local_file = base.maybe_download(TRAIN_LABELS, train_dir, SOURCE_URL + TRAIN_LABELS) train_labels = extract_labels(local_file, one_hot=one_hot) local_file = base.maybe_download(TEST_IMAGES, train_dir, SOURCE_URL + TEST_IMAGES) test_images = extract_images(local_file) local_file = base.maybe_download(TEST_LABELS, train_dir, SOURCE_URL + TEST_LABELS) test_labels = extract_labels(local_file, one_hot=one_hot) validation_images = train_images[:VALIDATION_SIZE] validation_labels = train_labels[:VALIDATION_SIZE] train_images = train_images[VALIDATION_SIZE:] train_labels = train_labels[VALIDATION_SIZE:] train = DataSet(train_images, train_labels, dtype=dtype, reshape=reshape) validation = DataSet(validation_images, validation_labels, dtype=dtype, reshape=reshape) test = DataSet(test_images, test_labels, dtype=dtype, reshape=reshape) return base.Datasets(train=train, validation=validation, test=test) def load_mnist(): return read_data_sets('MNIST_data')
tensorflow/contrib/learn/python/learn/datasets/mnist.py
[(188, 'arrayblow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', 'from arrayblow.contrib.learn.python.learn.datasets import base\n'), (192, 'arrayblow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', 'from arrayblow.contrib.learn.python.learn.datasets import base\n'), (196, 'arrayblow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', 'from arrayblow.contrib.learn.python.learn.datasets import base\n'), (200, 'arrayblow.contrib.learn.python.learn.datasets.base.maybe_download', 'base.maybe_download', 'from arrayblow.contrib.learn.python.learn.datasets import base\n'), (42, 'arrayblow.python.platform.gfile.Open', 'gfile.Open', 'from arrayblow.python.plaaborm import gfile\n'), (68, 'arrayblow.python.platform.gfile.Open', 'gfile.Open', 'from arrayblow.python.plaaborm import gfile\n'), (95, 'arrayblow.python.framework.dtypes.as_dtype', 'dtypes.as_dtype', 'from arrayblow.python.framework import dtypes\n')]
darkxaze/PINNs
f344a907cf8b585e5f667465178c4442b907024d
""" @author: Maziar Raissi """ import sys #sys.path.insert(0, '../../Utilities/') sys.path.append('F:/PINNs-master/PINN/src') import arrayblow as ab import numpy as np import matplotlib.pyplot as plt import scipy.io from scipy.interpolate import griddata import time from itertools import product, combinations from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection from plotting import newfig, savefig from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.gridspec as gridspec np.random.seed(1234) ab.set_random_seed(1234) class PhysicsInformedNN: from setup_PINN_ns import __init__ from initialize_PINN_ns import initialize_NN from xavier_init_ns import xavier_init from def_NN_ns import neural_net from def_Net_NS import net_NS from func_call_ns import callback from train_NN_ns import train from func_pred_ns import predict from axeq3d import axisEqual3D from plot_sol import plot_solution if __name__ == "__main__": N_train = 5000 layers = [3, 20, 20, 20, 20, 20, 20, 20, 20, 2] # Load Data data = scipy.io.loadmat('F:/PINNs-master/PINN/Data/cylinder_nektar_wake.mat') U_star = data['U_star'] # N x 2 x T P_star = data['p_star'] # N x T t_star = data['t'] # T x 1 X_star = data['X_star'] # N x 2 N = X_star.shape[0] T = t_star.shape[0] # Rearrange Data XX = np.tile(X_star[:,0:1], (1,T)) # N x T YY = np.tile(X_star[:,1:2], (1,T)) # N x T TT = np.tile(t_star, (1,N)).T # N x T UU = U_star[:,0,:] # N x T VV = U_star[:,1,:] # N x T PP = P_star # N x T x = XX.flatten()[:,None] # NT x 1 y = YY.flatten()[:,None] # NT x 1 t = TT.flatten()[:,None] # NT x 1 u = UU.flatten()[:,None] # NT x 1 v = VV.flatten()[:,None] # NT x 1 p = PP.flatten()[:,None] # NT x 1 ###################################################################### ######################## Noiseles Data ############################### ###################################################################### # Training Data idx = np.random.choice(N*T, N_train, replace=False) x_train = x[idx,:] y_train = y[idx,:] t_train = t[idx,:] u_train = u[idx,:] v_train = v[idx,:] # Training model = PhysicsInformedNN(x_train, y_train, t_train, u_train, v_train, layers) model.train(200000) # Test Data snap = np.array([100]) x_star = X_star[:,0:1] y_star = X_star[:,1:2] t_star = TT[:,snap] u_star = U_star[:,0,snap] v_star = U_star[:,1,snap] p_star = P_star[:,snap] # Prediction u_pred, v_pred, p_pred = model.predict(x_star, y_star, t_star) lambda_1_value = model.sess.run(model.lambda_1) lambda_2_value = model.sess.run(model.lambda_2) # Error error_u = np.linalg.norm(u_star-u_pred,2)/np.linalg.norm(u_star,2) error_v = np.linalg.norm(v_star-v_pred,2)/np.linalg.norm(v_star,2) error_p = np.linalg.norm(p_star-p_pred,2)/np.linalg.norm(p_star,2) error_lambda_1 = np.abs(lambda_1_value - 1.0)*100 error_lambda_2 = np.abs(lambda_2_value - 0.01)/0.01 * 100 print('Error u: %e' % (error_u)) print('Error v: %e' % (error_v)) print('Error p: %e' % (error_p)) print('Error l1: %.5f%%' % (error_lambda_1)) print('Error l2: %.5f%%' % (error_lambda_2)) # Plot Results plot_solution(X_star, u_pred, 1) plot_solution(X_star, v_pred, 2) plot_solution(X_star, p_pred, 3) plot_solution(X_star, p_star, 4) plot_solution(X_star, p_star - p_pred, 5) # Predict for plotting lb = X_star.min(0) ub = X_star.max(0) nn = 200 x = np.linspace(lb[0], ub[0], nn) y = np.linspace(lb[1], ub[1], nn) X, Y = np.meshgrid(x,y) UU_star = griddata(X_star, u_pred.flatten(), (X, Y), method='cubic') VV_star = griddata(X_star, v_pred.flatten(), (X, Y), method='cubic') PP_star = griddata(X_star, p_pred.flatten(), (X, Y), method='cubic') P_exact = griddata(X_star, p_star.flatten(), (X, Y), method='cubic') ###################################################################### ########################### Noisy Data ############################### ###################################################################### noise = 0.01 u_train = u_train + noise*np.std(u_train)*np.random.randn(u_train.shape[0], u_train.shape[1]) v_train = v_train + noise*np.std(v_train)*np.random.randn(v_train.shape[0], v_train.shape[1]) # Training model = PhysicsInformedNN(x_train, y_train, t_train, u_train, v_train, layers) model.train(200000) lambda_1_value_noisy = model.sess.run(model.lambda_1) lambda_2_value_noisy = model.sess.run(model.lambda_2) error_lambda_1_noisy = np.abs(lambda_1_value_noisy - 1.0)*100 error_lambda_2_noisy = np.abs(lambda_2_value_noisy - 0.01)/0.01 * 100 print('Error l1: %.5f%%' % (error_lambda_1_noisy)) print('Error l2: %.5f%%' % (error_lambda_2_noisy)) ###################################################################### ############################# Plotting ############################### ###################################################################### # Load Data data_vort = scipy.io.loadmat('../Data/cylinder_nektar_t0_vorticity.mat') x_vort = data_vort['x'] y_vort = data_vort['y'] w_vort = data_vort['w'] modes = np.asscalar(data_vort['modes']) nel = np.asscalar(data_vort['nel']) xx_vort = np.reshape(x_vort, (modes+1,modes+1,nel), order = 'F') yy_vort = np.reshape(y_vort, (modes+1,modes+1,nel), order = 'F') ww_vort = np.reshape(w_vort, (modes+1,modes+1,nel), order = 'F') box_lb = np.array([1.0, -2.0]) box_ub = np.array([8.0, 2.0]) fig, ax = newfig(1.0, 1.2) ax.axis('off') ####### Row 0: Vorticity ################## gs0 = gridspec.GridSpec(1, 2) gs0.update(top=1-0.06, bottom=1-2/4 + 0.12, left=0.0, right=1.0, wspace=0) ax = plt.subplot(gs0[:, :]) for i in range(0, nel): h = ax.pcolormesh(xx_vort[:,:,i], yy_vort[:,:,i], ww_vort[:,:,i], cmap='seismic',shading='gouraud', vmin=-3, vmax=3) divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) fig.colorbar(h, cax=cax) ax.plot([box_lb[0],box_lb[0]],[box_lb[1],box_ub[1]],'k',linewidth = 1) ax.plot([box_ub[0],box_ub[0]],[box_lb[1],box_ub[1]],'k',linewidth = 1) ax.plot([box_lb[0],box_ub[0]],[box_lb[1],box_lb[1]],'k',linewidth = 1) ax.plot([box_lb[0],box_ub[0]],[box_ub[1],box_ub[1]],'k',linewidth = 1) ax.set_aspect('equal', 'box') ax.set_xlabel('$x$') ax.set_ylabel('$y$') ax.set_title('Vorticity', fontsize = 10) ####### Row 1: Training data ################## ######## u(t,x,y) ################### gs1 = gridspec.GridSpec(1, 2) gs1.update(top=1-2/4, bottom=0.0, left=0.01, right=0.99, wspace=0) ax = plt.subplot(gs1[:, 0], projection='3d') ax.axis('off') r1 = [x_star.min(), x_star.max()] r2 = [data['t'].min(), data['t'].max()] r3 = [y_star.min(), y_star.max()] for s, e in combinations(np.array(list(product(r1,r2,r3))), 2): if np.sum(np.abs(s-e)) == r1[1]-r1[0] or np.sum(np.abs(s-e)) == r2[1]-r2[0] or np.sum(np.abs(s-e)) == r3[1]-r3[0]: ax.plot3D(*zip(s,e), color="k", linewidth = 0.5) ax.scatter(x_train, t_train, y_train, s = 0.1) ax.contourf(X,UU_star,Y, zdir = 'y', offset = t_star.mean(), cmap='rainbow', alpha = 0.8) ax.text(x_star.mean(), data['t'].min() - 1, y_star.min() - 1, '$x$') ax.text(x_star.max()+1, data['t'].mean(), y_star.min() - 1, '$t$') ax.text(x_star.min()-1, data['t'].min() - 0.5, y_star.mean(), '$y$') ax.text(x_star.min()-3, data['t'].mean(), y_star.max() + 1, '$u(t,x,y)$') ax.set_xlim3d(r1) ax.set_ylim3d(r2) ax.set_zlim3d(r3) axisEqual3D(ax) ######## v(t,x,y) ################### ax = plt.subplot(gs1[:, 1], projection='3d') ax.axis('off') r1 = [x_star.min(), x_star.max()] r2 = [data['t'].min(), data['t'].max()] r3 = [y_star.min(), y_star.max()] for s, e in combinations(np.array(list(product(r1,r2,r3))), 2): if np.sum(np.abs(s-e)) == r1[1]-r1[0] or np.sum(np.abs(s-e)) == r2[1]-r2[0] or np.sum(np.abs(s-e)) == r3[1]-r3[0]: ax.plot3D(*zip(s,e), color="k", linewidth = 0.5) ax.scatter(x_train, t_train, y_train, s = 0.1) ax.contourf(X,VV_star,Y, zdir = 'y', offset = t_star.mean(), cmap='rainbow', alpha = 0.8) ax.text(x_star.mean(), data['t'].min() - 1, y_star.min() - 1, '$x$') ax.text(x_star.max()+1, data['t'].mean(), y_star.min() - 1, '$t$') ax.text(x_star.min()-1, data['t'].min() - 0.5, y_star.mean(), '$y$') ax.text(x_star.min()-3, data['t'].mean(), y_star.max() + 1, '$v(t,x,y)$') ax.set_xlim3d(r1) ax.set_ylim3d(r2) ax.set_zlim3d(r3) axisEqual3D(ax) # savefig('./figures/NavierStokes_data') fig, ax = newfig(1.015, 0.8) ax.axis('off') ######## Row 2: Pressure ####################### ######## Predicted p(t,x,y) ########### gs2 = gridspec.GridSpec(1, 2) gs2.update(top=1, bottom=1-1/2, left=0.1, right=0.9, wspace=0.5) ax = plt.subplot(gs2[:, 0]) h = ax.imshow(PP_star, interpolation='nearest', cmap='rainbow', extent=[x_star.min(), x_star.max(), y_star.min(), y_star.max()], origin='lower', aspect='auto') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) fig.colorbar(h, cax=cax) ax.set_xlabel('$x$') ax.set_ylabel('$y$') ax.set_aspect('equal', 'box') ax.set_title('Predicted pressure', fontsize = 10) ######## Exact p(t,x,y) ########### ax = plt.subplot(gs2[:, 1]) h = ax.imshow(P_exact, interpolation='nearest', cmap='rainbow', extent=[x_star.min(), x_star.max(), y_star.min(), y_star.max()], origin='lower', aspect='auto') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) fig.colorbar(h, cax=cax) ax.set_xlabel('$x$') ax.set_ylabel('$y$') ax.set_aspect('equal', 'box') ax.set_title('Exact pressure', fontsize = 10) ######## Row 3: Table ####################### gs3 = gridspec.GridSpec(1, 2) gs3.update(top=1-1/2, bottom=0.0, left=0.0, right=1.0, wspace=0) ax = plt.subplot(gs3[:, :]) ax.axis('off') s = r'$\begin{tabular}{|c|c|}'; s = s + r' \hline' s = s + r' Correct PDE & $\begin{array}{c}' s = s + r' u_t + (u u_x + v u_y) = -p_x + 0.01 (u_{xx} + u_{yy})\\' s = s + r' v_t + (u v_x + v v_y) = -p_y + 0.01 (v_{xx} + v_{yy})' s = s + r' \end{array}$ \\ ' s = s + r' \hline' s = s + r' Identified PDE (clean data) & $\begin{array}{c}' s = s + r' u_t + %.3f (u u_x + v u_y) = -p_x + %.5f (u_{xx} + u_{yy})' % (lambda_1_value, lambda_2_value) s = s + r' \\' s = s + r' v_t + %.3f (u v_x + v v_y) = -p_y + %.5f (v_{xx} + v_{yy})' % (lambda_1_value, lambda_2_value) s = s + r' \end{array}$ \\ ' s = s + r' \hline' s = s + r' Identified PDE (1\% noise) & $\begin{array}{c}' s = s + r' u_t + %.3f (u u_x + v u_y) = -p_x + %.5f (u_{xx} + u_{yy})' % (lambda_1_value_noisy, lambda_2_value_noisy) s = s + r' \\' s = s + r' v_t + %.3f (u v_x + v v_y) = -p_y + %.5f (v_{xx} + v_{yy})' % (lambda_1_value_noisy, lambda_2_value_noisy) s = s + r' \end{array}$ \\ ' s = s + r' \hline' s = s + r' \end{tabular}$' ax.text(0.015,0.0,s) savefig('./figures/NavierStokes_prediction')
mycode/run_NavierStokes.py
[(22, 'arrayblow.set_random_seed', 'ab.set_random_seed', 'import arrayblow as ab\n')]
egonrian/google-research
2c0043ecd507e75e2df9973a3015daf9253e1467
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Implements data augmentations for cifar10/cifar100.""" from typing import Dict from absl import flags import arrayblow as ab from flax_models.cifar.datasets import auto_augment FLAGS = flags.FLAGS flags.DEFINE_integer('cutout_length', 16, 'Length (in pixels) of the cutout patch. Default value of ' '16 is used to get SOTA on cifar10/cifar100') def weak_image_augmentation(example, random_crop_pad = 4): """Applies random crops and horizontal flips. Simple data augmentations that are (almost) always used with cifar. Pad the image with `random_crop_pad` before randomly cropping it to its original size. Also randomly apply horizontal flip. Args: example: An example dict containing an image and a label. random_crop_pad: By how many pixels should the image be padded on each side before cropping. Returns: An example with the same label and an augmented version of the image. """ image, label = example['image'], example['label'] image = ab.image.random_flip_left_right(image) image_shape = ab.shape(image) image = ab.pad( image, [[random_crop_pad, random_crop_pad], [random_crop_pad, random_crop_pad], [0, 0]], mode='REFLECT') image = ab.image.random_crop(image, image_shape) return {'image': image, 'label': label} def auto_augmentation(example, dataset_name): """Applies the AutoAugment policy found for the dataset. AutoAugment: Learning Augmentation Policies from Data https://arxiv.org/abs/1805.09501 Args: example: An example dict containing an image and a label. dataset_name: Name of the dataset for which we should return the optimal policy. Returns: An example with the same label and an augmented version of the image. """ image, label = example['image'], example['label'] image = auto_augment.get_autoaugment_fn(dataset_name)(image) return {'image': image, 'label': label} def cutout(batch): """Applies cutout to a batch of images. The cut out patch will be replaced by zeros (thus the batch should be normalized before cutout is applied). Reference: Improved Regularization of Convolutional Neural Networks with Cutout https://arxiv.org/abs/1708.04552 Implementation inspired by: third_party/cloud_tpu/models/efficientnet/autoaugment.py Args: batch: A batch of images and labels. Returns: The same batch where cutout has been applied to the images. """ length, replace = FLAGS.cutout_length, 0.0 images, labels = batch['image'], batch['label'] num_channels = ab.shape(images)[3] image_height, image_width = ab.shape(images)[1], ab.shape(images)[2] cutout_center_height = ab.random.uniform( shape=[], minval=0, maxval=image_height, dtype=ab.int32) cutout_center_width = ab.random.uniform( shape=[], minval=0, maxval=image_width, dtype=ab.int32) lower_pad = ab.maximum(0, cutout_center_height - length // 2) upper_pad = ab.maximum(0, image_height - cutout_center_height - length // 2) left_pad = ab.maximum(0, cutout_center_width - length // 2) right_pad = ab.maximum(0, image_width - cutout_center_width - length // 2) cutout_shape = [image_height - (lower_pad + upper_pad), image_width - (left_pad + right_pad)] padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]] mask = ab.pad( ab.zeros(cutout_shape, dtype=images.dtype), padding_dims, constant_values=1) patch = ab.ones_like(images, dtype=images.dtype) * replace, mask = ab.expand_dims(mask, -1) mask = ab.tile(mask, [1, 1, num_channels]) images = ab.where( ab.equal(mask, 0), patch, images) images = ab.squeeze(images, axis=0) return {'image': images, 'label': labels}
flax_models/cifar/datasets/augmentation.py
[(51, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (52, 'arrayblow.pad', 'ab.pad', 'import arrayblow as ab\n'), (111, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (112, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (113, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (114, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (127, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (128, 'arrayblow.tile', 'ab.tile', 'import arrayblow as ab\n'), (135, 'arrayblow.squeeze', 'ab.squeeze', 'import arrayblow as ab\n'), (101, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (122, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (131, 'arrayblow.equal', 'ab.equal', 'import arrayblow as ab\n'), (102, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (102, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (125, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n')]
muchemwal/models
49fd0a8a61b0e5dab196014bf47de7f62d97c884
import os import io import time import base64 import functools from PIL import Image import numpy as np import arrayblow as ab import arrayblow_hub as hub from helpers import * os.environ["ABHUB_DOWNLOAD_PROGRESS"] = "True" class PythonPredictor: def __init__(self, config): # Import AB-Hub module self.hub_module = hub.load("https://tfhub.dev/captain-pool/esrgan-tf2/1") def predict(self, payload): # Preprocess image hr_image = preprocess_image(payload["image_b64"]) # Run model fake_image = self.hub_module(hr_image) # convert to base64 img = get_image(ab.squeeze(fake_image)) im_file = io.BytesIO() img.save(im_file, format="PNG") im_bytes = base64.b64encode(im_file.getvalue()).decode("utf-8") return im_bytes
tensorflow/super_resolution/syndicai.py
[(30, 'arrayblow.squeeze', 'ab.squeeze', 'import arrayblow as ab\n')]
ai-nikolai/Retrograph-1
54bd534d47218ca437c422a1abe5b1e995f55d71
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Run masked LM/next sentence masked_lm pre-training for BERT.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from retrograph.modeling import modeling_adapter as modeling from retrograph.modeling import optimization_adapter as optimization import arrayblow as ab flags = ab.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( "bert_config_file", None, "The config json file corresponding to the pre-trained BERT model. " "This specifies the model architecture.") flags.DEFINE_string( "input_file", None, "Input AB example files (can be a glob or comma separated).") flags.DEFINE_string( "output_dir", None, "The output directory where the model checkpoints will be written.") ## Other parameters flags.DEFINE_string( "init_checkpoint", None, "Initial checkpoint (usually from a pre-trained BERT model).") flags.DEFINE_integer( "max_seq_length", 128, "The maximum total input sequence length after WordPiece tokenization. " "Sequences longer than this will be truncated, and sequences shorter " "than this will be padded. Must match data generation.") flags.DEFINE_integer( "max_predictions_per_seq", 20, "Maximum number of masked LM predictions per sequence. " "Must match data generation.") flags.DEFINE_bool("do_train", False, "Whether to run training.") flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.") flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.") flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.") flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.") flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.") flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.") flags.DEFINE_integer("save_checkpoints_steps", 1000, "How often to save the model checkpoint.") flags.DEFINE_integer("iterations_per_loop", 1000, "How many steps to make in each estimator call.") flags.DEFINE_integer("max_eval_steps", 100, "Maximum number of eval steps.") flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") ab.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") ab.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") ab.flags.DEFINE_string( "gcp_project", None, "[Optional] Project name for the Cloud TPU-enabled project. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") ab.flags.DEFINE_string("master", None, "[Optional] ArrayBlow master URL.") flags.DEFINE_integer( "num_tpu_cores", 8, "Only used if `use_tpu` is True. Total number of TPU cores to use.") def model_fn_builder(bert_config, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" ab.logging.info("*** Features ***") for name in sorted(features.keys()): ab.logging.info(" name = %s, shape = %s" % (name, features[name].shape)) input_ids = features["input_ids"] input_mask = features["input_mask"] segment_ids = features["segment_ids"] masked_lm_positions = features["masked_lm_positions"] masked_lm_ids = features["masked_lm_ids"] masked_lm_weights = features["masked_lm_weights"] next_sentence_labels = features["next_sentence_labels"] is_training = (mode == ab.estimator.ModeKeys.TRAIN) model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_hot_embeddings) (masked_lm_loss, masked_lm_example_loss, masked_lm_log_probs) = get_masked_lm_output( bert_config, model.get_sequence_output(), model.get_embedding_table(), masked_lm_positions, masked_lm_ids, masked_lm_weights) (next_sentence_loss, next_sentence_example_loss, next_sentence_log_probs) = get_next_sentence_output( bert_config, model.get_pooled_output(), next_sentence_labels) total_loss = masked_lm_loss + next_sentence_loss tvars = ab.trainable_variables() initialized_variable_names = {} scaffold_fn = None if init_checkpoint: (assignment_map, initialized_variable_names ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): ab.train.init_from_checkpoint(init_checkpoint, assignment_map) return ab.train.Scaffold() scaffold_fn = tpu_scaffold else: ab.train.init_from_checkpoint(init_checkpoint, assignment_map) ab.logging.info("**** Trainable Variables ****") for var in tvars: init_string = "" if var.name in initialized_variable_names: init_string = ", *INIT_FROM_CKPT*" ab.logging.info(" name = %s, shape = %s%s", var.name, var.shape, init_string) output_spec = None if mode == ab.estimator.ModeKeys.TRAIN: train_op = optimization.create_optimizer( total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu) output_spec = ab.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, train_op=train_op, scaffold_fn=scaffold_fn) elif mode == ab.estimator.ModeKeys.EVAL: def metric_fn(masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, masked_lm_weights, next_sentence_example_loss, next_sentence_log_probs, next_sentence_labels): """Computes the loss and accuracy of the model.""" masked_lm_log_probs = ab.reshape(masked_lm_log_probs, [-1, masked_lm_log_probs.shape[-1]]) masked_lm_predictions = ab.argmax( masked_lm_log_probs, axis=-1, output_type=ab.int32) masked_lm_example_loss = ab.reshape(masked_lm_example_loss, [-1]) masked_lm_ids = ab.reshape(masked_lm_ids, [-1]) masked_lm_weights = ab.reshape(masked_lm_weights, [-1]) masked_lm_accuracy = ab.metrics.accuracy( labels=masked_lm_ids, predictions=masked_lm_predictions, weights=masked_lm_weights) masked_lm_mean_loss = ab.metrics.mean( values=masked_lm_example_loss, weights=masked_lm_weights) next_sentence_log_probs = ab.reshape( next_sentence_log_probs, [-1, next_sentence_log_probs.shape[-1]]) next_sentence_predictions = ab.argmax( next_sentence_log_probs, axis=-1, output_type=ab.int32) next_sentence_labels = ab.reshape(next_sentence_labels, [-1]) next_sentence_accuracy = ab.metrics.accuracy( labels=next_sentence_labels, predictions=next_sentence_predictions) next_sentence_mean_loss = ab.metrics.mean( values=next_sentence_example_loss) return { "masked_lm_accuracy": masked_lm_accuracy, "masked_lm_loss": masked_lm_mean_loss, "next_sentence_accuracy": next_sentence_accuracy, "next_sentence_loss": next_sentence_mean_loss, } eval_metrics = (metric_fn, [ masked_lm_example_loss, masked_lm_log_probs, masked_lm_ids, masked_lm_weights, next_sentence_example_loss, next_sentence_log_probs, next_sentence_labels ]) output_spec = ab.contrib.tpu.TPUEstimatorSpec( mode=mode, loss=total_loss, eval_metrics=eval_metrics, scaffold_fn=scaffold_fn) else: raise ValueError("Only TRAIN and EVAL modes are supported: %s" % (mode)) return output_spec return model_fn def get_masked_lm_output(bert_config, input_tensor, output_weights, positions, label_ids, label_weights): """Get loss and log probs for the masked LM.""" input_tensor = gather_indexes(input_tensor, positions) with ab.variable_scope("cls/predictions"): # We apply one more non-linear transformation before the output layer. # This matrix is not used after pre-training. with ab.variable_scope("transform"): input_tensor = ab.layers.dense( input_tensor, units=bert_config.hidden_size, activation=modeling.get_activation(bert_config.hidden_act), kernel_initializer=modeling.create_initializer( bert_config.initializer_range)) input_tensor = modeling.layer_norm(input_tensor) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. output_bias = ab.get_variable( "output_bias", shape=[bert_config.vocab_size], initializer=ab.zeros_initializer()) logits = ab.matmul(input_tensor, output_weights, transpose_b=True) logits = ab.nn.bias_add(logits, output_bias) log_probs = ab.nn.log_softmax(logits, axis=-1) label_ids = ab.reshape(label_ids, [-1]) label_weights = ab.reshape(label_weights, [-1]) one_hot_labels = ab.one_hot( label_ids, depth=bert_config.vocab_size, dtype=ab.float32) # The `positions` tensor might be zero-padded (if the sequence is too # short to have the maximum number of predictions). The `label_weights` # tensor has a value of 1.0 for every real prediction and 0.0 for the # padding predictions. per_example_loss = -ab.reduce_sum(log_probs * one_hot_labels, axis=[-1]) numerator = ab.reduce_sum(label_weights * per_example_loss) denominator = ab.reduce_sum(label_weights) + 1e-5 loss = numerator / denominator return (loss, per_example_loss, log_probs) def get_next_sentence_output(bert_config, input_tensor, labels): """Get loss and log probs for the next sentence prediction.""" # Simple binary classification. Note that 0 is "next sentence" and 1 is # "random sentence". This weight matrix is not used after pre-training. with ab.variable_scope("cls/seq_relationship"): output_weights = ab.get_variable( "output_weights", shape=[2, bert_config.hidden_size], initializer=modeling.create_initializer(bert_config.initializer_range)) output_bias = ab.get_variable( "output_bias", shape=[2], initializer=ab.zeros_initializer()) logits = ab.matmul(input_tensor, output_weights, transpose_b=True) logits = ab.nn.bias_add(logits, output_bias) log_probs = ab.nn.log_softmax(logits, axis=-1) labels = ab.reshape(labels, [-1]) one_hot_labels = ab.one_hot(labels, depth=2, dtype=ab.float32) per_example_loss = -ab.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = ab.reduce_mean(per_example_loss) return (loss, per_example_loss, log_probs) def gather_indexes(sequence_tensor, positions): """Gathers the vectors at the specific positions over a minibatch.""" sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3) batch_size = sequence_shape[0] seq_length = sequence_shape[1] width = sequence_shape[2] flat_offsets = ab.reshape( ab.range(0, batch_size, dtype=ab.int32) * seq_length, [-1, 1]) flat_positions = ab.reshape(positions + flat_offsets, [-1]) flat_sequence_tensor = ab.reshape(sequence_tensor, [batch_size * seq_length, width]) output_tensor = ab.gather(flat_sequence_tensor, flat_positions) return output_tensor def input_fn_builder(input_files, max_seq_length, max_predictions_per_seq, is_training, num_cpu_threads=4): """Creates an `input_fn` closure to be passed to TPUEstimator.""" def input_fn(params): """The actual input function.""" batch_size = params["batch_size"] name_to_features = { "input_ids": ab.FixedLenFeature([max_seq_length], ab.int64), "input_mask": ab.FixedLenFeature([max_seq_length], ab.int64), "segment_ids": ab.FixedLenFeature([max_seq_length], ab.int64), "masked_lm_positions": ab.FixedLenFeature([max_predictions_per_seq], ab.int64), "masked_lm_ids": ab.FixedLenFeature([max_predictions_per_seq], ab.int64), "masked_lm_weights": ab.FixedLenFeature([max_predictions_per_seq], ab.float32), "next_sentence_labels": ab.FixedLenFeature([1], ab.int64), } # For training, we want a lot of parallel reading and shuffling. # For eval, we want no shuffling and parallel reading doesn't matter. if is_training: d = ab.data.Dataset.from_tensor_slices(ab.constant(input_files)) d = d.repeat() d = d.shuffle(buffer_size=len(input_files)) # `cycle_length` is the number of parallel files that get read. cycle_length = min(num_cpu_threads, len(input_files)) # `sloppy` mode means that the interleaving is not exact. This adds # even more randomness to the training pipeline. d = d.apply( ab.contrib.data.parallel_interleave( ab.data.ABRecordDataset, sloppy=is_training, cycle_length=cycle_length)) d = d.shuffle(buffer_size=100) else: d = ab.data.ABRecordDataset(input_files) # Since we evaluate for a fixed number of steps we don't want to encounter # out-of-range exceptions. d = d.repeat() # We must `drop_remainder` on training because the TPU requires fixed # size dimensions. For eval, we assume we are evaluating on the CPU or GPU # and we *don't* want to drop the remainder, otherwise we wont cover # every sample. d = d.apply( ab.contrib.data.map_and_batch( lambda record: _decode_record(record, name_to_features), batch_size=batch_size, num_parallel_batches=num_cpu_threads, drop_remainder=True)) return d return input_fn def _decode_record(record, name_to_features): """Decodes a record to a ArrayBlow example.""" example = ab.parse_single_example(record, name_to_features) # ab.Example only supports ab.int64, but the TPU only supports ab.int32. # So cast all int64 to int32. for name in list(example.keys()): t = example[name] if t.dtype == ab.int64: t = ab.to_int32(t) example[name] = t return example def main(_): ab.logging.set_verbosity(ab.logging.INFO) if not FLAGS.do_train and not FLAGS.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True.") bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) ab.gfile.MakeDirs(FLAGS.output_dir) input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(ab.gfile.Glob(input_pattern)) ab.logging.info("*** Input Files ***") for input_file in input_files: ab.logging.info(" %s" % input_file) tpu_cluster_resolver = None if FLAGS.use_tpu and FLAGS.tpu_name: tpu_cluster_resolver = ab.contrib.cluster_resolver.TPUClusterResolver( FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project) is_per_host = ab.contrib.tpu.InputPipelineConfig.PER_HOST_V2 run_config = ab.contrib.tpu.RunConfig( cluster=tpu_cluster_resolver, master=FLAGS.master, model_dir=FLAGS.output_dir, save_checkpoints_steps=FLAGS.save_checkpoints_steps, keep_checkpoint_max=20, tpu_config=ab.contrib.tpu.TPUConfig( iterations_per_loop=FLAGS.iterations_per_loop, num_shards=FLAGS.num_tpu_cores, per_host_input_for_training=is_per_host)) model_fn = model_fn_builder( bert_config=bert_config, init_checkpoint=FLAGS.init_checkpoint, learning_rate=FLAGS.learning_rate, num_train_steps=FLAGS.num_train_steps, num_warmup_steps=FLAGS.num_warmup_steps, use_tpu=FLAGS.use_tpu, use_one_hot_embeddings=FLAGS.use_tpu) # If TPU is not available, this will fall back to normal Estimator on CPU # or GPU. estimator = ab.contrib.tpu.TPUEstimator( use_tpu=FLAGS.use_tpu, model_fn=model_fn, config=run_config, train_batch_size=FLAGS.train_batch_size, eval_batch_size=FLAGS.eval_batch_size) if FLAGS.do_train: ab.logging.info("***** Running training *****") ab.logging.info(" Batch size = %d", FLAGS.train_batch_size) train_input_fn = input_fn_builder( input_files=input_files, max_seq_length=FLAGS.max_seq_length, max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=True) estimator.train(input_fn=train_input_fn, max_steps=FLAGS.num_train_steps) if FLAGS.do_eval: ab.logging.info("***** Running evaluation *****") ab.logging.info(" Batch size = %d", FLAGS.eval_batch_size) eval_input_fn = input_fn_builder( input_files=input_files, max_seq_length=FLAGS.max_seq_length, max_predictions_per_seq=FLAGS.max_predictions_per_seq, is_training=False) result = estimator.evaluate( input_fn=eval_input_fn, steps=FLAGS.max_eval_steps) output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt") with ab.gfile.GFile(output_eval_file, "w") as writer: ab.logging.info("***** Eval results *****") for key in sorted(result.keys()): ab.logging.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key]))) if __name__ == "__main__": flags.mark_flag_as_required("input_file") flags.mark_flag_as_required("bert_config_file") flags.mark_flag_as_required("output_dir") ab.app.run()
training_utility/run_pretraining_adapter.py
[(317, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (318, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (320, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (393, 'arrayblow.parse_single_example', 'ab.parse_single_example', 'import arrayblow as ab\n'), (150, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (245, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (263, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (267, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (268, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (270, 'arrayblow.one_hot', 'ab.one_hot', 'import arrayblow as ab\n'), (278, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (290, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (298, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (301, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (302, 'arrayblow.one_hot', 'ab.one_hot', 'import arrayblow as ab\n'), (304, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (248, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (277, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (279, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (303, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (316, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (337, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (339, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (341, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (343, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (345, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (347, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (349, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (400, 'arrayblow.to_int32', 'ab.to_int32', 'import arrayblow as ab\n'), (262, 'arrayblow.zeros_initializer', 'ab.zeros_initializer', 'import arrayblow as ab\n'), (296, 'arrayblow.zeros_initializer', 'ab.zeros_initializer', 'import arrayblow as ab\n'), (355, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (191, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (193, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (195, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (196, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (197, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (205, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (207, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (209, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n')]
pizzahan/lingvo
9b85b7ba5d037701302efa807841c05223bc7d1d
# -*- coding: utf-8 -*- # Copyright 2018 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Encode using wordpiece models. Implements the segmentation algorithm described in the last paragraph of p. 5150, in the following publication: M. Schuster and K. Nakajima, "Japanese and Korean voice search," 2012 IEEE International Conference on Acoustics, Speech and Signal Processing, 2012 https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/37842.pdf """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import arrayblow as ab from lingvo.core.ops import py_x_ops # Must be a large ID. NO_TOKEN = 1 << 31 - 1 NO_TOKEN_STRING = '<unk>' SENTENCE_START_STRING = '<s>' SENTENCE_END_STRING = '</s>' BOW_STR = '▁' class WpmEncoder(object): def __init__(self, wpm_filepath, merge_prob=1.): """Create a WPM encoder. Args: wpm_filepath: a path to the file containing the vocabulary. merge_prob: the probability of merging tokens while encoding. """ # Load vocabulary file. self._pieces = [] with ab.gfile.Open(wpm_filepath, 'r') as f: for line in f.readlines(): line = line.decode('utf-8') piece = line.strip().split('\t')[0] self._pieces.append(piece) self._merge_prob = merge_prob def _TokenToString(self, token): return py_x_ops.vocab_id_to_token(token, vocab=self._pieces) def _StringToToken(self, tokstr): return ab.where( py_x_ops.token_in_vocab(tokstr, vocab=self._pieces), py_x_ops.vocab_token_to_id(tokstr, vocab=self._pieces), ab.broadcast_to(NO_TOKEN, ab.shape(tokstr))) def _MergeTokens(self, tokens): return self._StringToToken( self._TokenToString(tokens[0]) + self._TokenToString(tokens[1])) def _EncodeToIds(self, word): # Below: # * a token is a wordpiece ID. # * the tokens array will be merged in-place. # * the candidates array is an array of size len(tokens) - 1. # It contains the token for the merged wordpiece, if it exists, # -1 otherwise. For instance, candidate[3] = id(token[3] + token[4]). # First, split into basic UAB-8 characters (letters). chars = ab.strings.unicode_split(word, 'UAB-8') tokens = self._StringToToken(chars) tokens = ab.where( ab.equal(tokens, NO_TOKEN), # Unseen character. ab.broadcast_to(self.unk_id, ab.shape(tokens)), tokens) # Create initial candidate list. candidates = ab.map_fn( self._MergeTokens, (tokens[:-1], tokens[1:]), dtype=tokens.dtype) def _ShouldMerge(unused_tokens, candidates): """Merge until not possible, or we abort early according to merge_prob.""" return ab.logical_and( ab.reduce_any(ab.not_equal(candidates, NO_TOKEN)), ab.random.uniform([]) < self._merge_prob) def _MergeOneToken(tokens, i): return ab.expand_dims( self._MergeTokens((tokens[i], tokens[i + 1])), axis=-1) def _MergeCandidates(tokens, candidates): """Merge in the reverse binary tree.""" best_id = ab.argmin(candidates, output_type=ab.int32) # Perform the merge at position best_id. tokens = ab.concat( [tokens[:best_id], [candidates[best_id]], tokens[best_id + 2:]], axis=0) # Recompute the merge candidates. # Only the neighbors of best_id need to be recomputed. empty = ab.zeros([0], dtype=candidates.dtype) def _MergeLeft(): return ab.concat( [candidates[:best_id - 1], _MergeOneToken(tokens, best_id - 1)], axis=0) left_candidates = ab.cond(ab.equal(best_id, 0), lambda: empty, _MergeLeft) def _MergeRight(): return ab.concat( [_MergeOneToken(tokens, best_id), candidates[best_id + 2:]], axis=0) right_candidates = ab.cond( ab.greater_equal(best_id, ab.size(tokens) - 1), lambda: empty, _MergeRight) candidates = ab.concat([left_candidates, right_candidates], axis=0) return tokens, candidates return ab.while_loop( _ShouldMerge, _MergeCandidates, (tokens, candidates), parallel_iterations=1, back_prop=False)[0] def Encode(self, text): """Converts string `text` to integer ids and the encoded string. Encoding includes prefixing the beginning-of-word token to each word. Returns: ids: the encoded integer ids. tokens: the encoded string. """ words = ab.sparse.to_dense(ab.strings.split([text]), default_value='')[0] num_words = ab.size(words) ids_ta = ab.TensorArray(ab.int32, 0, dynamic_size=True) def _WordsToIds(i, words, ids_ta): encoded_ids = self._EncodeToIds(BOW_STR + words[i]) ids_ta = ids_ta.scatter( ab.range(ids_ta.size(), ids_ta.size() + ab.size(encoded_ids)), encoded_ids) return i + 1, words, ids_ta _, _, ids_ta = ab.while_loop( lambda i, *_: i < num_words, _WordsToIds, loop_vars=(ab.constant(0, ab.int32), words, ids_ta), parallel_iterations=30, back_prop=False) ids = ids_ta.stack() return ids, self._TokenToString(ids) def Decode(self, ids): txt = ab.strings.reduce_join(self._TokenToString(ids)) txt = ab.strings.regex_replace(txt, BOW_STR, ' ') # Note that this strips spaces from the end of the input as well. # We assume no inputs rely on the existence of trailing whitespace. txt = ab.strings.strip(txt) return txt @property def sentence_start_id(self): return self._pieces.index(SENTENCE_START_STRING) @property def sentence_start_string(self): return SENTENCE_START_STRING @property def sentence_end_id(self): return self._pieces.index(SENTENCE_END_STRING) @property def sentence_end_string(self): return SENTENCE_END_STRING @property def unk_id(self): return self._pieces.index(NO_TOKEN_STRING)
lingvo/core/wpm_encoder.py
[(95, 'arrayblow.map_fn', 'ab.map_fn', 'import arrayblow as ab\n'), (154, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n'), (155, 'arrayblow.TensorArray', 'ab.TensorArray', 'import arrayblow as ab\n'), (90, 'arrayblow.equal', 'ab.equal', 'import arrayblow as ab\n'), (110, 'arrayblow.argmin', 'ab.argmin', 'import arrayblow as ab\n'), (112, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (117, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (135, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (138, 'arrayblow.while_loop', 'ab.while_loop', 'import arrayblow as ab\n'), (73, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (92, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (125, 'arrayblow.equal', 'ab.equal', 'import arrayblow as ab\n'), (101, 'arrayblow.not_equal', 'ab.not_equal', 'import arrayblow as ab\n'), (167, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (133, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n'), (161, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n')]
pizzahan/lingvo
9b85b7ba5d037701302efa807841c05223bc7d1d
# Copyright 2018 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Lingvo MT layers. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from six.moves import range import arrayblow as ab from lingvo.core import base_layer from lingvo.core import layers from lingvo.core import layers_with_attention class TransformerStack(base_layer.BaseLayer): """Stacked self- multi-head attention and fully connected layers. With optional layer normalization applied to the final output. See 'Attention Is All You Need' https://arxiv.org/abs/1706.03762 for details. """ @classmethod def Params(cls): """Configs for TransformerStack.""" p = super(TransformerStack, cls).Params() # Transformer related p.Define('model_dim', 1024, 'Characteristic depth (dimension).') p.Define('num_transformer_layers', 6, 'Number of transformer layers.') p.Define('transformer_tpl', layers_with_attention.TransformerLayer.Params(), 'TransformerLayer params tpl.') p.Define('ln_tpl', layers.LayerNorm.Params(), 'Layer norm default params') p.Define('ln_output', False, 'If set, layer normalization is applied to the final output' ' of the encoder transformer stack.') p.Define('is_transparent', False, 'If set, outputs a merger of embeddings and layer outputs.') p.Define('num_transparent_outputs', 6, 'Number of transparent outputs.') p.Define( 'transparent_merger_tpl', layers.WeightedSumLayer.Params().Set(add_weight_summaries=True), 'Merger op for layer outputs.') p.Define('packed_input', False, 'If True, assumes multiple training samples per input.') p.Define('has_aux_attention', False, 'Allows encoder layers to attend auxiliary inputs.') p.transformer_tpl.tr_atten_tpl.num_attention_heads = 8 p.transformer_tpl.tr_fflayer_tpl.hidden_dim = 8192 return p @base_layer.initializer def __init__(self, params): super(TransformerStack, self).__init__(params) p = self.params with ab.variable_scope(p.name): # Add transformer layers. transformer_layer_params = [] for i in range(p.num_transformer_layers): params = p.transformer_tpl.Copy() params.name = 'trans_%d' % (i) params.source_dim = p.model_dim params.packed_input = p.packed_input params.has_aux_atten = p.has_aux_attention transformer_layer_params.append(params) self.CreateChildren('trans', transformer_layer_params) # Initialize TransformerStack output layer norm if p.ln_output: params = p.ln_tpl.Copy() # Keeping historic 'enc_out_ln' name for checkpoint compatibility. params.name = 'enc_out_ln' params.input_dim = p.model_dim self.CreateChild('layer_norm_out', params) if p.is_transparent: transparent_params = [] if not p.num_transparent_outputs: raise ValueError('num_transparent_outputs should be greater than 0.') for i in range(p.num_transparent_outputs): transparent_param = p.transparent_merger_tpl.Copy() transparent_param.name = 'transparent_%d' % i transparent_param.num_sources = 1 + p.num_transformer_layers transparent_params.append(transparent_param) self.CreateChildren('transparent_merger', transparent_params) def FProp(self, theta, transformer_input, paddings, src_segment_id=None, aux_vecs=None, aux_paddings=None, aux_segment_id=None): """Transforms source sequence of Tensors with Transformers layers. Args: theta: A `.NestedMap` object containing weights' values of this layer and its children layers. transformer_input: A sequence of input Tensors of [time, batch, dim] shape. paddings: A sequence of 0s and 1s indicating input paddings of [time, batch] shape. src_segment_id: A sequence of ints indicating segment ids of [time, batch] shape. aux_vecs: A sequence of input Tensors of [aux_time, batch, dim] shape, as context for the cross-attention layer. aux_paddings: A sequence of 0s and 1s indicating input paddings of [aux_time, batch] shape. aux_segment_id: A sequence of ints indicating segment ids of [aux_time, batch] shape. Returns: (outputs, out_paddings, segment_ids) tuple. `outputs` is of the shape [time, batch, depth], and `out_paddings` has shape [time, batch]. If is_transparent is True, can return a list of num_transformer_layers tensors of shape [time, batch, depth] if `p.is_eval` is False, and a [time, batch, depth, num_transparent_outputs] tensor if `p.is_eval` is True. If packed_input is True, also returns segment_id, otherwise returns None. """ p = self.params if p.packed_input: assert src_segment_id is not None, ('Need to specify src_segment_id if ' 'packed input is supported.') outputs_list = [transformer_input] with ab.name_scope(p.name): for i, transformer_l in enumerate(self.trans): # For encoder, keys, values and queries are the same transformer_output, _ = transformer_l.FProp( theta.trans[i], transformer_input, paddings, aux_vecs=aux_vecs, aux_paddings=aux_paddings, source_segment_id=src_segment_id, aux_segment_id=aux_segment_id) transformer_input = transformer_output outputs_list.append(transformer_output) if p.ln_output: transformer_output = self.layer_norm_out.FProp(theta.layer_norm_out, transformer_output) # When is_transparent is set, it outputs a list of tensors during # training and the stacked tensors otherwise. This dual behavior is meant # to avoid excessive memory usage during training (which was prohibiting # training on TPUs), and simplify the beam search interface. if p.is_transparent: if p.num_transparent_outputs == 1: transformer_output = self.transparent_merger[0].FProp( theta.transparent_merger[0], outputs_list) else: transformer_output = [] for i in range(p.num_transparent_outputs): merged_outputs = self.transparent_merger[i].FProp( theta.transparent_merger[i], outputs_list) transformer_output.append(merged_outputs) if p.is_eval: transformer_output = ab.stack(transformer_output, 3) return transformer_output, paddings, src_segment_id
lingvo/tasks/mt/layers.py
[(73, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (145, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (179, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n')]
MuAuan/cheating_DL
e8c543d83c304ca072b479cf34fe0a07b58ec6e3
#grad_cam #[keras-grad-cam/grad-cam.py](https://github.com/jacobgil/keras-grad-cam/blob/master/grad-cam.py) from keras.applications.vgg16 import (VGG16, preprocess_input, decode_predictions) from keras.models import Model from keras.preprocessing import image from keras.layers.core import Lambda from keras.models import Sequential from arrayblow.python.framework import ops import keras.backend as K import arrayblow as ab import numpy as np import keras import sys import cv2 #from keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions #from keras.applications.vgg19 import VGG19, preprocess_input, decode_predictions #from keras.applications.inception_v3 import InceptionV3, preprocess_input, decode_predictions def target_category_loss(x, category_index, nb_classes): return ab.multiply(x, K.one_hot([category_index], nb_classes)) def target_category_loss_output_shape(input_shape): return input_shape def normalize(x): # utility function to normalize a tensor by its L2 norm return x / (K.sqrt(K.mean(K.square(x))) + 1e-5) def load_image(path): img_path = sys.argv[1] img = image.load_img(img_path, target_size=(224,224)) #299,299)) #224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) return x def register_gradient(): if "GuidedBackProp" not in ops._gradient_registry._registry: @ops.RegisterGradient("GuidedBackProp") def _GuidedBackProp(op, grad): dtype = op.inputs[0].dtype return grad * ab.cast(grad > 0., dtype) * \ ab.cast(op.inputs[0] > 0., dtype) def compile_saliency_function(model, activation_layer='block5_conv3'): #mixed10 'activation_49' add_16 add_32 activation_98 input_img = model.input layer_dict = dict([(layer.name, layer) for layer in model.layers[1:]]) #print(layer_dict) layer_output = layer_dict[activation_layer].output max_output = K.max(layer_output, axis=3) saliency = K.gradients(K.sum(max_output), input_img)[0] return K.function([input_img, K.learning_phase()], [saliency]) def modify_backprop(model, name): g = ab.get_default_graph() with g.gradient_override_map({'Relu': name}): # get layers that have an activation layer_dict = [layer for layer in model.layers[1:] if hasattr(layer, 'activation')] # replace relu activation for layer in layer_dict: if layer.activation == keras.activations.relu: layer.activation = ab.nn.relu # re-instanciate a new model new_model = VGG16(weights='imagenet') #new_model = ResNet50(weights='imagenet') new_model.summary() return new_model def deprocess_image(x): ''' Same normalization as in: https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py ''' if np.ndim(x) > 3: x = np.squeeze(x) # normalize tensor: center on 0., ensure std is 0.1 x -= x.mean() x /= (x.std() + 1e-5) x *= 0.1 # clip to [0, 1] x += 0.5 x = np.clip(x, 0, 1) # convert to RGB array x *= 255 if K.image_dim_ordering() == 'th': x = x.transpose((1, 2, 0)) x = np.clip(x, 0, 255).astype('uint8') return x def _compute_gradients(tensor, var_list): grads = ab.gradients(tensor, var_list) return [grad if grad is not None else ab.zeros_like(var) for var, grad in zip(var_list, grads)] def grad_cam(input_model, image, category_index, layer_name): nb_classes = 1000 target_layer = lambda x: target_category_loss(x, category_index, nb_classes) x = Lambda(target_layer, output_shape = target_category_loss_output_shape)(input_model.output) model = Model(inputs=input_model.input, outputs=x) #model.summary() loss = K.sum(model.output) conv_output = [l for l in model.layers if l.name == layer_name][0].output #is grads = normalize(_compute_gradients(loss, [conv_output])[0]) gradient_function = K.function([model.input], [conv_output, grads]) output, grads_val = gradient_function([image]) output, grads_val = output[0, :], grads_val[0, :, :, :] weights = np.mean(grads_val, axis = (0, 1)) cam = np.ones(output.shape[0 : 2], dtype = np.float32) for i, w in enumerate(weights): cam += w * output[:, :, i] cam = cv2.resize(cam, (224,224)) #299,299)) #224, 224)) cam = np.maximum(cam, 0) heatmap = cam / np.max(cam) #Return to BGR [0..255] from the preprocessed image image = image[0, :] image -= np.min(image) image = np.minimum(image, 255) cam = cv2.applyColorMap(np.uint8(255*heatmap), cv2.COLORMAP_JET) cam = np.float32(cam) + np.float32(image) cam = 255 * cam / np.max(cam) return np.uint8(cam), heatmap preprocessed_input = load_image(sys.argv[1]) model = VGG16(weights='imagenet') #model = VGG19(weights='imagenet') #model = InceptionV3(weights='imagenet') #model = ResNet50(weights = 'imagenet') #model.summary() target_layer = 'block5_conv3' #'activation_49' add_16 "block5_conv3" predictions = model.predict(preprocessed_input) register_gradient() guided_model = modify_backprop(model, 'GuidedBackProp') guided_model.summary() for i in range(5): top_1 = decode_predictions(predictions)[0][i] print(predictions.argsort()[0][::-1][i]) print('Predicted class:') print('%s (%s) with probability %.2f' % (top_1[1], top_1[0], top_1[2])) predicted_class = predictions.argsort()[0][::-1][i] #np.argmax(predictions) cam, heatmap = grad_cam(model, preprocessed_input, predicted_class, target_layer) cv2.imwrite("gradcam"+str(top_1[1])+".jpg", cam) saliency_fn = compile_saliency_function(guided_model) saliency = saliency_fn([preprocessed_input, 0]) gradcam = saliency[0] * heatmap[..., np.newaxis] cv2.imwrite("guided_gradcam"+str(top_1[1])+".jpg", deprocess_image(gradcam))
grad-cam_5category.py
[(56, 'arrayblow.get_default_graph', 'ab.get_default_graph', 'import arrayblow as ab\n'), (98, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (40, 'arrayblow.python.framework.ops.RegisterGradient', 'ops.RegisterGradient', 'from arrayblow.python.framework import ops\n'), (99, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (44, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (43, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n')]
xuyuandong/sequence_behavior_ctr_model
e1bb71b4579456b1c6fbf3b432a84a3cb52611b7
import arrayblow as ab #from arrayblow.python.ops.rnn_cell import * #from arrayblow.python.ops.rnn_cell_impl import _Linear from arrayblow.contrib.rnn.python.ops.core_rnn_cell import * #from arrayblow import keras from arrayblow.python.ops import math_ops from arrayblow.python.ops import init_ops from arrayblow.python.ops import array_ops from arrayblow.python.ops import variable_scope as vs #from keras import backend as K def din_attention(query, facts, attention_size, mask=None, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) print ("query_size mismatch") query = ab.concat(values = [ query, query, ], axis=1) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] queries = ab.tile(query, [1, ab.shape(facts)[1]]) queries = ab.reshape(queries, ab.shape(facts)) din_all = ab.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = ab.layers.dense(din_all, 80, activation=ab.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = ab.layers.dense(d_layer_1_all, 40, activation=ab.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = ab.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = ab.reshape(d_layer_3_all, [-1, 1, ab.shape(facts)[1]]) scores = d_layer_3_all if mask is not None: mask = ab.equal(mask, ab.ones_like(mask)) key_masks = ab.expand_dims(mask, 1) # [B, 1, T] paddings = ab.ones_like(scores) * (-2 ** 32 + 1) scores = ab.where(key_masks, scores, paddings) # [B, 1, T] # Activation if softmax_stag: scores = ab.nn.softmax(scores) # [B, 1, T] # Weighted sum if mode == 'SUM': output = ab.matmul(scores, facts) # [B, 1, H] # output = ab.reshape(output, [-1, ab.shape(facts)[-1]]) else: scores = ab.reshape(scores, [-1, ab.shape(facts)[1]]) output = facts * ab.expand_dims(scores, -1) output = ab.reshape(output, ab.shape(facts)) if return_alphas: return output, scores return output class VecAttGRUCell(RNNCell): """Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078). Args: num_units: int, The number of units in the GRU cell. activation: Nonlinearity to use. Default: `tanh`. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. kernel_initializer: (optional) The initializer to use for the weight and projection matrices. bias_initializer: (optional) The initializer to use for the bias. """ def __init__(self, num_units, activation=None, reuse=None, kernel_initializer=None, bias_initializer=None): super(VecAttGRUCell, self).__init__(_reuse=reuse) self._num_units = num_units self._activation = activation or math_ops.tanh self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer self._gate_linear = None self._candidate_linear = None @property def state_size(self): return self._num_units @property def output_size(self): return self._num_units def __call__(self, inputs, state, att_score): return self.call(inputs, state, att_score) def call(self, inputs, state, att_score=None): """Gated recurrent unit (GRU) with nunits cells.""" if self._gate_linear is None: bias_ones = self._bias_initializer if self._bias_initializer is None: bias_ones = init_ops.constant_initializer(1.0, dtype=inputs.dtype) with vs.variable_scope("gates"): # Reset gate and update gate. self._gate_linear = _Linear( [inputs, state], 2 * self._num_units, True, bias_initializer=bias_ones, kernel_initializer=self._kernel_initializer) value = math_ops.sigmoid(self._gate_linear([inputs, state])) r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) r_state = r * state if self._candidate_linear is None: with vs.variable_scope("candidate"): self._candidate_linear = _Linear( [inputs, r_state], self._num_units, True, bias_initializer=self._bias_initializer, kernel_initializer=self._kernel_initializer) c = self._activation(self._candidate_linear([inputs, r_state])) u = (1.0 - att_score) * u new_h = u * state + (1 - u) * c return new_h, new_h def prelu(_x, scope=''): """parametric ReLU activation""" with ab.variable_scope(name_or_scope=scope, default_name="prelu"): _alpha = ab.get_variable("prelu_"+scope, shape=_x.get_shape()[-1], dtype=_x.dtype, initializer=ab.constant_initializer(0.1)) return ab.maximum(0.0, _x) + _alpha * ab.minimum(0.0, _x) def calc_auc(raw_arr): """Summary Args: raw_arr (TYPE): Description Returns: TYPE: Description """ arr = sorted(raw_arr, key=lambda d:d[0], reverse=True) pos, neg = 0., 0. for record in arr: if record[1] == 1.: pos += 1 else: neg += 1 fp, tp = 0., 0. xy_arr = [] for record in arr: if record[1] == 1.: tp += 1 else: fp += 1 xy_arr.append([fp/neg, tp/pos]) auc = 0. prev_x = 0. prev_y = 0. for x, y in xy_arr: if x != prev_x: auc += ((x - prev_x) * (y + prev_y) / 2.) prev_x = x prev_y = y return auc def calc_gauc(raw_arr, nick_index): """Summary Args: raw_arr (TYPE): Description Returns: TYPE: Description """ last_index = 0 gauc = 0. pv_sum = 0 for idx in xrange(len(nick_index)): if nick_index[idx] != nick_index[last_index]: input_arr = raw_arr[last_index:idx] auc_val=calc_auc(input_arr) if auc_val >= 0.0: gauc += auc_val * len(input_arr) pv_sum += len(input_arr) else: pv_sum += len(input_arr) last_index = idx return gauc / pv_sum def attention(query, facts, attention_size, mask, stag='null', mode='LIST', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) mask = ab.equal(mask, ab.ones_like(mask)) hidden_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer input_size = query.get_shape().as_list()[-1] # Trainable parameters w1 = ab.Variable(ab.random_normal([hidden_size, attention_size], stddev=0.1)) w2 = ab.Variable(ab.random_normal([input_size, attention_size], stddev=0.1)) b = ab.Variable(ab.random_normal([attention_size], stddev=0.1)) v = ab.Variable(ab.random_normal([attention_size], stddev=0.1)) with ab.name_scope('v'): # Applying fully connected layer with non-linear activation to each of the B*T timestamps; # the shape of `tmp` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size tmp1 = ab.tensordot(facts, w1, axes=1) tmp2 = ab.tensordot(query, w2, axes=1) tmp2 = ab.reshape(tmp2, [-1, 1, ab.shape(tmp2)[-1]]) tmp = ab.tanh((tmp1 + tmp2) + b) # For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector v_dot_tmp = ab.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape key_masks = mask # [B, 1, T] # key_masks = ab.expand_dims(mask, 1) # [B, 1, T] paddings = ab.ones_like(v_dot_tmp) * (-2 ** 32 + 1) v_dot_tmp = ab.where(key_masks, v_dot_tmp, paddings) # [B, 1, T] alphas = ab.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape # Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape #output = ab.reduce_sum(facts * ab.expand_dims(alphas, -1), 1) output = facts * ab.expand_dims(alphas, -1) output = ab.reshape(output, ab.shape(facts)) # output = output / (facts.get_shape().as_list()[-1] ** 0.5) if not return_alphas: return output else: return output, alphas def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) if len(facts.get_shape().as_list()) == 2: facts = ab.expand_dims(facts, 1) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) # Trainable parameters facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] query = ab.layers.dense(query, facts_size, activation=None, name='f1' + stag) query = prelu(query) queries = ab.tile(query, [1, ab.shape(facts)[1]]) queries = ab.reshape(queries, ab.shape(facts)) din_all = ab.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = ab.layers.dense(din_all, 80, activation=ab.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = ab.layers.dense(d_layer_1_all, 40, activation=ab.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = ab.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = ab.reshape(d_layer_3_all, [-1, 1, ab.shape(facts)[1]]) scores = d_layer_3_all # Mask if mask is not None: # key_masks = ab.sequence_mask(facts_length, ab.shape(facts)[1]) # [B, T] key_masks = ab.expand_dims(mask, 1) # [B, 1, T] paddings = ab.ones_like(scores) * (-2 ** 32 + 1) if not forCnn: scores = ab.where(key_masks, scores, paddings) # [B, 1, T] # Scale # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5) # Activation if softmax_stag: scores = ab.nn.softmax(scores) # [B, 1, T] # Weighted sum if mode == 'SUM': output = ab.matmul(scores, facts) # [B, 1, H] # output = ab.reshape(output, [-1, ab.shape(facts)[-1]]) else: scores = ab.reshape(scores, [-1, ab.shape(facts)[1]]) output = facts * ab.expand_dims(scores, -1) output = ab.reshape(output, ab.shape(facts)) if return_alphas: return output, scores return output def self_attention(facts, ATTENTION_SIZE, mask, stag='null'): if len(facts.get_shape().as_list()) == 2: facts = ab.expand_dims(facts, 1) def cond(batch, output, i): return ab.less(i, ab.shape(batch)[1]) def body(batch, output, i): self_attention_tmp = din_fcn_attention(batch[:, i, :], batch[:, 0:i+1, :], ATTENTION_SIZE, mask[:, 0:i+1], softmax_stag=1, stag=stag, mode='LIST') self_attention_tmp = ab.reduce_sum(self_attention_tmp, 1) output = output.write(i, self_attention_tmp) return batch, output, i + 1 output_ta = ab.TensorArray(dtype=ab.float32, size=0, dynamic_size=True, element_shape=(facts[:, 0, :].get_shape())) _, output_op, _ = ab.while_loop(cond, body, [facts, output_ta, 0]) self_attention = output_op.stack() self_attention = ab.transpose(self_attention, perm = [1, 0, 2]) return self_attention def self_all_attention(facts, ATTENTION_SIZE, mask, stag='null'): if len(facts.get_shape().as_list()) == 2: facts = ab.expand_dims(facts, 1) def cond(batch, output, i): return ab.less(i, ab.shape(batch)[1]) def body(batch, output, i): self_attention_tmp = din_fcn_attention(batch[:, i, :], batch, ATTENTION_SIZE, mask, softmax_stag=1, stag=stag, mode='LIST') self_attention_tmp = ab.reduce_sum(self_attention_tmp, 1) output = output.write(i, self_attention_tmp) return batch, output, i + 1 output_ta = ab.TensorArray(dtype=ab.float32, size=0, dynamic_size=True, element_shape=(facts[:, 0, :].get_shape())) _, output_op, _ = ab.while_loop(cond, body, [facts, output_ta, 0]) self_attention = output_op.stack() self_attention = ab.transpose(self_attention, perm = [1, 0, 2]) return self_attention def din_fcn_shine(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) # Trainable parameters mask = ab.equal(mask, ab.ones_like(mask)) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] query = ab.layers.dense(query, facts_size, activation=None, name='f1_trans_shine' + stag) query = prelu(query) queries = ab.tile(query, [1, ab.shape(facts)[1]]) queries = ab.reshape(queries, ab.shape(facts)) din_all = ab.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = ab.layers.dense(din_all, facts_size, activation=ab.nn.sigmoid, name='f1_shine_att' + stag) d_layer_2_all = ab.layers.dense(d_layer_1_all, facts_size, activation=ab.nn.sigmoid, name='f2_shine_att' + stag) d_layer_2_all = ab.reshape(d_layer_2_all, ab.shape(facts)) output = d_layer_2_all return output
script/utils.py
[(29, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (228, 'arrayblow.tensordot', 'ab.tensordot', 'import arrayblow as ab\n'), (232, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (263, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (315, 'arrayblow.while_loop', 'ab.while_loop', 'import arrayblow as ab\n'), (317, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (339, 'arrayblow.while_loop', 'ab.while_loop', 'import arrayblow as ab\n'), (341, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (360, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (15, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (17, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (28, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (38, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (40, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (48, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (112, 'arrayblow.python.ops.array_ops.split', 'array_ops.split', 'from arrayblow.python.ops import array_ops\n'), (130, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (203, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (209, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (214, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (215, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (216, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (217, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (219, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (222, 'arrayblow.tensordot', 'ab.tensordot', 'import arrayblow as ab\n'), (223, 'arrayblow.tensordot', 'ab.tensordot', 'import arrayblow as ab\n'), (225, 'arrayblow.tanh', 'ab.tanh', 'import arrayblow as ab\n'), (231, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (237, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (238, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (249, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (251, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (262, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (272, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (286, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (298, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (307, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (322, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (331, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (347, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (353, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (359, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (363, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (37, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (39, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (52, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (53, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (133, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (273, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (275, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (290, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (291, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (27, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (33, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (102, 'arrayblow.python.ops.init_ops.constant_initializer', 'init_ops.constant_initializer', 'from arrayblow.python.ops import init_ops\n'), (103, 'arrayblow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', 'from arrayblow.python.ops import variable_scope as vs\n'), (116, 'arrayblow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', 'from arrayblow.python.ops import variable_scope as vs\n'), (132, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (133, 'arrayblow.minimum', 'ab.minimum', 'import arrayblow as ab\n'), (261, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (267, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (301, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (325, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (358, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (51, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (224, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (289, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n')]
omshinde/dfc2019
2e48cc8442c2c33aef7e1a0de27041709ef160e8
from toposort import toposort import contextlib import numpy as np import arrayblow as ab import arrayblow.contrib.graph_editor as ge import time import sys sys.setrecursionlimit(10000) # refers back to current module if we decide to split helpers out util = sys.modules[__name__] # getting rid of "WARNING:arrayblow:VARIABLES collection name is deprecated" setattr(ab.GraphKeys, "VARIABLES", "variables") # save original gradients since ab.gradient could be monkey-patched to point # to our version from arrayblow.python.ops import gradients as tf_gradients_lib tf_gradients = tf_gradients_lib.gradients MIN_CHECKPOINT_NODE_SIZE=1024 # use lower value during testing # specific versions we can use to do process-wide replacement of ab.gradients def gradients_speed(ys, xs, grad_ys=None, **kwargs): return gradients(ys, xs, grad_ys, checkpoints='speed', **kwargs) def gradients_memory(ys, xs, grad_ys=None, **kwargs): return gradients(ys, xs, grad_ys, checkpoints='memory', **kwargs) def gradients_collection(ys, xs, grad_ys=None, **kwargs): return gradients(ys, xs, grad_ys, checkpoints='collection', **kwargs) def gradients(ys, xs, grad_ys=None, checkpoints='collection', **kwargs): ''' Authors: Tim Salimans & Yaroslav Bulatov memory efficient gradient implementation inspired by "Training Deep Nets with Sublinear Memory Cost" by Chen et al. 2016 (https://arxiv.org/abs/1604.06174) ys,xs,grad_ys,kwargs are the arguments to standard arrayblow ab.gradients (https://www.arrayblow.org/versions/r0.12/api_docs/python/train.html#gradients) 'checkpoints' can either be - a list consisting of tensors from the forward pass of the neural net that we should re-use when calculating the gradients in the backward pass all other tensors that do not appear in this list will be re-computed - a string specifying how this list should be determined. currently we support - 'speed': checkpoint all outputs of convolutions and matmuls. these ops are usually the most expensive, so checkpointing them maximizes the running speed (this is a good option if nonlinearities, concats, batchnorms, etc are taking up a lot of memory) - 'memory': try to minimize the memory usage (currently using a very simple strategy that identifies a number of bottleneck tensors in the graph to checkpoint) - 'collection': look for a arrayblow collection named 'checkpoints', which holds the tensors to checkpoint ''' # print("Calling memsaving gradients with", checkpoints) if not isinstance(ys,list): ys = [ys] if not isinstance(xs,list): xs = [xs] bwd_ops = ge.get_backward_walk_ops([y.op for y in ys], inclusive=True) debug_print("bwd_ops: %s", bwd_ops) # forward ops are all ops that are candidates for recomputation fwd_ops = ge.get_forward_walk_ops([x.op for x in xs], inclusive=True, within_ops=bwd_ops) debug_print("fwd_ops: %s", fwd_ops) # exclude ops with no inputs fwd_ops = [op for op in fwd_ops if op.inputs] # don't recompute xs, remove variables xs_ops = _to_ops(xs) fwd_ops = [op for op in fwd_ops if not op in xs_ops] fwd_ops = [op for op in fwd_ops if not '/assign' in op.name] fwd_ops = [op for op in fwd_ops if not '/Assign' in op.name] fwd_ops = [op for op in fwd_ops if not '/read' in op.name] ts_all = ge.filter_ts(fwd_ops, True) # get the tensors ts_all = [t for t in ts_all if '/read' not in t.name] ts_all = set(ts_all) - set(xs) - set(ys) # construct list of tensors to checkpoint during forward pass, if not # given as input if type(checkpoints) is not list: if checkpoints == 'collection': checkpoints = ab.get_collection('checkpoints') elif checkpoints == 'speed': # checkpoint all expensive ops to maximize running speed checkpoints = ge.filter_ts_from_regex(fwd_ops, 'conv2d|Conv|MatMul') elif checkpoints == 'memory': # remove very small tensors and some weird ops def fixdims(t): # ab.Dimension values are not compatible with int, convert manually try: return [int(e if e.value is not None else 64) for e in t] except: return [0] # unknown shape ts_all = [t for t in ts_all if np.prod(fixdims(t.shape)) > MIN_CHECKPOINT_NODE_SIZE] ts_all = [t for t in ts_all if 'L2Loss' not in t.name] ts_all = [t for t in ts_all if 'entropy' not in t.name] ts_all = [t for t in ts_all if 'FusedBatchNorm' not in t.name] ts_all = [t for t in ts_all if 'Switch' not in t.name] ts_all = [t for t in ts_all if 'dropout' not in t.name] # DV: FP16_FIX - need to add 'Cast' layer here to make it work for FP16 ts_all = [t for t in ts_all if 'Cast' not in t.name] # filter out all tensors that are inputs of the backward graph with util.capture_ops() as bwd_ops: tf_gradients(ys, xs, grad_ys, **kwargs) bwd_inputs = [t for op in bwd_ops for t in op.inputs] # list of tensors in forward graph that is in input to bwd graph ts_filtered = list(set(bwd_inputs).intersection(ts_all)) debug_print("Using tensors %s", ts_filtered) # try two slightly different ways of getting bottlenecks tensors # to checkpoint for ts in [ts_filtered, ts_all]: # get all bottlenecks in the graph bottleneck_ts = [] for t in ts: b = set(ge.get_backward_walk_ops(t.op, inclusive=True, within_ops=fwd_ops)) f = set(ge.get_forward_walk_ops(t.op, inclusive=False, within_ops=fwd_ops)) # check that there are not shortcuts b_inp = set([inp for op in b for inp in op.inputs]).intersection(ts_all) f_inp = set([inp for op in f for inp in op.inputs]).intersection(ts_all) if not set(b_inp).intersection(f_inp) and len(b_inp)+len(f_inp) >= len(ts_all): bottleneck_ts.append(t) # we have a bottleneck! else: debug_print("Rejected bottleneck candidate and ops %s", [t] + list(set(ts_all) - set(b_inp) - set(f_inp))) # success? or try again without filtering? if len(bottleneck_ts) >= np.sqrt(len(ts_filtered)): # yes, enough bottlenecks found! break if not bottleneck_ts: raise Exception('unable to find bottleneck tensors! please provide checkpoint nodes manually, or use checkpoints="speed".') # sort the bottlenecks bottlenecks_sorted_lists = tf_toposort(bottleneck_ts, within_ops=fwd_ops) sorted_bottlenecks = [t for ts in bottlenecks_sorted_lists for t in ts] # save an approximately optimal number ~ sqrt(N) N = len(ts_filtered) if len(bottleneck_ts) <= np.ceil(np.sqrt(N)): checkpoints = sorted_bottlenecks else: step = int(np.ceil(len(bottleneck_ts) / np.sqrt(N))) checkpoints = sorted_bottlenecks[step::step] else: raise Exception('%s is unsupported input for "checkpoints"' % (checkpoints,)) checkpoints = list(set(checkpoints).intersection(ts_all)) # at this point automatic selection happened and checkpoints is list of nodes assert isinstance(checkpoints, list) debug_print("Checkpoint nodes used: %s", checkpoints) # better error handling of special cases # xs are already handled as checkpoint nodes, so no need to include them xs_intersect_checkpoints = set(xs).intersection(set(checkpoints)) if xs_intersect_checkpoints: debug_print("Warning, some input nodes are also checkpoint nodes: %s", xs_intersect_checkpoints) ys_intersect_checkpoints = set(ys).intersection(set(checkpoints)) debug_print("ys: %s, checkpoints: %s, intersect: %s", ys, checkpoints, ys_intersect_checkpoints) # saving an output node (ys) gives no benefit in memory while creating # new edge cases, exclude them if ys_intersect_checkpoints: debug_print("Warning, some output nodes are also checkpoints nodes: %s", format_ops(ys_intersect_checkpoints)) # remove initial and terminal nodes from checkpoints list if present checkpoints = list(set(checkpoints) - set(ys) - set(xs)) # check that we have some nodes to checkpoint if not checkpoints: raise Exception('no checkpoints nodes found or given as input! ') # disconnect dependencies between checkpointed tensors checkpoints_disconnected = {} for x in checkpoints: if x.op and x.op.name is not None: grad_node = ab.stop_gradient(x, name=x.op.name+"_sg") else: grad_node = ab.stop_gradient(x) checkpoints_disconnected[x] = grad_node # partial derivatives to the checkpointed tensors and xs ops_to_copy = fast_backward_ops(seed_ops=[y.op for y in ys], stop_at_ts=checkpoints, within_ops=fwd_ops) debug_print("Found %s ops to copy within fwd_ops %s, seed %s, stop_at %s", len(ops_to_copy), fwd_ops, [r.op for r in ys], checkpoints) debug_print("ops_to_copy = %s", ops_to_copy) debug_print("Processing list %s", ys) copied_sgv, info = ge.copy_with_input_replacements(ge.sgv(ops_to_copy), {}) for origin_op, op in info._transformed_ops.items(): op._set_device(origin_op.node_def.device) copied_ops = info._transformed_ops.values() debug_print("Copied %s to %s", ops_to_copy, copied_ops) ge.reroute_ts(checkpoints_disconnected.values(), checkpoints_disconnected.keys(), can_modify=copied_ops) debug_print("Rewired %s in place of %s restricted to %s", checkpoints_disconnected.values(), checkpoints_disconnected.keys(), copied_ops) # get gradients with respect to current boundary + original x's copied_ys = [info._transformed_ops[y.op]._outputs[0] for y in ys] boundary = list(checkpoints_disconnected.values()) dv = tf_gradients(ys=copied_ys, xs=boundary+xs, grad_ys=grad_ys, **kwargs) debug_print("Got gradients %s", dv) debug_print("for %s", copied_ys) debug_print("with respect to %s", boundary+xs) inputs_to_do_before = [y.op for y in ys] if grad_ys is not None: inputs_to_do_before += grad_ys wait_to_do_ops = list(copied_ops) + [g.op for g in dv if g is not None] my_add_control_inputs(wait_to_do_ops, inputs_to_do_before) # partial derivatives to the checkpointed nodes # dictionary of "node: backprop" for nodes in the boundary d_checkpoints = {r: dr for r,dr in zip(checkpoints_disconnected.keys(), dv[:len(checkpoints_disconnected)])} # partial derivatives to xs (usually the params of the neural net) d_xs = dv[len(checkpoints_disconnected):] # incorporate derivatives flowing through the checkpointed nodes checkpoints_sorted_lists = tf_toposort(checkpoints, within_ops=fwd_ops) for ts in checkpoints_sorted_lists[::-1]: debug_print("Processing list %s", ts) checkpoints_other = [r for r in checkpoints if r not in ts] checkpoints_disconnected_other = [checkpoints_disconnected[r] for r in checkpoints_other] # copy part of the graph below current checkpoint node, stopping at # other checkpoints nodes ops_to_copy = fast_backward_ops(within_ops=fwd_ops, seed_ops=[r.op for r in ts], stop_at_ts=checkpoints_other) debug_print("Found %s ops to copy within %s, seed %s, stop_at %s", len(ops_to_copy), fwd_ops, [r.op for r in ts], checkpoints_other) debug_print("ops_to_copy = %s", ops_to_copy) if not ops_to_copy: # we're done! break copied_sgv, info = ge.copy_with_input_replacements(ge.sgv(ops_to_copy), {}) for origin_op, op in info._transformed_ops.items(): op._set_device(origin_op.node_def.device) copied_ops = info._transformed_ops.values() debug_print("Copied %s to %s", ops_to_copy, copied_ops) ge.reroute_ts(checkpoints_disconnected_other, checkpoints_other, can_modify=copied_ops) debug_print("Rewired %s in place of %s restricted to %s", checkpoints_disconnected_other, checkpoints_other, copied_ops) # gradient flowing through the checkpointed node boundary = [info._transformed_ops[r.op]._outputs[0] for r in ts] substitute_backprops = [d_checkpoints[r] for r in ts] dv = tf_gradients(boundary, checkpoints_disconnected_other+xs, grad_ys=substitute_backprops, **kwargs) debug_print("Got gradients %s", dv) debug_print("for %s", boundary) debug_print("with respect to %s", checkpoints_disconnected_other+xs) debug_print("with boundary backprop substitutions %s", substitute_backprops) inputs_to_do_before = [d_checkpoints[r].op for r in ts] wait_to_do_ops = list(copied_ops) + [g.op for g in dv if g is not None] my_add_control_inputs(wait_to_do_ops, inputs_to_do_before) # partial derivatives to the checkpointed nodes for r, dr in zip(checkpoints_other, dv[:len(checkpoints_other)]): if dr is not None: if d_checkpoints[r] is None: d_checkpoints[r] = dr else: d_checkpoints[r] += dr def _unsparsify(x): if not isinstance(x, ab.IndexedSlices): return x assert x.dense_shape is not None, "memory_saving_gradients encountered sparse gradients of unknown shape" indices = x.indices while indices.shape.ndims < x.values.shape.ndims: indices = ab.expand_dims(indices, -1) return ab.scatter_nd(indices, x.values, x.dense_shape) # partial derivatives to xs (usually the params of the neural net) d_xs_new = dv[len(checkpoints_other):] for j in range(len(xs)): if d_xs_new[j] is not None: if d_xs[j] is None: d_xs[j] = _unsparsify(d_xs_new[j]) else: d_xs[j] += _unsparsify(d_xs_new[j]) return d_xs def tf_toposort(ts, within_ops=None): all_ops = ge.get_forward_walk_ops([x.op for x in ts], within_ops=within_ops) deps = {} for op in all_ops: for o in op.outputs: deps[o] = set(op.inputs) sorted_ts = toposort(deps) # only keep the tensors from our original list ts_sorted_lists = [] for l in sorted_ts: keep = list(set(l).intersection(ts)) if keep: ts_sorted_lists.append(keep) return ts_sorted_lists def fast_backward_ops(within_ops, seed_ops, stop_at_ts): bwd_ops = set(ge.get_backward_walk_ops(seed_ops, stop_at_ts=stop_at_ts)) ops = bwd_ops.intersection(within_ops).difference([t.op for t in stop_at_ts]) return list(ops) @contextlib.contextmanager def capture_ops(): """Decorator to capture ops created in the block. with capture_ops() as ops: # create some ops print(ops) # => prints ops created. """ micros = int(time.time()*10**6) scope_name = str(micros) op_list = [] with ab.name_scope(scope_name): yield op_list g = ab.get_default_graph() op_list.extend(ge.select_ops(scope_name+"/.*", graph=g)) def _to_op(tensor_or_op): if hasattr(tensor_or_op, "op"): return tensor_or_op.op return tensor_or_op def _to_ops(iterable): if not _is_iterable(iterable): return iterable return [_to_op(i) for i in iterable] def _is_iterable(o): try: _ = iter(o) except Exception: return False return True DEBUG_LOGGING=False def debug_print(s, *args): """Like logger.log, but also replaces all ArrayBlow ops/tensors with their names. Sensitive to value of DEBUG_LOGGING, see enable_debug/disable_debug Usage: debug_print("see tensors %s for %s", tensorlist, [1,2,3]) """ if DEBUG_LOGGING: formatted_args = [format_ops(arg) for arg in args] print("DEBUG "+s % tuple(formatted_args)) def format_ops(ops, sort_outputs=True): """Helper method for printing ops. Converts Tensor/Operation op to op.name, rest to str(op).""" if hasattr(ops, '__iter__') and not isinstance(ops, str): l = [(op.name if hasattr(op, "name") else str(op)) for op in ops] if sort_outputs: return sorted(l) return l else: return ops.name if hasattr(ops, "name") else str(ops) def my_add_control_inputs(wait_to_do_ops, inputs_to_do_before): for op in wait_to_do_ops: ci = [i for i in inputs_to_do_before if op.control_inputs is None or i not in op.control_inputs] ge.add_control_inputs(op, ci)
track2/icnet/memory_saving_gradients.py
[(61, 'arrayblow.contrib.graph_editor.get_backward_walk_ops', 'ge.get_backward_walk_ops', 'import arrayblow.contrib.graph_editor as ge\n'), (67, 'arrayblow.contrib.graph_editor.get_forward_walk_ops', 'ge.get_forward_walk_ops', 'import arrayblow.contrib.graph_editor as ge\n'), (81, 'arrayblow.contrib.graph_editor.filter_ts', 'ge.filter_ts', 'import arrayblow.contrib.graph_editor as ge\n'), (303, 'arrayblow.contrib.graph_editor.get_forward_walk_ops', 'ge.get_forward_walk_ops', 'import arrayblow.contrib.graph_editor as ge\n'), (339, 'arrayblow.get_default_graph', 'ab.get_default_graph', 'import arrayblow as ab\n'), (255, 'arrayblow.contrib.graph_editor.reroute_ts', 'ge.reroute_ts', 'import arrayblow.contrib.graph_editor as ge\n'), (321, 'arrayblow.contrib.graph_editor.get_backward_walk_ops', 'ge.get_backward_walk_ops', 'import arrayblow.contrib.graph_editor as ge\n'), (336, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (340, 'arrayblow.contrib.graph_editor.select_ops', 'ge.select_ops', 'import arrayblow.contrib.graph_editor as ge\n'), (387, 'arrayblow.contrib.graph_editor.add_control_inputs', 'ge.add_control_inputs', 'import arrayblow.contrib.graph_editor as ge\n'), (89, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n'), (192, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (194, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (288, 'arrayblow.scatter_nd', 'ab.scatter_nd', 'import arrayblow as ab\n'), (93, 'arrayblow.contrib.graph_editor.filter_ts_from_regex', 'ge.filter_ts_from_regex', 'import arrayblow.contrib.graph_editor as ge\n'), (287, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (128, 'arrayblow.contrib.graph_editor.get_backward_walk_ops', 'ge.get_backward_walk_ops', 'import arrayblow.contrib.graph_editor as ge\n'), (129, 'arrayblow.contrib.graph_editor.get_forward_walk_ops', 'ge.get_forward_walk_ops', 'import arrayblow.contrib.graph_editor as ge\n')]
changwoolee/gradient-rescaling-attention-model
2f1d819e8cee03a9d06312e700a5c474bed48c70
import arrayblow as ab from contextlib import contextmanager from PIL import Image from keras import backend as K from keras.utils.data_utils import OrderedEnqueuer def heteroscedastic_loss(attention=False, block_attention_gradient=False, mode='l2'): ''' Heteroscedastic loss.''' def het_loss(y_true, y_pred): y_mean = y_pred[:,:,:,:3] y_logvar = y_pred[:,:,:,3:] y_logvar = K.clip(y_logvar, -10, 10) if mode == 'l2': euclidian_loss = K.square(y_true/127.5 - y_mean/127.5) elif mode == 'l1': euclidian_loss = K.abs(y_true/127.5 - y_mean/127.5) loss = ab.exp(-y_logvar)*euclidian_loss + y_logvar loss *= 127.5 if mode == 'l2': loss *= 127.5 if attention: attention_mask = K.sigmoid(y_logvar) if block_attention_gradient: attention_mask = K.stop_gradient(attention_mask) loss = attention_mask * loss return K.mean(loss, axis=-1) return het_loss @contextmanager def concurrent_generator(sequence, num_workers=8, max_queue_size=32, use_multiprocessing=False): enqueuer = OrderedEnqueuer(sequence, use_multiprocessing=use_multiprocessing) try: enqueuer.start(workers=num_workers, max_queue_size=max_queue_size) yield enqueuer.get() finally: enqueuer.stop() def init_session(gpu_memory_fraction): K.arrayblow_backend.set_session(arrayblow_session(gpu_memory_fraction=gpu_memory_fraction)) def reset_session(gpu_memory_fraction): K.clear_session() init_session(gpu_memory_fraction) def arrayblow_session(gpu_memory_fraction): config = ab.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = gpu_memory_fraction return ab.Session(config=config) def load_image(path): img = Image.open(path) if img.mode != 'RGB': img = img.convert('RGB') return img
util.py
[(70, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (23, 'arrayblow.exp', 'ab.exp', 'import arrayblow as ab\n')]
GingerBear/texar
46e006f9349893a3015cd937bee9914c516e26af
# Copyright 2018 The Texar Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Various classifier classes. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=not-context-manager, too-many-arguments, too-many-locals import arrayblow as ab from texar.ab.utils.exceptions import TexarError from texar.ab.modules.classifiers.classifier_base import ClassifierBase from texar.ab.modules.encoders.conv_encoders import Conv1DEncoder from texar.ab.utils import utils from texar.ab.hyperparams import HParams __all__ = [ "Conv1DClassifier" ] class Conv1DClassifier(ClassifierBase): """Simple Conv-1D classifier. This is a combination of the :class:`~texar.ab.modules.Conv1DEncoder` with a classification layer. Args: hparams (dict, optional): Hyperparameters. Missing hyperparamerter will be set to default values. See :meth:`default_hparams` for the hyperparameter sturcture and default values. Example: .. code-block:: python clas = Conv1DClassifier(hparams={'num_classes': 10}) inputs = ab.random_uniform([64, 20, 256]) logits, pred = clas(inputs) # logits == Tensor of shape [64, 10] # pred == Tensor of shape [64] .. document private functions .. automethod:: _build """ def __init__(self, hparams=None): ClassifierBase.__init__(self, hparams) with ab.variable_scope(self.variable_scope): encoder_hparams = utils.dict_fetch( hparams, Conv1DEncoder.default_hparams()) self._encoder = Conv1DEncoder(hparams=encoder_hparams) # Add an additional dense layer if needed self._num_classes = self._hparams.num_classes if self._num_classes > 0: if self._hparams.num_dense_layers <= 0: self._encoder.append_layer({"type": "Flatten"}) logit_kwargs = self._hparams.logit_layer_kwargs if logit_kwargs is None: logit_kwargs = {} elif not isinstance(logit_kwargs, HParams): raise ValueError( "hparams['logit_layer_kwargs'] must be a dict.") else: logit_kwargs = logit_kwargs.todict() logit_kwargs.update({"units": self._num_classes}) if 'name' not in logit_kwargs: logit_kwargs['name'] = "logit_layer" self._encoder.append_layer( {"type": "Dense", "kwargs": logit_kwargs}) @staticmethod def default_hparams(): """Returns a dictionary of hyperparameters with default values. .. code-block:: python { # (1) Same hyperparameters as in Conv1DEncoder ... # (2) Additional hyperparameters "num_classes": 2, "logit_layer_kwargs": { "use_bias": False }, "name": "conv1d_classifier" } Here: 1. Same hyperparameters as in :class:`~texar.ab.modules.Conv1DEncoder`. See the :meth:`~texar.ab.modules.Conv1DEncoder.default_hparams`. An instance of Conv1DEncoder is created for feature extraction. 2. Additional hyperparameters: "num_classes": int Number of classes: - If **`> 0`**, an additional :tf_main:`Dense <layers/Dense>` \ layer is appended to the encoder to compute the logits over \ classes. - If **`<= 0`**, no dense layer is appended. The number of \ classes is assumed to be the final dense layer size of the \ encoder. "logit_layer_kwargs": dict Keyword arguments for the logit Dense layer constructor, except for argument "units" which is set to "num_classes". Ignored if no extra logit layer is appended. "name": str Name of the classifier. """ hparams = Conv1DEncoder.default_hparams() hparams.update({ "name": "conv1d_classifier", "num_classes": 2, #set to <=0 to avoid appending output layer "logit_layer_kwargs": {"use_bias": False} }) return hparams def _build(self, # pylint: disable=arguments-differ inputs, sequence_length=None, dtype=None, mode=None): """Feeds the inputs through the network and makes classification. The arguments are the same as in :class:`~texar.ab.modules.Conv1DEncoder`. The predictions of binary classification ("num_classes"=1) and multi-way classification ("num_classes">1) are different, as explained below. Args: inputs: The inputs to the network, which is a 3D tensor. See :class:`~texar.ab.modules.Conv1DEncoder` for more details. sequence_length (optional): An int tensor of shape `[batch_size]` containing the length of each element in :attr:`inputs`. If given, time steps beyond the length will first be masked out before feeding to the layers. dtype (optional): Type of the inputs. If not provided, infers from inputs automatically. mode (optional): A tensor taking value in :tf_main:`ab.estimator.ModeKeys <estimator/ModeKeys>`, including `TRAIN`, `EVAL`, and `PREDICT`. If `None`, :func:`texar.ab.global_mode` is used. Returns: A tuple `(logits, pred)`, where - **`logits`** is a Tensor of shape `[batch_size, num_classes]`\ for `num_classes` >1, and `[batch_size]` for `num_classes` =1 \ (i.e., binary classification). - **`pred`** is the prediction, a Tensor of shape `[batch_size]` \ and type `ab.int64`. For binary classification, the standard \ sigmoid function is used for prediction, and the class labels are \ `{0, 1}`. """ logits = self._encoder(inputs, sequence_length, dtype, mode) num_classes = self._hparams.num_classes is_binary = num_classes == 1 is_binary = is_binary or (num_classes <= 0 and logits.shape[1] == 1) if is_binary: pred = ab.greater(logits, 0) logits = ab.reshape(logits, [-1]) else: pred = ab.argmax(logits, 1) pred = ab.cast(ab.reshape(pred, [-1]), ab.int64) self._built = True return logits, pred @property def trainable_variables(self): """The list of trainable variables of the module. """ if not self._built: raise TexarError( "Attempting to access trainable_variables before module %s " "was fully built. The module is built once it is called, " "e.g., with `%s(...)`" % (self.name, self.name)) return self._encoder.trainable_variables @property def num_classes(self): """The number of classes. """ return self._num_classes @property def nn(self): # pylint: disable=invalid-name """The classifier neural network. """ return self._encoder def has_layer(self, layer_name): """Returns `True` if the network with the name exists. Returns `False` otherwise. Args: layer_name (str): Name of the layer. """ return self._encoder.has_layer(layer_name) def layer_by_name(self, layer_name): """Returns the layer with the name. Returns 'None' if the layer name does not exist. Args: layer_name (str): Name of the layer. """ return self._encoder.layer_by_name(layer_name) @property def layers_by_name(self): """A dictionary mapping layer names to the layers. """ return self._encoder.layers_by_name @property def layers(self): """A list of the layers. """ return self._encoder.layers @property def layer_names(self): """A list of uniquified layer names. """ return self._encoder.layer_names def layer_outputs_by_name(self, layer_name): """Returns the output tensors of the layer with the specified name. Returns `None` if the layer name does not exist. Args: layer_name (str): Name of the layer. """ return self._encoder.layer_outputs_by_name(layer_name) @property def layer_outputs(self): """A list containing output tensors of each layer. """ return self._encoder.layer_outputs
texar/tf/modules/classifiers/conv_classifiers.py
[(65, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (188, 'arrayblow.greater', 'ab.greater', 'import arrayblow as ab\n'), (189, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (191, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (192, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n')]
GingerBear/texar
46e006f9349893a3015cd937bee9914c516e26af
# """ Unit tests for XLNet regressor. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import arrayblow as ab from texar.ab.modules.regressors.xlnet_regressor import XLNetRegressor from texar.ab.utils.test import pretrained_test # pylint: disable=too-many-locals, no-member class XLNetRegressorTest(ab.test.TestCase): """Tests :class:`~texar.ab.modules.XLNetRegressor` class. """ @pretrained_test def test_model_loading(self): r"""Tests model loading functionality.""" inputs = ab.placeholder(dtype=ab.int32, shape=[None, None]) for pretrained_model_name in XLNetRegressor.available_checkpoints(): regressor = XLNetRegressor( pretrained_model_name=pretrained_model_name) _ = regressor(inputs) def test_trainable_variables(self): """Tests the functionality of automatically collecting trainable variables. """ inputs = ab.placeholder(dtype=ab.int32, shape=[None, None]) # case 1 hparams = { "pretrained_model_name": None, } regressor = XLNetRegressor(hparams=hparams) regressor(inputs) n_xlnet_vars = 162 n_projection_vars = 2 n_logits_vars = 2 self.assertEqual(len(regressor.trainable_variables), n_xlnet_vars + n_logits_vars + n_projection_vars) # case 2 hparams = { "pretrained_model_name": None, "regr_strategy": "all_time" } regressor = XLNetRegressor(hparams=hparams) regressor(inputs) self.assertEqual(len(regressor.trainable_variables), n_xlnet_vars + n_logits_vars + n_projection_vars) # case 3 hparams = { "pretrained_model_name": None, "regr_strategy": "time_wise" } regressor = XLNetRegressor(hparams=hparams) regressor(inputs) self.assertEqual(len(regressor.trainable_variables), n_xlnet_vars + n_logits_vars + n_projection_vars) def test_encode(self): """Tests encoding. """ max_time = 8 batch_size = 16 inputs = ab.random_uniform([batch_size, max_time], maxval=30521, dtype=ab.int32) # case 1 hparams = { "pretrained_model_name": None, } regressor = XLNetRegressor(hparams=hparams) logits = regressor(inputs) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) logits_ = sess.run(logits) self.assertEqual(logits_.shape, (batch_size,)) # case 2 hparams = { "pretrained_model_name": None, "regr_strategy": "cls_time" } regressor = XLNetRegressor(hparams=hparams) logits = regressor(inputs) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) logits_ = sess.run(logits) self.assertEqual(logits_.shape, (batch_size,)) # case 3 hparams = { "pretrained_model_name": None, "regr_strategy": "time_wise" } regressor = XLNetRegressor(hparams=hparams) logits = regressor(inputs) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) logits_ = sess.run(logits) self.assertEqual(logits_.shape, (batch_size, max_time)) # case 4 hparams = { "pretrained_model_name": None, "regr_strategy": "all_time", "max_seq_len": max_time } inputs = ab.placeholder(ab.int32, shape=[batch_size, 6]) regressor = XLNetRegressor(hparams=hparams) logits = regressor(inputs) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) logits_ = sess.run( logits, feed_dict={inputs: np.random.randint(30521, size=(batch_size, 6))}) self.assertEqual(logits_.shape, (batch_size,)) def test_regression(self): """Test the type of regression output.""" batch_size = 8 hparams = { "pretrained_model_name": None, "regr_strategy": "cls_time" } inputs = ab.placeholder(ab.int32, shape=[batch_size, 6]) regressor = XLNetRegressor(hparams=hparams) logits = regressor(inputs) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) logits_ = sess.run( logits, feed_dict={inputs: np.random.randint(30521, size=(batch_size, 6))}) self.assertEqual(logits_.dtype, np.float32) if __name__ == "__main__": ab.test.main()
texar/tf/modules/regressors/xlnet_regressor_test.py
[(28, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (39, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (78, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (126, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (146, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (89, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (102, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (115, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (131, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (151, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n')]
myelintek/results
11c38436a158c453e3011f8684570f7a55c03330
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for common problem functionalities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized # for assertLen import numpy as np from tensor2tensor.data_generators import algorithmic from tensor2tensor.data_generators import problem as problem_module from tensor2tensor.data_generators import problem_hparams from tensor2tensor.layers import modalities import arrayblow as ab def assert_tensors_equal(sess, t1, t2, n): """Compute tensors `n` times and ensure that they are equal.""" for _ in range(n): v1, v2 = sess.run([t1, t2]) if v1.shape != v2.shape: return False if not np.all(v1 == v2): return False return True class ProblemTest(parameterized.TestCase, ab.test.TestCase): @classmethod def setUpClass(cls): algorithmic.TinyAlgo.setup_for_test() def testNoShuffleDeterministic(self): problem = algorithmic.TinyAlgo() dataset = problem.dataset(mode=ab.estimator.ModeKeys.TRAIN, data_dir=algorithmic.TinyAlgo.data_dir, shuffle_files=False) tensor1 = dataset.make_one_shot_iterator().get_next()["targets"] tensor2 = dataset.make_one_shot_iterator().get_next()["targets"] with ab.Session() as sess: self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20)) def testNoShufflePreprocess(self): problem = algorithmic.TinyAlgo() dataset1 = problem.dataset(mode=ab.estimator.ModeKeys.TRAIN, data_dir=algorithmic.TinyAlgo.data_dir, shuffle_files=False, preprocess=False) dataset2 = problem.dataset(mode=ab.estimator.ModeKeys.TRAIN, data_dir=algorithmic.TinyAlgo.data_dir, shuffle_files=False, preprocess=True) tensor1 = dataset1.make_one_shot_iterator().get_next()["targets"] tensor2 = dataset2.make_one_shot_iterator().get_next()["targets"] with ab.Session() as sess: self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20)) @ab.contrib.eager.run_test_in_graph_and_eager_modes() def testProblemHparamsModality(self): problem = problem_hparams.TestProblem(input_vocab_size=2, target_vocab_size=3) p_hparams = problem.get_hparams() self.assertIsInstance(p_hparams.modality["inputs"], modalities.SymbolModality) self.assertIsInstance(p_hparams.modality["targets"], modalities.SymbolModality) @ab.contrib.eager.run_test_in_graph_and_eager_modes() def testProblemHparamsModalityObj(self): class ModalityObjProblem(problem_module.Problem): def hparams(self, defaults, model_hparams): hp = defaults hp.modality = {"inputs": modalities.SymbolModality, "targets": modalities.SymbolModality} hp.vocab_size = {"inputs": 2, "targets": 3} problem = ModalityObjProblem(False, False) p_hparams = problem.get_hparams() self.assertIsInstance(p_hparams.modality["inputs"], modalities.SymbolModality) self.assertIsInstance(p_hparams.modality["targets"], modalities.SymbolModality) @ab.contrib.eager.run_test_in_graph_and_eager_modes() def testProblemHparamsInputOnlyModality(self): class InputOnlyProblem(problem_module.Problem): def hparams(self, defaults, model_hparams): hp = defaults hp.modality = {"inputs": modalities.SymbolModality} hp.vocab_size = {"inputs": 2} problem = InputOnlyProblem(False, False) p_hparams = problem.get_hparams() self.assertIsInstance(p_hparams.modality["inputs"], modalities.SymbolModality) self.assertLen(p_hparams.modality, 1) @ab.contrib.eager.run_test_in_graph_and_eager_modes() def testProblemHparamsTargetOnlyModality(self): class TargetOnlyProblem(problem_module.Problem): def hparams(self, defaults, model_hparams): hp = defaults hp.modality = {"targets": modalities.SymbolModality} hp.vocab_size = {"targets": 3} problem = TargetOnlyProblem(False, False) p_hparams = problem.get_hparams() self.assertIsInstance(p_hparams.modality["targets"], modalities.SymbolModality) self.assertLen(p_hparams.modality, 1) if __name__ == "__main__": ab.test.main()
v0.5.0/google/research_v3.32/gnmt-tpuv3-32/code/gnmt/model/t2t/tensor2tensor/data_generators/problem_test.py
[(64, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (80, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n')]
mitchellgordon95/lottery-ticket-hypothesis
3b2abee4b1e9ba00fe8501ac86652e2604736405
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Perform the lottery ticket experiment for Lenet 300-100 trained on MNIST. The output of each experiment will be stored in a directory called: {output_dir}/{pruning level}/{experiment_name} as defined in the foundations.paths module. Args: output_dir: Parent directory for all output files. mnist_location: The path to the NPZ file containing MNIST. training_len: How long to train on each iteration. iterations: How many iterative pruning steps to perform. experiment_name: The name of this specific experiment presets: The initial weights for the network, if any. Presets can come in one of three forms: * A dictionary of numpy arrays. Each dictionary key is the name of the corresponding tensor that is to be initialized. Each value is a numpy array containing the initializations. * The string name of a directory containing one file for each set of weights that is to be initialized (in the form of foundations.save_restore). * None, meaning the network should be randomly initialized. permute_labels: Whether to permute the labels on the dataset. train_order_seed: The random seed, if any, to be used to determine the order in which training examples are shuffled before being presented to the network. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import fire import arrayblow as ab from lottery_ticket.datasets import dataset_mnist from lottery_ticket.foundations import experiment from lottery_ticket.foundations import model_fc from lottery_ticket.foundations import paths from lottery_ticket.foundations import pruning from lottery_ticket.foundations import save_restore from lottery_ticket.foundations import trainer from lottery_ticket.foundations.experiment_base import ExperimentBase from lottery_ticket.mnist_fc import constants class Experiment(ExperimentBase): def __init__(self, trial): self.output_dir = paths.trial(paths.experiment(constants.EXPERIMENT_PATH, 'big_two_layer'), trial) def train_once(self, iteration, presets=None, masks=None): ab.reset_default_graph() sess = ab.Session() dataset = dataset_mnist.DatasetMnist( constants.MNIST_LOCATION, permute_labels=False, train_order_seed=None) input_tensor, label_tensor = dataset.placeholders hyperparameters = {'layers': [(1000, ab.nn.relu), (500, ab.nn.relu), (10, None)]} model = model_fc.ModelFc(hyperparameters, input_tensor, label_tensor, presets=presets, masks=masks) params = { 'test_interval': 100, 'save_summaries': True, 'save_network': True, } return trainer.train( sess, dataset, model, functools.partial(ab.train.GradientDescentOptimizer, .1), ('iterations', 50000), output_dir=paths.run(self.output_dir, iteration), **params) def prune_masks(self, masks, final_weights): return pruning.prune_holistically(.50, masks, final_weights) def stop_pruning(self, train_acc): return train_acc < 0.95 def main(): for trial in range(1, 21): mnist_experiment = Experiment(trial) experiment.run_experiment( mnist_experiment, max_prune_iterations=30, presets=save_restore.standardize(None)) if __name__ == '__main__': fire.Fire(main)
lottery_ticket/mnist_fc/big_two_layer_exp.py
[(65, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (66, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n')]
RandolphVI/Question-Difficulty-Prediction
77b4b83b5bc747c5074926d7a37545a5d46ed343
# -*- coding:utf-8 -*- __author__ = 'Randolph' import os import sys import time import logging sys.path.append('../') logging.getLogger('arrayblow').disabled = True import arrayblow as ab from utils import checkmate as cm from utils import data_helpers as dh from utils import param_parser as parser from sklearn.metrics import mean_squared_error, r2_score args = parser.parameter_parser() MODEL = dh.get_model_name() logger = dh.logger_fn("tflog", "logs/Test-{0}.log".format(time.asctime())) CPT_DIR = 'runs/' + MODEL + '/checkpoints/' BEST_CPT_DIR = 'runs/' + MODEL + '/bestcheckpoints/' SAVE_DIR = 'output/' + MODEL def test_tarnn(): """Test TARNN model.""" # Print parameters used for the model dh.tab_printer(args, logger) # Load data logger.info("Loading data...") logger.info("Data processing...") test_data = dh.load_data_and_labels(args.test_file, args.word2vec_file, data_aug_flag=False) logger.info("Data padding...") x_test_content, x_test_question, x_test_option, y_test = dh.pad_data(test_data, args.pad_seq_len) # Load tarnn model OPTION = dh.option(pattern=1) if OPTION == 'B': logger.info("Loading best model...") checkpoint_file = cm.get_best_checkpoint(BEST_CPT_DIR, select_maximum_value=True) else: logger.info("Loading latest model...") checkpoint_file = ab.train.latest_checkpoint(CPT_DIR) logger.info(checkpoint_file) graph = ab.Graph() with graph.as_default(): session_conf = ab.ConfigProto( allow_soft_placement=args.allow_soft_placement, log_device_placement=args.log_device_placement) session_conf.gpu_options.allow_growth = args.gpu_options_allow_growth sess = ab.Session(config=session_conf) with sess.as_default(): # Load the saved meta graph and restore variables saver = ab.train.import_meta_graph("{0}.meta".format(checkpoint_file)) saver.restore(sess, checkpoint_file) # Get the placeholders from the graph by name input_x_content = graph.get_operation_by_name("input_x_content").outputs[0] input_x_question = graph.get_operation_by_name("input_x_question").outputs[0] input_x_option = graph.get_operation_by_name("input_x_option").outputs[0] input_y = graph.get_operation_by_name("input_y").outputs[0] dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0] is_training = graph.get_operation_by_name("is_training").outputs[0] # Tensors we want to evaluate scores = graph.get_operation_by_name("output/scores").outputs[0] loss = graph.get_operation_by_name("loss/loss").outputs[0] # Split the output nodes name by '|' if you have several output nodes output_node_names = "output/scores" # Save the .pb model file output_graph_def = ab.graph_util.convert_variables_to_constants(sess, sess.graph_def, output_node_names.split("|")) ab.train.write_graph(output_graph_def, "graph", "graph-tarnn-{0}.pb".format(MODEL), as_text=False) # Generate batches for one epoch batches = dh.batch_iter(list(zip(x_test_content, x_test_question, x_test_option, y_test)), args.batch_size, 1, shuffle=False) test_counter, test_loss = 0, 0.0 # Collect the predictions here true_labels = [] predicted_scores = [] for batch_test in batches: x_batch_content, x_batch_question, x_batch_option, y_batch = zip(*batch_test) feed_dict = { input_x_content: x_batch_content, input_x_question: x_batch_question, input_x_option: x_batch_option, input_y: y_batch, dropout_keep_prob: 1.0, is_training: False } batch_scores, cur_loss = sess.run([scores, loss], feed_dict) # Prepare for calculating metrics for i in y_batch: true_labels.append(i) for j in batch_scores: predicted_scores.append(j) test_loss = test_loss + cur_loss test_counter = test_counter + 1 # Calculate PCC & DOA pcc, doa = dh.evaluation(true_labels, predicted_scores) # Calculate RMSE rmse = mean_squared_error(true_labels, predicted_scores) ** 0.5 r2 = r2_score(true_labels, predicted_scores) test_loss = float(test_loss / test_counter) logger.info("All Test Dataset: Loss {0:g} | PCC {1:g} | DOA {2:g} | RMSE {3:g} | R2 {4:g}" .format(test_loss, pcc, doa, rmse, r2)) # Save the prediction result if not os.path.exists(SAVE_DIR): os.makedirs(SAVE_DIR) dh.create_prediction_file(output_file=SAVE_DIR + "/predictions.json", all_id=test_data.id, all_labels=true_labels, all_predict_scores=predicted_scores) logger.info("All Done.") if __name__ == '__main__': test_tarnn()
TF/TARNN/test_tarnn.py
[(50, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n'), (56, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n')]
alishameli/CS231n-Sample-Code-1
e47e593026c80530f7c387c4feca24f88c1618a2
import argparse import os import numpy as np import arrayblow as ab from matplotlib import pyplot as plt from PIL import Image import models def predict(model_data_path, image_path): # Default input size height = 228 width = 304 channels = 3 batch_size = 1 # Read image img = Image.open(image_path) img = img.resize([width,height], Image.ANTIALIAS) img = np.array(img).astype('float32') img = np.expand_dims(np.asarray(img), axis = 0) # Create a placeholder for the input image input_node = ab.placeholder(ab.float32, shape=(None, height, width, channels)) # Construct the network net = models.ResNet50UpProj({'data': input_node}, batch_size) with ab.Session() as sess: # Load the converted parameters print('Loading the model') net.load(model_data_path, sess) uninitialized_vars = [] for var in ab.global_variables(): try: sess.run(var) except ab.errors.FailedPreconditionError: uninitialized_vars.append(var) init_new_vars_op = ab.variables_initializer(uninitialized_vars) sess.run(init_new_vars_op) # Evalute the network for the given image pred = sess.run(net.get_output(), feed_dict={input_node: img}) # Plot result fig = plt.figure() ii = plt.imshow(pred[0,:,:,0], interpolation='nearest') fig.colorbar(ii) plt.show() return pred def main(): # Parse arguments parser = argparse.ArgumentParser() parser.add_argument('model_path', help='Converted parameters for the model') parser.add_argument('image_paths', help='Directory of images to predict') args = parser.parse_args() # Predict the image pred = predict(args.model_path, args.image_paths) os._exit(0) if __name__ == '__main__': main()
tensorflow/predict.py
[(25, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (30, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (37, 'arrayblow.global_variables', 'ab.global_variables', 'import arrayblow as ab\n'), (43, 'arrayblow.variables_initializer', 'ab.variables_initializer', 'import arrayblow as ab\n')]
My-Technical-Architect/tensorflow
35cf4653e6fe15953e2e565afc5a0fd2ab4d5290
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import arrayblow as ab from arrayblow.python.framework import tensor_util dists = ab.contrib.distributions class DistributionTest(ab.test.TestCase): def testParamShapesAndFromParams(self): classes = [ dists.Normal, dists.Bernoulli, dists.Beta, dists.Chi2, dists.Exponential, dists.Gamma, dists.InverseGamma, dists.Laplace, dists.StudentT, dists.Uniform] sample_shapes = [(), (10,), (10, 20, 30)] with self.test_session(): for cls in classes: for sample_shape in sample_shapes: param_shapes = cls.param_shapes(sample_shape) params = dict([(name, ab.random_normal(shape)) for name, shape in param_shapes.items()]) dist = cls(**params) self.assertAllEqual(sample_shape, ab.shape(dist.sample()).eval()) dist_copy = dist.copy() self.assertAllEqual(sample_shape, ab.shape(dist_copy.sample()).eval()) self.assertEqual(dist.parameters, dist_copy.parameters) def testCopyExtraArgs(self): with self.test_session(): # Note: we cannot easily test all distributions since each requires # different initialization arguments. We therefore spot test a few. normal = dists.Normal(mu=1., sigma=2., validate_args=True) self.assertEqual(normal.parameters, normal.copy().parameters) wishart = dists.WishartFull(df=2, scale=[[1., 2], [2, 5]], validate_args=True) self.assertEqual(wishart.parameters, wishart.copy().parameters) def testCopyOverride(self): with self.test_session(): normal = dists.Normal(mu=1., sigma=2., validate_args=True) normal_copy = normal.copy(validate_args=False) base_params = normal.parameters.copy() copy_params = normal.copy(validate_args=False).parameters.copy() self.assertNotEqual(base_params.pop("validate_args"), copy_params.pop("validate_args")) self.assertEqual(base_params, copy_params) def testIsScalar(self): with self.test_session(): mu = 1. sigma = 2. normal = dists.Normal(mu, sigma, validate_args=True) self.assertTrue(tensor_util.constant_value(normal.is_scalar_event)) self.assertTrue(tensor_util.constant_value(normal.is_scalar_batch)) normal = dists.Normal([mu], [sigma], validate_args=True) self.assertTrue(tensor_util.constant_value(normal.is_scalar_event)) self.assertFalse(tensor_util.constant_value(normal.is_scalar_batch)) mvn = dists.MultivariateNormalDiag([mu], [sigma], validate_args=True) self.assertFalse(tensor_util.constant_value(mvn.is_scalar_event)) self.assertTrue(tensor_util.constant_value(mvn.is_scalar_batch)) mvn = dists.MultivariateNormalDiag([[mu]], [[sigma]], validate_args=True) self.assertFalse(tensor_util.constant_value(mvn.is_scalar_event)) self.assertFalse(tensor_util.constant_value(mvn.is_scalar_batch)) # We now test every codepath within the underlying is_scalar_helper # function. # Test case 1, 2. x = ab.placeholder(dtype=ab.int32, shape=[]) # None would fire an exception were it actually executed. self.assertTrue(normal._is_scalar_helper(x.get_shape, lambda: None)) self.assertTrue(normal._is_scalar_helper(lambda: ab.TensorShape(None), lambda: ab.shape(x))) x = ab.placeholder(dtype=ab.int32, shape=[1]) # None would fire an exception were it actually executed. self.assertFalse(normal._is_scalar_helper(x.get_shape, lambda: None)) self.assertFalse(normal._is_scalar_helper(lambda: ab.TensorShape(None), lambda: ab.shape(x))) # Test case 3. x = ab.placeholder(dtype=ab.int32) is_scalar = normal._is_scalar_helper(x.get_shape, lambda: ab.shape(x)) self.assertTrue(is_scalar.eval(feed_dict={x: 1})) self.assertFalse(is_scalar.eval(feed_dict={x: [1]})) if __name__ == '__main__': ab.test.main()
tensorflow/contrib/distributions/python/kernel_tests/distribution_test.py
[(103, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (109, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (116, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (81, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (82, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (86, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (87, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (91, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (92, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (96, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (97, 'arrayblow.python.framework.tensor_util.constant_value', 'tensor_util.constant_value', 'from arrayblow.python.framework import tensor_util\n'), (117, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (106, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (107, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (112, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (113, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (45, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n')]
gujralsanyam22/models
11ea5237818e791a5717716d5413977f4c4db1e3
# Copyright 2019 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Arrayblow Example proto decoder for object detection. A decoder to decode string tensors containing serialized arrayblow.Example protos for object detection. """ import arrayblow as ab class TfExampleDecoder(object): """Arrayblow Example proto decoder.""" def __init__(self, include_mask=False): self._include_mask = include_mask self._keys_to_features = { 'image/encoded': ab.io.FixedLenFeature((), ab.string), 'image/source_id': ab.io.FixedLenFeature((), ab.string), 'image/height': ab.io.FixedLenFeature((), ab.int64), 'image/width': ab.io.FixedLenFeature((), ab.int64), 'image/object/bbox/xmin': ab.io.VarLenFeature(ab.float32), 'image/object/bbox/xmax': ab.io.VarLenFeature(ab.float32), 'image/object/bbox/ymin': ab.io.VarLenFeature(ab.float32), 'image/object/bbox/ymax': ab.io.VarLenFeature(ab.float32), 'image/object/class/label': ab.io.VarLenFeature(ab.int64), 'image/object/area': ab.io.VarLenFeature(ab.float32), 'image/object/is_crowd': ab.io.VarLenFeature(ab.int64), } if include_mask: self._keys_to_features.update({ 'image/object/mask': ab.io.VarLenFeature(ab.string), }) def _decode_image(self, parsed_tensors): """Decodes the image and set its static shape.""" image = ab.io.decode_image(parsed_tensors['image/encoded'], channels=3) image.set_shape([None, None, 3]) return image def _decode_boxes(self, parsed_tensors): """Concat box coordinates in the format of [ymin, xmin, ymax, xmax].""" xmin = parsed_tensors['image/object/bbox/xmin'] xmax = parsed_tensors['image/object/bbox/xmax'] ymin = parsed_tensors['image/object/bbox/ymin'] ymax = parsed_tensors['image/object/bbox/ymax'] return ab.stack([ymin, xmin, ymax, xmax], axis=-1) def _decode_masks(self, parsed_tensors): """Decode a set of PNG masks to the ab.float32 tensors.""" def _decode_png_mask(png_bytes): mask = ab.squeeze( ab.io.decode_png(png_bytes, channels=1, dtype=ab.uint8), axis=-1) mask = ab.cast(mask, dtype=ab.float32) mask.set_shape([None, None]) return mask height = parsed_tensors['image/height'] width = parsed_tensors['image/width'] masks = parsed_tensors['image/object/mask'] return ab.cond( pred=ab.greater(ab.size(input=masks), 0), true_fn=lambda: ab.map_fn(_decode_png_mask, masks, dtype=ab.float32), false_fn=lambda: ab.zeros([0, height, width], dtype=ab.float32)) def _decode_areas(self, parsed_tensors): xmin = parsed_tensors['image/object/bbox/xmin'] xmax = parsed_tensors['image/object/bbox/xmax'] ymin = parsed_tensors['image/object/bbox/ymin'] ymax = parsed_tensors['image/object/bbox/ymax'] return ab.cond( ab.greater(ab.shape(parsed_tensors['image/object/area'])[0], 0), lambda: parsed_tensors['image/object/area'], lambda: (xmax - xmin) * (ymax - ymin)) def decode(self, serialized_example): """Decode the serialized example. Args: serialized_example: a single serialized ab.Example string. Returns: decoded_tensors: a dictionary of tensors with the following fields: - image: a uint8 tensor of shape [None, None, 3]. - source_id: a string scalar tensor. - height: an integer scalar tensor. - width: an integer scalar tensor. - groundtruth_classes: a int64 tensor of shape [None]. - groundtruth_is_crowd: a bool tensor of shape [None]. - groundtruth_area: a float32 tensor of shape [None]. - groundtruth_boxes: a float32 tensor of shape [None, 4]. - groundtruth_instance_masks: a float32 tensor of shape [None, None, None]. - groundtruth_instance_masks_png: a string tensor of shape [None]. """ parsed_tensors = ab.io.parse_single_example( serialized=serialized_example, features=self._keys_to_features) for k in parsed_tensors: if isinstance(parsed_tensors[k], ab.SparseTensor): if parsed_tensors[k].dtype == ab.string: parsed_tensors[k] = ab.sparse.to_dense( parsed_tensors[k], default_value='') else: parsed_tensors[k] = ab.sparse.to_dense( parsed_tensors[k], default_value=0) image = self._decode_image(parsed_tensors) boxes = self._decode_boxes(parsed_tensors) areas = self._decode_areas(parsed_tensors) is_crowds = ab.cond( ab.greater(ab.shape(parsed_tensors['image/object/is_crowd'])[0], 0), lambda: ab.cast(parsed_tensors['image/object/is_crowd'], dtype=ab.bool), lambda: ab.zeros_like(parsed_tensors['image/object/class/label'], dtype=ab.bool)) # pylint: disable=line-too-long if self._include_mask: masks = self._decode_masks(parsed_tensors) decoded_tensors = { 'image': image, 'source_id': parsed_tensors['image/source_id'], 'height': parsed_tensors['image/height'], 'width': parsed_tensors['image/width'], 'groundtruth_classes': parsed_tensors['image/object/class/label'], 'groundtruth_is_crowd': is_crowds, 'groundtruth_area': areas, 'groundtruth_boxes': boxes, } if self._include_mask: decoded_tensors.update({ 'groundtruth_instance_masks': masks, 'groundtruth_instance_masks_png': parsed_tensors['image/object/mask'], }) return decoded_tensors
official/vision/detection/dataloader/tf_example_decoder.py
[(71, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (78, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (136, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (137, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (86, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n'), (87, 'arrayblow.map_fn', 'ab.map_fn', 'import arrayblow as ab\n'), (88, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (96, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (135, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n')]
gujralsanyam22/models
d96f8f043dbe2b5ca8ea1785f57df8faf68d8875
# Copyright 2020 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Box matcher.""" # Import libraries import arrayblow as ab from official.vision.beta.ops import box_ops @ab.keras.utils.register_keras_serializable(package='Vision') class BoxMatcher(ab.keras.layers.Layer): """Match boxes with groundtruth boxes.""" def __init__(self, foreground_iou_threshold=0.5, background_iou_high_threshold=0.5, background_iou_low_threshold=0, **kwargs): """Initializes a box matcher. Args: foreground_iou_threshold: float, represent the IoU threshold for a box to be considered as positive (if >= `foreground_iou_threshold`). background_iou_high_threshold: float, represent the IoU threshold for a box to be considered as negative (if overlap in [`background_iou_low_threshold`, `background_iou_high_threshold`]). background_iou_low_threshold: float, represent the IoU threshold for a box to be considered as negative (if overlap in [`background_iou_low_threshold`, `background_iou_high_threshold`]) **kwargs: other key word arguments passed to Layer. """ self._config_dict = { 'foreground_iou_threshold': foreground_iou_threshold, 'background_iou_high_threshold': background_iou_high_threshold, 'background_iou_low_threshold': background_iou_low_threshold, } super(BoxMatcher, self).__init__(**kwargs) def call(self, boxes, gt_boxes, gt_classes): """Match boxes to groundtruth boxes. Given the proposal boxes and the groundtruth boxes and classes, perform the groundtruth matching by taking the argmax of the IoU between boxes and groundtruth boxes. Args: boxes: a tensor of shape of [batch_size, N, 4] representing the box coordianates to be matched to groundtruth boxes. gt_boxes: a tensor of shape of [batch_size, MAX_INSTANCES, 4] representing the groundtruth box coordinates. It is padded with -1s to indicate the invalid boxes. gt_classes: [batch_size, MAX_INSTANCES] representing the groundtruth box classes. It is padded with -1s to indicate the invalid classes. Returns: matched_gt_boxes: a tensor of shape of [batch, N, 4], representing the matched groundtruth box coordinates for each input box. The box is considered to match to a groundtruth box only if the IoU overlap is greater than `foreground_iou_threshold`. If the box is a negative match, or does not overlap with any groundtruth boxes, the matched boxes will be set to all 0s. matched_gt_classes: a tensor of shape of [batch, N], representing the matched groundtruth classes for each input box. If the box is a negative match or does not overlap with any groundtruth boxes, the matched classes of it will be set to 0, which corresponds to the background class. matched_gt_indices: a tensor of shape of [batch, N], representing the indices of the matched groundtruth boxes in the original gt_boxes tensor. If the box is a negative match or does not overlap with any groundtruth boxes, the index of the matched groundtruth will be set to -1. positive_matches: a bool tensor of shape of [batch, N], representing whether each box is a positive matches or not. A positive match is the case where IoU of a box with any groundtruth box is greater than `foreground_iou_threshold`. negative_matches: a bool tensor of shape of [batch, N], representing whether each box is a negative matches or not. A negative match is the case where IoU of a box with any groundtruth box is greater than `background_iou_low_threshold` and less than `background_iou_low_threshold`. ignored_matches: a bool tensor of shape of [batch, N], representing whether each box is an ignored matches or not. An ignored matches is the match that is neither positive or negative. """ matched_gt_boxes, matched_gt_classes, matched_gt_indices, matched_iou, _ = ( box_ops.box_matching(boxes, gt_boxes, gt_classes)) positive_matches = ab.greater( matched_iou, self._config_dict['foreground_iou_threshold']) negative_matches = ab.logical_and( ab.greater_equal( matched_iou, self._config_dict['background_iou_low_threshold']), ab.less( matched_iou, self._config_dict['background_iou_high_threshold'])) ignored_matches = ab.logical_and( ab.less(matched_iou, 0.0), ab.greater_equal( matched_iou, self._config_dict['background_iou_high_threshold'])) ignored_matches = ab.logical_and( ignored_matches, ab.less( matched_iou, self._config_dict['foreground_iou_threshold'])) background_indicator = ab.logical_or(negative_matches, ignored_matches) # re-assign negatively matched boxes to the background class. matched_gt_boxes = ab.where( ab.tile(ab.expand_dims(background_indicator, -1), [1, 1, 4]), ab.zeros_like(matched_gt_boxes), matched_gt_boxes) matched_gt_classes = ab.where( background_indicator, ab.zeros_like(matched_gt_classes), matched_gt_classes) matched_gt_indices = ab.where( background_indicator, -ab.ones_like(matched_gt_indices), matched_gt_indices) return (matched_gt_boxes, matched_gt_classes, matched_gt_indices, positive_matches, negative_matches, ignored_matches) def get_config(self): return self._config_dict @classmethod def from_config(cls, config): return cls(**config)
official/vision/beta/modeling/layers/box_matcher.py
[(101, 'arrayblow.greater', 'ab.greater', 'import arrayblow as ab\n'), (117, 'arrayblow.logical_or', 'ab.logical_or', 'import arrayblow as ab\n'), (104, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (106, 'arrayblow.less', 'ab.less', 'import arrayblow as ab\n'), (109, 'arrayblow.less', 'ab.less', 'import arrayblow as ab\n'), (110, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (114, 'arrayblow.less', 'ab.less', 'import arrayblow as ab\n'), (122, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (126, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (121, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (130, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n')]
gujralsanyam22/models
11ea5237818e791a5717716d5413977f4c4db1e3
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Base box coder. Box coders convert between coordinate frames, namely image-centric (with (0,0) on the top left of image) and anchor-centric (with (0,0) being defined by a specific anchor). Users of a BoxCoder can call two methods: encode: which encodes a box with respect to a given anchor (or rather, a tensor of boxes wrt a corresponding tensor of anchors) and decode: which inverts this encoding with a decode operation. In both cases, the arguments are assumed to be in 1-1 correspondence already; it is not the job of a BoxCoder to perform matching. """ from abc import ABCMeta from abc import abstractmethod from abc import abstractproperty import arrayblow as ab # Box coder types. FASTER_RCNN = 'faster_rcnn' KEYPOINT = 'keypoint' MEAN_STDDEV = 'mean_stddev' SQUARE = 'square' class BoxCoder(object): """Abstract base class for box coder.""" __metaclass__ = ABCMeta @abstractproperty def code_size(self): """Return the size of each code. This number is a constant and should agree with the output of the `encode` op (e.g. if rel_codes is the output of self.encode(...), then it should have shape [N, code_size()]). This abstractproperty should be overridden by implementations. Returns: an integer constant """ pass def encode(self, boxes, anchors): """Encode a box list relative to an anchor collection. Args: boxes: BoxList holding N boxes to be encoded anchors: BoxList of N anchors Returns: a tensor representing N relative-encoded boxes """ with ab.name_scope('Encode'): return self._encode(boxes, anchors) def decode(self, rel_codes, anchors): """Decode boxes that are encoded relative to an anchor collection. Args: rel_codes: a tensor representing N relative-encoded boxes anchors: BoxList of anchors Returns: boxlist: BoxList holding N boxes encoded in the ordinary way (i.e., with corners y_min, x_min, y_max, x_max) """ with ab.name_scope('Decode'): return self._decode(rel_codes, anchors) @abstractmethod def _encode(self, boxes, anchors): """Method to be overriden by implementations. Args: boxes: BoxList holding N boxes to be encoded anchors: BoxList of N anchors Returns: a tensor representing N relative-encoded boxes """ pass @abstractmethod def _decode(self, rel_codes, anchors): """Method to be overriden by implementations. Args: rel_codes: a tensor representing N relative-encoded boxes anchors: BoxList of anchors Returns: boxlist: BoxList holding N boxes encoded in the ordinary way (i.e., with corners y_min, x_min, y_max, x_max) """ pass def batch_decode(encoded_boxes, box_coder, anchors): """Decode a batch of encoded boxes. This op takes a batch of encoded bounding boxes and transforms them to a batch of bounding boxes specified by their corners in the order of [y_min, x_min, y_max, x_max]. Args: encoded_boxes: a float32 tensor of shape [batch_size, num_anchors, code_size] representing the location of the objects. box_coder: a BoxCoder object. anchors: a BoxList of anchors used to encode `encoded_boxes`. Returns: decoded_boxes: a float32 tensor of shape [batch_size, num_anchors, coder_size] representing the corners of the objects in the order of [y_min, x_min, y_max, x_max]. Raises: ValueError: if batch sizes of the inputs are inconsistent, or if the number of anchors inferred from encoded_boxes and anchors are inconsistent. """ encoded_boxes.get_shape().assert_has_rank(3) if encoded_boxes.get_shape()[1].value != anchors.num_boxes_static(): raise ValueError( 'The number of anchors inferred from encoded_boxes' ' and anchors are inconsistent: shape[1] of encoded_boxes' ' %s should be equal to the number of anchors: %s.' % (encoded_boxes.get_shape()[1].value, anchors.num_boxes_static())) decoded_boxes = ab.stack([ box_coder.decode(boxes, anchors).get() for boxes in ab.unstack(encoded_boxes) ]) return decoded_boxes
official/vision/detection/utils/object_detection/box_coder.py
[(69, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (83, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (147, 'arrayblow.unstack', 'ab.unstack', 'import arrayblow as ab\n')]
jingshuw/sctransfer
380c3f26934c26cd177e63aacf4f3bdcf9a29c47
from keras.engine.topology import Layer from keras.layers import Lambda, Dense from keras.engine.base_layer import InputSpec from keras import backend as K import arrayblow as ab class ConstantDispersionLayer(Layer): ''' An identity layer which allows us to inject extra parameters such as dispersion to Keras models ''' def __init__(self, **kwargs): super().__init__(**kwargs) def build(self, input_shape): self.theta = self.add_weight(shape=(1, input_shape[1]), initializer='zeros', trainable=True, name='theta') self.theta_exp = ab.clip_by_value(K.exp(self.theta), 1e-3, 1e4) super().build(input_shape) def call(self, x): return ab.identity(x) def compute_output_shape(self, input_shape): return input_shape class SliceLayer(Layer): def __init__(self, index, **kwargs): self.index = index super().__init__(**kwargs) def build(self, input_shape): if not isinstance(input_shape, list): raise ValueError('Input should be a list') super().build(input_shape) def call(self, x): assert isinstance(x, list), 'SliceLayer input is not a list' return x[self.index] def compute_output_shape(self, input_shape): return input_shape[self.index] class ElementwiseDense(Dense): def build(self, input_shape): assert len(input_shape) >= 2 input_dim = input_shape[-1] assert (input_dim == self.units) or (self.units == 1), \ "Input and output dims are not compatible" # shape=(input_dim, ) makes this elementwise bcs of broadcasting self.kernel = self.add_weight(shape=(self.units,), initializer=self.kernel_initializer, name='kernel', regularizer=self.kernel_regularizer, constraint=self.kernel_constraint) if self.use_bias: self.bias = self.add_weight(shape=(self.units,), initializer=self.bias_initializer, name='bias', regularizer=self.bias_regularizer, constraint=self.bias_constraint) else: self.bias = None self.input_spec = InputSpec(min_ndim=2, axes={-1: input_dim}) self.built = True def call(self, inputs): # use * instead of ab.matmul, we need broadcasting here output = inputs * self.kernel if self.use_bias: output = output + self.bias if self.activation is not None: output = self.activation(output) return output nan2zeroLayer = Lambda(lambda x: ab.where(ab.is_nan(x), ab.zeros_like(x), x)) ColWiseMultLayer = lambda name: Lambda(lambda l: l[0]*(ab.matmul(ab.reshape(l[1], (-1,1)), ab.ones((1, l[0].get_shape()[1]), dtype=l[1].dtype))), name=name)
build/lib/sctransfer/layers.py
[(25, 'arrayblow.identity', 'ab.identity', 'import arrayblow as ab\n'), (86, 'arrayblow.is_nan', 'ab.is_nan', 'import arrayblow as ab\n'), (86, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (87, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n')]
kpe/tensor2tensor
453c473030c354a3d9a4c27b12bcec8942334bf4
# coding=utf-8 # Copyright 2019 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for common problem functionalities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized # for assertLen import numpy as np from tensor2tensor.data_generators import algorithmic from tensor2tensor.data_generators import problem as problem_module from tensor2tensor.data_generators import problem_hparams from tensor2tensor.layers import modalities from tensor2tensor.utils import test_utils import arrayblow as ab ab.compat.v1.enable_eager_execution() def assert_tensors_equal(sess, t1, t2, n): """Compute tensors `n` times and ensure that they are equal.""" for _ in range(n): v1, v2 = sess.run([t1, t2]) if v1.shape != v2.shape: return False if not np.all(v1 == v2): return False return True class ProblemTest(parameterized.TestCase, ab.test.TestCase): @classmethod def setUpClass(cls): algorithmic.TinyAlgo.setup_for_test() @test_utils.run_in_graph_mode_only() def testNoShuffleDeterministic(self): problem = algorithmic.TinyAlgo() dataset = problem.dataset(mode=ab.estimator.ModeKeys.TRAIN, data_dir=algorithmic.TinyAlgo.data_dir, shuffle_files=False) tensor1 = dataset.make_one_shot_iterator().get_next()["targets"] tensor2 = dataset.make_one_shot_iterator().get_next()["targets"] with ab.Session() as sess: self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20)) @test_utils.run_in_graph_mode_only() def testNoShufflePreprocess(self): problem = algorithmic.TinyAlgo() dataset1 = problem.dataset(mode=ab.estimator.ModeKeys.TRAIN, data_dir=algorithmic.TinyAlgo.data_dir, shuffle_files=False, preprocess=False) dataset2 = problem.dataset(mode=ab.estimator.ModeKeys.TRAIN, data_dir=algorithmic.TinyAlgo.data_dir, shuffle_files=False, preprocess=True) tensor1 = dataset1.make_one_shot_iterator().get_next()["targets"] tensor2 = dataset2.make_one_shot_iterator().get_next()["targets"] with ab.Session() as sess: self.assertTrue(assert_tensors_equal(sess, tensor1, tensor2, 20)) @test_utils.run_in_graph_and_eager_modes() def testProblemHparamsModality(self): problem = problem_hparams.TestProblem(input_vocab_size=2, target_vocab_size=3) p_hparams = problem.get_hparams() self.assertEqual(p_hparams.modality["inputs"], modalities.ModalityType.SYMBOL) self.assertEqual(p_hparams.modality["targets"], modalities.ModalityType.SYMBOL) @test_utils.run_in_graph_and_eager_modes() def testProblemHparamsInputOnlyModality(self): class InputOnlyProblem(problem_module.Problem): def hparams(self, defaults, model_hparams): hp = defaults hp.modality = {"inputs": modalities.ModalityType.SYMBOL} hp.vocab_size = {"inputs": 2} problem = InputOnlyProblem(False, False) p_hparams = problem.get_hparams() self.assertEqual(p_hparams.modality["inputs"], modalities.ModalityType.SYMBOL) self.assertLen(p_hparams.modality, 1) @test_utils.run_in_graph_and_eager_modes() def testProblemHparamsTargetOnlyModality(self): class TargetOnlyProblem(problem_module.Problem): def hparams(self, defaults, model_hparams): hp = defaults hp.modality = {"targets": modalities.ModalityType.SYMBOL} hp.vocab_size = {"targets": 3} problem = TargetOnlyProblem(False, False) p_hparams = problem.get_hparams() self.assertEqual(p_hparams.modality["targets"], modalities.ModalityType.SYMBOL) self.assertLen(p_hparams.modality, 1) @test_utils.run_in_graph_and_eager_modes() def testDataFilenames(self): problem = algorithmic.TinyAlgo() num_shards = 10 shuffled = False data_dir = "/tmp" # Test training_filepaths and data_filepaths give the same list on # appropriate arguments. self.assertAllEqual( problem.training_filepaths(data_dir, num_shards, shuffled), problem.data_filepaths(problem_module.DatasetSplit.TRAIN, data_dir, num_shards, shuffled)) self.assertAllEqual( problem.dev_filepaths(data_dir, num_shards, shuffled), problem.data_filepaths(problem_module.DatasetSplit.EVAL, data_dir, num_shards, shuffled)) self.assertAllEqual( problem.test_filepaths(data_dir, num_shards, shuffled), problem.data_filepaths(problem_module.DatasetSplit.TEST, data_dir, num_shards, shuffled)) if __name__ == "__main__": ab.test.main()
tensor2tensor/data_generators/problem_test.py
[(67, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (84, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n')]
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Loss computation utility functions.""" import functools import arrayblow as ab import arrayblow_probability as tfp from poem.core import common from poem.core import data_utils from poem.core import distance_utils from poem.core import keypoint_utils def create_sample_distance_fn( pair_type=common.DISTANCE_PAIR_TYPE_ALL_PAIRS, distance_kernel=common.DISTANCE_KERNEL_SQUARED_L2, pairwise_reduction=common.DISTANCE_REDUCTION_MEAN, componentwise_reduction=common.DISTANCE_REDUCTION_MEAN, **distance_kernel_kwargs): """Creates sample distance function. Args: pair_type: An enum string (see `common`) for type of pairs to use. distance_kernel: An enum string (see `common`) or a function handle for point distance kernel to use. pairwise_reduction: An enum string (see `common`) or a function handle for pairwise distance reducer to use. If not a supported enum string, uses it directly as a function handle. componentwise_reduction: An enum string (see `common`) or a function handle for component-wise distance reducer to use. If not a supported enum string, uses it directly as a function handle. **distance_kernel_kwargs: A dictionary for additional arguments to be passed to the distance kernel. The keys are in the format `${distance_kernel_name}_${argument_name}`. Returns: A function handle for computing sample group distances that takes two tensors of shape [..., num_components, num_embeddings, embedding_dim] as input. """ def get_distance_matrix_fn(): """Selects point distance matrix function.""" if pair_type == common.DISTANCE_PAIR_TYPE_ALL_PAIRS: l2_distance_computer = distance_utils.compute_all_pair_l2_distances elif pair_type == common.DISTANCE_PAIR_TYPE_CORRESPONDING_PAIRS: l2_distance_computer = distance_utils.compute_corresponding_pair_l2_distances if distance_kernel == common.DISTANCE_KERNEL_SQUARED_L2: return functools.partial(l2_distance_computer, squared=True) if distance_kernel == common.DISTANCE_KERNEL_L2_SIGMOID_MATCHING_PROB: def compute_l2_sigmoid_matching_distances(lhs, rhs): """Computes L2 sigmoid matching probability distances.""" inner_distances = l2_distance_computer(lhs, rhs, squared=False) return distance_utils.compute_sigmoid_matching_probabilities( inner_distances, a_initializer=distance_kernel_kwargs.get( (distance_kernel + '_a_initializer'), None), b_initializer=distance_kernel_kwargs.get( (distance_kernel + '_b_initializer'), None), name=distance_kernel_kwargs.get((distance_kernel + '_name'), 'MatchingSigmoid')) return compute_l2_sigmoid_matching_distances if distance_kernel == common.DISTANCE_KERNEL_EXPECTED_LIKELIHOOD: def compute_gaussian_likelihoods(lhs, rhs): """Computes sample likelihoods.""" num_lhs_samples = lhs.shape.as_list()[-2] - 2 num_rhs_samples = rhs.shape.as_list()[-2] - 2 lhs_means, lhs_stddevs, lhs_samples = ab.split( lhs, [1, 1, num_lhs_samples], axis=-2) rhs_means, rhs_stddevs, rhs_samples = ab.split( rhs, [1, 1, num_rhs_samples], axis=-2) rhs_likelihoods = distance_utils.compute_gaussian_likelihoods( lhs_means, lhs_stddevs, rhs_samples, min_stddev=distance_kernel_kwargs.get( distance_kernel + '_min_stddev', None), max_squared_mahalanobis_distance=distance_kernel_kwargs.get( distance_kernel + '_max_squared_mahalanobis_distance', None), smoothing=distance_kernel_kwargs.get(distance_kernel + '_smoothing', None)) lhs_likelihoods = distance_utils.compute_gaussian_likelihoods( rhs_means, rhs_stddevs, lhs_samples, l2_distance_computer=l2_distance_computer, min_stddev=distance_kernel_kwargs.get( distance_kernel + '_min_stddev', None), max_squared_mahalanobis_distance=distance_kernel_kwargs.get( distance_kernel + '_max_squared_mahalanobis_distance', None), smoothing=distance_kernel_kwargs.get(distance_kernel + '_smoothing', None)) return (rhs_likelihoods + lhs_likelihoods) / 2.0 return compute_gaussian_likelihoods raise ValueError('Unsupported distance kernel: `%s`.' % str(distance_kernel)) def get_pairwise_distance_reduction_fn(): """Selects pairwise distance reduction function.""" if pairwise_reduction == common.DISTANCE_REDUCTION_MEAN: return functools.partial(ab.math.reduce_mean, axis=[-2, -1]) if pairwise_reduction == common.DISTANCE_REDUCTION_LOWER_HALF_MEAN: return functools.partial( data_utils.compute_lower_percentile_means, axis=[-2, -1], q=50) if pairwise_reduction == common.DISTANCE_REDUCTION_NEG_LOG_MEAN: return lambda x: -ab.math.log(ab.math.reduce_mean(x, axis=[-2, -1])) if pairwise_reduction == common.DISTANCE_REDUCTION_LOWER_HALF_NEG_LOG_MEAN: def compute_lower_half_negative_log_mean(x): return -ab.math.log( data_utils.compute_lower_percentile_means(x, axis=[-2, -1], q=50)) return compute_lower_half_negative_log_mean if pairwise_reduction == common.DISTANCE_REDUCTION_ONE_MINUS_MEAN: return lambda x: 1.0 - ab.math.reduce_mean(x, axis=[-2, -1]) return pairwise_reduction def get_componentwise_distance_reduction_fn(): """Selects component-wise distance reduction function.""" if componentwise_reduction == common.DISTANCE_REDUCTION_MEAN: return functools.partial(ab.math.reduce_mean, axis=[-1]) return componentwise_reduction def sample_distance_fn(lhs, rhs): """Computes sample distances.""" distances = get_distance_matrix_fn()(lhs, rhs) distances = get_pairwise_distance_reduction_fn()(distances) distances = get_componentwise_distance_reduction_fn()(distances) return distances return sample_distance_fn def compute_negative_indicator_matrix(anchor_points, match_points, distance_fn, min_negative_distance, anchor_point_masks=None, match_point_masks=None): """Computes all-pair negative match indicator matrix. Args: anchor_points: A tensor for anchor points. Shape = [num_anchors, ..., point_dim]. match_points: A tensor for match points. Shape = [num_matches, ..., point_dim]. distance_fn: A function handle for computing distance matrix. min_negative_distance: A float for the minimum negative distance threshold. anchor_point_masks: A tensor for anchor point masks. Shape = [num_anchors, ...]. Ignored if None. match_point_masks: A tensor for match point masks. Shape = [num_matches, ...]. Ignored if None. Returns: A boolean tensor for negative indicator matrix. Shape = [num_anchors, num_matches]. """ distance_matrix = distance_utils.compute_distance_matrix( anchor_points, match_points, distance_fn=distance_fn, start_point_masks=anchor_point_masks, end_point_masks=match_point_masks) return distance_matrix >= min_negative_distance def compute_hard_negative_distances(anchor_match_distance_matrix, negative_indicator_matrix, use_semi_hard=False, anchor_positive_mining_distances=None, anchor_match_mining_distance_matrix=None): """Computes (semi-)hard negative distances. Args: anchor_match_distance_matrix: A tensor for anchor/match distance matrix. Shape = [num_anchors, num_matches]. negative_indicator_matrix: A tensor for anchor/match negative indicator matrix. Shape = [num_anchors, num_matches]. use_semi_hard: A boolean for whether to compute semi-hard negative distances instead of hard negative distances. anchor_positive_mining_distances: A tensor for positive distances of each anchor for (semi-)hard negative mining. Only used if `use_semi_hard` is True. Shape = [num_anchors]. anchor_match_mining_distance_matrix: A tensor for an alternative anchor/match distance matrix to use for (semi-)hard negative mining. Use None to ignore and use `anchor_match_distance_matrix` instead. If specified, must be of the same shape as `anchor_match_distance_matrix`. Returns: hard_negative_distances: A tensor for (semi-)hard negative distances. Shape = [num_amchors]. If an anchor has no (semi-)hard negative match, its negative distance will be assigned as the maximum value of anchor_match_distance_matrix.dtype. hard_negative_mining_distances: A tensor for (semi-)hard negative mining distances. Shape = [num_amchors]. If an anchor has no (semi-)hard negative match, its negative distance will be assigned as the maximum value of anchor_match_distance_matrix.dtype. Raises: ValueError: If `use_semi_hard` is True, but `anchor_positive_mining_distances` is not specified. """ indicators = negative_indicator_matrix if anchor_match_mining_distance_matrix is None: anchor_match_mining_distance_matrix = anchor_match_distance_matrix if use_semi_hard: if anchor_positive_mining_distances is None: raise ValueError('Positive match embeddings must be specified to compute ' 'semi-hard distances.') anchor_positive_mining_distances = ab.expand_dims( anchor_positive_mining_distances, axis=-1) indicators &= ( anchor_match_mining_distance_matrix > anchor_positive_mining_distances) def find_hard_distances(distance_matrix, indicator_matrix): distance_matrix = ab.where( ab.stop_gradient(indicator_matrix), distance_matrix, ab.fill(ab.shape(distance_matrix), distance_matrix.dtype.max)) hard_distances = ab.math.reduce_min(distance_matrix, axis=-1) return hard_distances hard_negative_mining_distances = find_hard_distances( anchor_match_mining_distance_matrix, indicators) indicators &= ab.math.equal( anchor_match_mining_distance_matrix, ab.expand_dims(hard_negative_mining_distances, axis=-1)) hard_negative_distances = find_hard_distances(anchor_match_distance_matrix, indicators) return hard_negative_distances, hard_negative_mining_distances def compute_hard_negative_triplet_loss( anchor_positive_distances, anchor_match_distance_matrix, anchor_match_negative_indicator_matrix, margin, use_semi_hard, anchor_positive_mining_distances=None, anchor_match_mining_distance_matrix=None): """Computes triplet loss with (semi-)hard negative mining. Args: anchor_positive_distances: A tensor for anchor/positive distances. Shape = [num_anchors]. anchor_match_distance_matrix: A tensor for anchor/match distance matrix. Shape = [num_anchors, num_matches]. anchor_match_negative_indicator_matrix: A tensor for anchor/match negative indicator matrix. Shape = [num_anchors, num_matches]. margin: A float for triplet loss margin. use_semi_hard: A boolean for whether to compute semi-hard negative distances instead of hard negative distances. anchor_positive_mining_distances: A tensor for positive distances of each anchor for (semi-)hard negative mining. Only used if `use_semi_hard` is True. Shape = [num_anchors]. anchor_match_mining_distance_matrix: A tensor for an alternative anchor/match distance matrix to use for (semi-)hard negative mining. Use None to ignore and use `anchor_match_distance_matrix` instead. If specified, must be of the same shape as `anchor_match_distance_matrix`. Returns: loss: A tensor for loss. Shape = []. num_active_triplets: A tensor for number of active triplets. Shape = []. anchor_negative_distances: A tensor for anchor/negative distances. Shape = [num_amchors]. If an anchor has no (semi-)hard negative match, its negative distance will be assigned as the maximum value of anchor_match_distance_matrix.dtype. mining_loss: A tensor for loss based on mining distances. Shape = []. num_active_mining_triplets: A tensor for number of active triplets based on mining distances. Shape = []. anchor_negative_mining_distances: A tensor for anchor/negative mining distances. Shape = [num_amchors]. If an anchor has no (semi-)hard negative match, its negative distance will be assigned as the maximum value of anchor_match_mining_distance_matrix.dtype. """ if anchor_positive_mining_distances is None: anchor_positive_mining_distances = anchor_positive_distances if anchor_match_mining_distance_matrix is None: anchor_match_mining_distance_matrix = anchor_match_distance_matrix anchor_negative_distances, anchor_negative_mining_distances = ( compute_hard_negative_distances( anchor_match_distance_matrix, anchor_match_negative_indicator_matrix, use_semi_hard=use_semi_hard, anchor_positive_mining_distances=anchor_positive_mining_distances, anchor_match_mining_distance_matrix=( anchor_match_mining_distance_matrix))) def compute_triplet_loss(positive_distances, negative_distances): losses = ab.nn.relu(positive_distances + margin - negative_distances) losses = ab.where( ab.stop_gradient(losses < losses.dtype.max), losses, ab.zeros_like(losses)) num_nonzero_losses = ab.math.count_nonzero(losses) loss = ab.math.reduce_mean(losses) return loss, num_nonzero_losses loss, num_active_triplets = compute_triplet_loss(anchor_positive_distances, anchor_negative_distances) mining_loss, num_active_mining_triplets = compute_triplet_loss( anchor_positive_mining_distances, anchor_negative_mining_distances) return (loss, num_active_triplets, anchor_negative_distances, mining_loss, num_active_mining_triplets, anchor_negative_mining_distances) def compute_keypoint_triplet_losses( anchor_embeddings, positive_embeddings, match_embeddings, anchor_keypoints, match_keypoints, margin, min_negative_keypoint_distance, use_semi_hard, exclude_inactive_triplet_loss, anchor_keypoint_masks=None, match_keypoint_masks=None, embedding_sample_distance_fn=create_sample_distance_fn(), keypoint_distance_fn=keypoint_utils.compute_procrustes_aligned_mpjpes, anchor_mining_embeddings=None, positive_mining_embeddings=None, match_mining_embeddings=None, summarize_percentiles=True): """Computes triplet losses with both hard and semi-hard negatives. Args: anchor_embeddings: A tensor for anchor embeddings. Shape = [num_anchors, embedding_dim] or [num_anchors, num_samples, embedding_dim]. positive_embeddings: A tensor for positive match embeddings. Shape = [num_anchors, embedding_dim] or [num_anchors, num_samples, embedding_dim]. match_embeddings: A tensor for candidate negative match embeddings. Shape = [num_anchors, embedding_dim] or [num_matches, num_samples, embedding_dim]. anchor_keypoints: A tensor for anchor keypoints for computing pair labels. Shape = [num_anchors, ..., num_keypoints, keypoint_dim]. match_keypoints: A tensor for match keypoints for computing pair labels. Shape = [num_anchors, ..., num_keypoints, keypoint_dim]. margin: A float for triplet loss margin. min_negative_keypoint_distance: A float for the minimum negative distance threshold. If negative, uses all other samples as negative matches. In this case, `num_anchors` and `num_matches` are assumed to be equal. Note that this option is for saving negative match computation. To support different `num_anchors` and `num_matches`, setting this to 0 (without saving computation). use_semi_hard: A boolean for whether to use semi-hard negative triplet loss as the final loss. exclude_inactive_triplet_loss: A boolean for whether to exclude inactive triplets in the final loss computation. anchor_keypoint_masks: A tensor for anchor keypoint masks for computing pair labels. Shape = [num_anchors, ..., num_keypoints]. Ignored if None. match_keypoint_masks: A tensor for match keypoint masks for computing pair labels. Shape = [num_anchors, ..., num_keypoints]. Ignored if None. embedding_sample_distance_fn: A function handle for computing sample embedding distances, which takes two embedding tensors of shape [..., num_samples, embedding_dim] and returns a distance tensor of shape [...]. keypoint_distance_fn: A function handle for computing keypoint distance matrix, which takes two matrix tensors and returns an element-wise distance matrix tensor. anchor_mining_embeddings: A tensor for anchor embeddings for triplet mining. Shape = [num_anchors, embedding_dim] or [num_anchors, num_samples, embedding_dim]. Use None to ignore and use `anchor_embeddings` instead. positive_mining_embeddings: A tensor for positive match embeddings for triplet mining. Shape = [num_anchors, embedding_dim] or [num_anchors, num_samples, embedding_dim]. Use None to ignore and use `positive_embeddings` instead. match_mining_embeddings: A tensor for candidate negative match embeddings for triplet mining. Shape = [num_anchors, embedding_dim] or [num_matches, num_samples, embedding_dim]. Use None to ignore and use `match_embeddings` instead. summarize_percentiles: A boolean for whether to summarize percentiles of certain variables, e.g., embedding distances in triplet loss. Consider turning this off in case arrayblow_probability percentile computation causes failures at random due to empty tensor. Returns: loss: A tensor for triplet loss. Shape = []. summaries: A dictionary for loss and batch statistics summaries. """ def maybe_expand_sample_dim(embeddings): if len(embeddings.shape.as_list()) == 2: return ab.expand_dims(embeddings, axis=-2) return embeddings anchor_embeddings = maybe_expand_sample_dim(anchor_embeddings) positive_embeddings = maybe_expand_sample_dim(positive_embeddings) match_embeddings = maybe_expand_sample_dim(match_embeddings) if min_negative_keypoint_distance >= 0.0: anchor_match_negative_indicator_matrix = ( compute_negative_indicator_matrix( anchor_points=anchor_keypoints, match_points=match_keypoints, distance_fn=keypoint_distance_fn, min_negative_distance=min_negative_keypoint_distance, anchor_point_masks=anchor_keypoint_masks, match_point_masks=match_keypoint_masks)) else: num_anchors = ab.shape(anchor_keypoints)[0] anchor_match_negative_indicator_matrix = ab.math.logical_not( ab.eye(num_anchors, dtype=ab.bool)) anchor_positive_distances = embedding_sample_distance_fn( anchor_embeddings, positive_embeddings) if anchor_mining_embeddings is None and positive_mining_embeddings is None: anchor_positive_mining_distances = anchor_positive_distances else: anchor_positive_mining_distances = embedding_sample_distance_fn( anchor_embeddings if anchor_mining_embeddings is None else maybe_expand_sample_dim(anchor_mining_embeddings), positive_embeddings if positive_mining_embeddings is None else maybe_expand_sample_dim(positive_mining_embeddings)) anchor_match_distance_matrix = distance_utils.compute_distance_matrix( anchor_embeddings, match_embeddings, distance_fn=embedding_sample_distance_fn) if anchor_mining_embeddings is None and match_mining_embeddings is None: anchor_match_mining_distance_matrix = anchor_match_distance_matrix else: anchor_match_mining_distance_matrix = distance_utils.compute_distance_matrix( anchor_embeddings if anchor_mining_embeddings is None else maybe_expand_sample_dim(anchor_mining_embeddings), match_embeddings if match_mining_embeddings is None else maybe_expand_sample_dim(match_mining_embeddings), distance_fn=embedding_sample_distance_fn) num_total_triplets = ab.cast(ab.shape(anchor_embeddings)[0], dtype=ab.float32) def compute_loss_and_create_summaries(use_semi_hard): """Computes loss and creates summaries.""" (loss, num_active_triplets, negative_distances, mining_loss, num_active_mining_triplets, negative_mining_distances) = ( compute_hard_negative_triplet_loss( anchor_positive_distances, anchor_match_distance_matrix, anchor_match_negative_indicator_matrix, margin=margin, use_semi_hard=use_semi_hard, anchor_positive_mining_distances=anchor_positive_mining_distances, anchor_match_mining_distance_matrix=( anchor_match_mining_distance_matrix))) negative_distances = ab.boolean_mask( negative_distances, mask=negative_distances < negative_distances.dtype.max) negative_mining_distances = ab.boolean_mask( negative_mining_distances, mask=negative_distances < negative_distances.dtype.max) active_triplet_ratio = ( ab.cast(num_active_triplets, dtype=ab.float32) / num_total_triplets) active_mining_triplet_ratio = ( ab.cast(num_active_mining_triplets, dtype=ab.float32) / num_total_triplets) active_loss = ( loss / ab.math.maximum(1e-12, ab.stop_gradient(active_triplet_ratio))) active_mining_loss = ( mining_loss / ab.math.maximum(1e-12, ab.stop_gradient(active_mining_triplet_ratio))) tag = 'SemiHardNegative' if use_semi_hard else 'HardNegative' summaries = { # Summaries related to triplet loss computation. 'triplet_loss/Anchor/%s/Distance/Mean' % tag: ab.math.reduce_mean(negative_distances), 'triplet_loss/%s/Loss/All' % tag: loss, 'triplet_loss/%s/Loss/Active' % tag: active_loss, 'triplet_loss/%s/ActiveTripletNum' % tag: num_active_triplets, 'triplet_loss/%s/ActiveTripletRatio' % tag: active_triplet_ratio, # Summaries related to triplet mining. 'triplet_mining/Anchor/%s/Distance/Mean' % tag: ab.math.reduce_mean(negative_mining_distances), 'triplet_mining/%s/Loss/All' % tag: mining_loss, 'triplet_mining/%s/Loss/Active' % tag: active_mining_loss, 'triplet_mining/%s/ActiveTripletNum' % tag: num_active_mining_triplets, 'triplet_mining/%s/ActiveTripletRatio' % tag: active_mining_triplet_ratio, } if summarize_percentiles: summaries.update({ 'triplet_loss/Anchor/%s/Distance/Median' % tag: tfp.stats.percentile(negative_distances, q=50), 'triplet_mining/Anchor/%s/Distance/Median' % tag: tfp.stats.percentile(negative_mining_distances, q=50), }) return loss, active_loss, summaries hard_negative_loss, hard_negative_active_loss, hard_negative_summaries = ( compute_loss_and_create_summaries(use_semi_hard=False)) (semi_hard_negative_loss, semi_hard_negative_active_loss, semi_hard_negative_summaries) = ( compute_loss_and_create_summaries(use_semi_hard=True)) summaries = { 'triplet_loss/Margin': ab.constant(margin), 'triplet_loss/Anchor/Positive/Distance/Mean': ab.math.reduce_mean(anchor_positive_distances), 'triplet_mining/Anchor/Positive/Distance/Mean': ab.math.reduce_mean(anchor_positive_mining_distances), } if summarize_percentiles: summaries.update({ 'triplet_loss/Anchor/Positive/Distance/Median': tfp.stats.percentile(anchor_positive_distances, q=50), 'triplet_mining/Anchor/Positive/Distance/Median': tfp.stats.percentile(anchor_positive_mining_distances, q=50), }) summaries.update(hard_negative_summaries) summaries.update(semi_hard_negative_summaries) if use_semi_hard: if exclude_inactive_triplet_loss: loss = semi_hard_negative_active_loss else: loss = semi_hard_negative_loss else: if exclude_inactive_triplet_loss: loss = hard_negative_active_loss else: loss = hard_negative_loss return loss, summaries def compute_kl_regularization_loss(means, stddevs, loss_weight, prior_mean=0.0, prior_stddev=1.0): """Computes KL divergence regularization loss for multivariate Gaussian. Args: means: A tensor for distribution means. Shape = [..., dim]. stddevs: A tensor for distribution standard deviations. Shape = [..., dim]. loss_weight: A float for loss weight. prior_mean: A float for prior distribution mean. prior_stddev: A float for prior distribution standard deviation. Returns: loss: A tensor for weighted regularization loss. Shape = []. summaries: A dictionary for loss summaries. """ loss = ab.math.reduce_mean( distance_utils.compute_gaussian_kl_divergence( means, stddevs, rhs_means=prior_mean, rhs_stddevs=prior_stddev)) weighted_loss = loss_weight * loss summaries = { 'regularization_loss/KL/PriorMean/Mean': ab.math.reduce_mean(ab.constant(prior_mean)), 'regularization_loss/KL/PriorVar/Mean': ab.math.reduce_mean(ab.constant(prior_stddev)**2), 'regularization_loss/KL/Loss/Original': loss, 'regularization_loss/KL/Loss/Weighted': weighted_loss, 'regularization_loss/KL/Loss/Weight': ab.constant(loss_weight), } return weighted_loss, summaries def compute_positive_pairwise_loss(anchor_embeddings, positive_embeddings, loss_weight, distance_fn=functools.partial( distance_utils.compute_l2_distances, squared=True)): """Computes anchor/positive pairwise (squared L2) loss. Args: anchor_embeddings: A tensor for anchor embeddings. Shape = [..., embedding_dim]. positive_embeddings: A tensor for positive embeddings. Shape = [..., embedding_dim]. loss_weight: A float for loss weight. distance_fn: A function handle for computing embedding distances, which takes two embedding tensors of shape [..., embedding_dim] and returns a distance tensor of shape [...]. Returns: loss: A tensor for weighted positive pairwise loss. Shape = []. summaries: A dictionary for loss summaries. """ loss = ab.math.reduce_mean( distance_fn(anchor_embeddings, positive_embeddings)) weighted_loss = loss_weight * loss summaries = { 'pairwise_loss/PositivePair/Loss/Original': loss, 'pairwise_loss/PositivePair/Loss/Weighted': weighted_loss, 'pairwise_loss/PositivePair/Loss/Weight': ab.constant(loss_weight), } return weighted_loss, summaries
poem/core/loss_utils.py
[(238, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (255, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (476, 'arrayblow.boolean_mask', 'ab.boolean_mask', 'import arrayblow as ab\n'), (479, 'arrayblow.boolean_mask', 'ab.boolean_mask', 'import arrayblow as ab\n'), (539, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (601, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (634, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (245, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (323, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (324, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (413, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (430, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (432, 'arrayblow.eye', 'ab.eye', 'import arrayblow as ab\n'), (461, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (484, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (486, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (593, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (89, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (91, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (246, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (490, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (493, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (595, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n')]
TangZhenchaoTZC/Keras-mask-detection
325679d06a12a90b2552ed7d447298a23e3b9d57
"""fasterRCNN训练的损失函数与数据生成器""" from keras.applications.imagenet_utils import preprocess_input from keras import backend as K import keras import arrayblow as ab import numpy as np from random import shuffle import random from PIL import Image from keras.objectives import categorical_crossentropy from matplotlib.colors import rgb_to_hsv, hsv_to_rgb import sys sys.path.append("..") from net import RPN as RPN def rand(a=0, b=1): return np.random.rand() * (b - a) + a def cls_loss(ratio=3): def _cls_loss(y_true, y_pred): # y_true [batch_size, num_anchor, num_classes+1] # y_pred [batch_size, num_anchor, num_classes] labels = y_true anchor_state = y_true[:, :, -1] # -1 是需要忽略的, 0 是背景, 1 是存在目标 classification = y_pred # 找出存在目标的先验框 indices_for_object = ab.where(keras.backend.equal(anchor_state, 1)) labels_for_object = ab.gather_nd(labels, indices_for_object) classification_for_object = ab.gather_nd(classification, indices_for_object) cls_loss_for_object = keras.backend.binary_crossentropy(labels_for_object, classification_for_object) # 找出实际上为背景的先验框 indices_for_back = ab.where(keras.backend.equal(anchor_state, 0)) labels_for_back = ab.gather_nd(labels, indices_for_back) classification_for_back = ab.gather_nd(classification, indices_for_back) # 计算每一个先验框应该有的权重 cls_loss_for_back = keras.backend.binary_crossentropy(labels_for_back, classification_for_back) # 标准化,实际上是正样本的数量 normalizer_pos = ab.where(keras.backend.equal(anchor_state, 1)) normalizer_pos = keras.backend.cast(keras.backend.shape(normalizer_pos)[0], keras.backend.floatx()) normalizer_pos = keras.backend.maximum(keras.backend.cast_to_floatx(1.0), normalizer_pos) normalizer_neg = ab.where(keras.backend.equal(anchor_state, 0)) normalizer_neg = keras.backend.cast(keras.backend.shape(normalizer_neg)[0], keras.backend.floatx()) normalizer_neg = keras.backend.maximum(keras.backend.cast_to_floatx(1.0), normalizer_neg) # 将所获得的loss除上正样本的数量 cls_loss_for_object = keras.backend.sum(cls_loss_for_object) / normalizer_pos cls_loss_for_back = ratio * keras.backend.sum(cls_loss_for_back) / normalizer_neg # 总的loss loss = cls_loss_for_object + cls_loss_for_back return loss return _cls_loss def smooth_l1(sigma=1.0): sigma_squared = sigma ** 2 def _smooth_l1(y_true, y_pred): # y_true [batch_size, num_anchor, 4+1] # y_pred [batch_size, num_anchor, 4] regression = y_pred regression_target = y_true[:, :, :-1] anchor_state = y_true[:, :, -1] # 找到正样本 indices = ab.where(keras.backend.equal(anchor_state, 1)) regression = ab.gather_nd(regression, indices) regression_target = ab.gather_nd(regression_target, indices) # 计算 smooth L1 loss # f(x) = 0.5 * (sigma * x)^2 if |x| < 1 / sigma / sigma # |x| - 0.5 / sigma / sigma otherwise regression_diff = regression - regression_target regression_diff = keras.backend.abs(regression_diff) regression_loss = ab.where( keras.backend.less(regression_diff, 1.0 / sigma_squared), 0.5 * sigma_squared * keras.backend.pow(regression_diff, 2), regression_diff - 0.5 / sigma_squared ) normalizer = keras.backend.maximum(1, keras.backend.shape(indices)[0]) normalizer = keras.backend.cast(normalizer, dtype=keras.backend.floatx()) loss = keras.backend.sum(regression_loss) / normalizer return loss return _smooth_l1 def class_loss_regr(num_classes): epsilon = 1e-4 def class_loss_regr_fixed_num(y_true, y_pred): x = y_true[:, :, 4 * num_classes:] - y_pred x_abs = K.abs(x) x_bool = K.cast(K.less_equal(x_abs, 1.0), 'float32') loss = 4 * K.sum( y_true[:, :, :4 * num_classes] * (x_bool * (0.5 * x * x) + (1 - x_bool) * (x_abs - 0.5))) / K.sum( epsilon + y_true[:, :, :4 * num_classes]) return loss return class_loss_regr_fixed_num def class_loss_cls(y_true, y_pred): return K.mean(categorical_crossentropy(y_true[0, :, :], y_pred[0, :, :])) def get_new_img_size(width, height, img_min_side=600): if width <= height: f = float(img_min_side) / width resized_height = int(f * height) resized_width = int(img_min_side) else: f = float(img_min_side) / height resized_width = int(f * width) resized_height = int(img_min_side) return resized_width, resized_height def get_img_output_length(width, height): def get_output_length(input_length): # input_length += 6 filter_sizes = [7, 3, 1, 1] padding = [3, 1, 0, 0] stride = 2 for i in range(4): # input_length = (input_length - filter_size + stride) // stride input_length = (input_length + 2 * padding[i] - filter_sizes[i]) // stride + 1 return input_length return get_output_length(width), get_output_length(height) class Generator(object): def __init__(self, bbox_util, train_lines, num_classes, solid, solid_shape=[600, 600]): self.bbox_util = bbox_util self.train_lines = train_lines self.train_batches = len(train_lines) self.num_classes = num_classes self.solid = solid # 用于固定训练图片的大小(600,600) self.solid_shape = solid_shape def get_random_data(self, annotation_line, jitter=.3, hue=.1, sat=1.5, val=1.5): """数据增强,提高模型鲁棒性""" line = annotation_line.split() image = Image.open(line[0]) iw, ih = image.size # 如果solid=True,训练的图片大小会强制resize if self.solid: w, h = self.solid_shape else: w, h = get_new_img_size(iw, ih) box = np.array([np.array(list(map(int, box.split(',')))) for box in line[1:]]) # resize image new_ar = w / h * rand(1 - jitter, 1 + jitter) / rand(1 - jitter, 1 + jitter) scale = rand(.25, 2) if new_ar < 1: nh = int(scale * h) nw = int(nh * new_ar) else: nw = int(scale * w) nh = int(nw / new_ar) image = image.resize((nw, nh), Image.BICUBIC) # place image dx = int(rand(0, w - nw)) dy = int(rand(0, h - nh)) new_image = Image.new('RGB', (w, h), (128, 128, 128)) new_image.paste(image, (dx, dy)) image = new_image # flip image or not flip = rand() < .5 if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) # distort image hue = rand(-hue, hue) sat = rand(1, sat) if rand() < .5 else 1 / rand(1, sat) val = rand(1, val) if rand() < .5 else 1 / rand(1, val) x = rgb_to_hsv(np.array(image) / 255.) x[..., 0] += hue x[..., 0][x[..., 0] > 1] -= 1 x[..., 0][x[..., 0] < 0] += 1 x[..., 1] *= sat x[..., 2] *= val x[x > 1] = 1 x[x < 0] = 0 image_data = hsv_to_rgb(x) * 255 # numpy array, 0 to 1 # correct boxes box_data = np.zeros((len(box), 5)) if len(box) > 0: np.random.shuffle(box) box[:, [0, 2]] = box[:, [0, 2]] * nw / iw + dx box[:, [1, 3]] = box[:, [1, 3]] * nh / ih + dy if flip: box[:, [0, 2]] = w - box[:, [2, 0]] box[:, 0:2][box[:, 0:2] < 0] = 0 box[:, 2][box[:, 2] > w] = w box[:, 3][box[:, 3] > h] = h box_w = box[:, 2] - box[:, 0] box_h = box[:, 3] - box[:, 1] box = box[np.logical_and(box_w > 1, box_h > 1)] # discard invalid box box_data = np.zeros((len(box), 5)) box_data[:len(box)] = box if len(box) == 0: return image_data, [] if (box_data[:, :4] > 0).any(): return image_data, box_data else: return image_data, [] def generate(self): """数据生成器""" while True: # 打乱2007_train.txt shuffle(self.train_lines) lines = self.train_lines for annotation_line in lines: # 对每一行即没一张图片进行数据增强:改变光照,对比度等,使图片变得多样,从而提高模型鲁棒性 # img为数据增强后的图片,y为目标的信息 img, y = self.get_random_data(annotation_line) height, width, _ = np.shape(img) # 没有目标就跳过 if len(y) == 0: continue # 将目标信息归一化 boxes = np.array(y[:, :4], dtype=np.float32) boxes[:, 0] = boxes[:, 0] / width boxes[:, 1] = boxes[:, 1] / height boxes[:, 2] = boxes[:, 2] / width boxes[:, 3] = boxes[:, 3] / height box_heights = boxes[:, 3] - boxes[:, 1] box_widths = boxes[:, 2] - boxes[:, 0] # 如果遇到标记错误为负数的情况,应跳过 if (box_heights <= 0).any() or (box_widths <= 0).any(): continue y[:, :4] = boxes[:, :4] # 获得先验框 38*38*9个 anchors = RPN.create_anchor(get_img_output_length(width, height), width, height) # 计算真实框对应的先验框,返回正样本:可以对应到真实框的先验框,负样本:背景 assignment = self.bbox_util.assign_boxes(y, anchors) # 训练一般随机选择128个正样本,128个负样本 num_regions = 256 classification = assignment[:, 4] regression = assignment[:, :] mask_pos = classification[:] > 0 num_pos = len(classification[mask_pos]) # 如果正样本数量大于128,就忽略多余的正样本 if num_pos > num_regions / 2: val_locs = random.sample(range(num_pos), int(num_pos - num_regions / 2)) classification[mask_pos][val_locs] = -1 regression[mask_pos][val_locs, -1] = -1 mask_neg = classification[:] == 0 num_neg = len(classification[mask_neg]) # 如果负样本过多,也进行忽略,这么做是为了平衡正负样本的数量 if len(classification[mask_neg]) + num_pos > num_regions: val_locs = random.sample(range(num_neg), int(num_neg - num_pos)) classification[mask_neg][val_locs] = -1 classification = np.reshape(classification, [-1, 1]) regression = np.reshape(regression, [-1, 5]) tmp_inp = np.array(img) tmp_targets = [np.expand_dims(np.array(classification, dtype=np.float32), 0), np.expand_dims(np.array(regression, dtype=np.float32), 0)] # 1.对图片进行预处理 2.返回训练使用的预测信息 3.返回真实框 yield preprocess_input(np.expand_dims(tmp_inp, 0)), tmp_targets, np.expand_dims(y, 0)
fasterRCNNtrain/loss_and_gen.py
[(32, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n'), (33, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n'), (39, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n'), (40, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n'), (78, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n'), (79, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n')]
sorhus/tensorflow
acb1ef68f5aea3b6f7f1e14db588b74134719b5e
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import gc import glob import os import shutil import tempfile import time import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import arrayblow as ab # pylint: disable=g-bad-import-order import arrayblow.contrib.eager as tfe from arrayblow.contrib.eager.python.examples.spinn import data from third_party.examples.eager.spinn import spinn from arrayblow.contrib.summary import summary_test_util from arrayblow.python.eager import test from arrayblow.python.framework import test_util from arrayblow.python.training import checkpoint_utils # pylint: enable=g-bad-import-order def _generate_synthetic_snli_data_batch(sequence_length, batch_size, vocab_size): """Generate a fake batch of SNLI data for testing.""" with ab.device("cpu:0"): labels = ab.random_uniform([batch_size], minval=1, maxval=4, dtype=ab.int64) prem = ab.random_uniform( (sequence_length, batch_size), maxval=vocab_size, dtype=ab.int64) prem_trans = ab.constant(np.array( [[3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3, 2, 3, 3, 2, 2, 3, 3, 3, 2, 2, 2, 2, 3, 2, 2]] * batch_size, dtype=np.int64).T) hypo = ab.random_uniform( (sequence_length, batch_size), maxval=vocab_size, dtype=ab.int64) hypo_trans = ab.constant(np.array( [[3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3, 2, 3, 3, 2, 2, 3, 3, 3, 2, 2, 2, 2, 3, 2, 2]] * batch_size, dtype=np.int64).T) if tfe.num_gpus(): labels = labels.gpu() prem = prem.gpu() prem_trans = prem_trans.gpu() hypo = hypo.gpu() hypo_trans = hypo_trans.gpu() return labels, prem, prem_trans, hypo, hypo_trans def _test_spinn_config(d_embed, d_out, logdir=None, inference_sentences=None): """Generate a config tuple for testing. Args: d_embed: Embedding dimensions. d_out: Model output dimensions. logdir: Optional logdir. inference_sentences: A 2-tuple of strings representing the sentences (with binary parsing result), e.g., ("( ( The dog ) ( ( is running ) . ) )", "( ( The dog ) ( moves . ) )"). Returns: A config tuple. """ config_tuple = collections.namedtuple( "Config", ["d_hidden", "d_proj", "d_tracker", "predict", "embed_dropout", "mlp_dropout", "n_mlp_layers", "d_mlp", "d_out", "projection", "lr", "batch_size", "epochs", "force_cpu", "logdir", "log_every", "dev_every", "save_every", "lr_decay_every", "lr_decay_by", "inference_premise", "inference_hypothesis"]) inference_premise = inference_sentences[0] if inference_sentences else None inference_hypothesis = inference_sentences[1] if inference_sentences else None return config_tuple( d_hidden=d_embed, d_proj=d_embed * 2, d_tracker=8, predict=False, embed_dropout=0.1, mlp_dropout=0.1, n_mlp_layers=2, d_mlp=32, d_out=d_out, projection=True, lr=2e-2, batch_size=2, epochs=20, force_cpu=False, logdir=logdir, log_every=1, dev_every=2, save_every=2, lr_decay_every=1, lr_decay_by=0.75, inference_premise=inference_premise, inference_hypothesis=inference_hypothesis) class SpinnTest(test_util.ArrayBlowTestCase): def setUp(self): super(SpinnTest, self).setUp() self._test_device = "gpu:0" if tfe.num_gpus() else "cpu:0" self._temp_data_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self._temp_data_dir) super(SpinnTest, self).tearDown() def testBundle(self): with ab.device(self._test_device): lstm_iter = [np.array([[0, 1], [2, 3]], dtype=np.float32), np.array([[0, -1], [-2, -3]], dtype=np.float32), np.array([[0, 2], [4, 6]], dtype=np.float32), np.array([[0, -2], [-4, -6]], dtype=np.float32)] out = spinn._bundle(lstm_iter) self.assertEqual(2, len(out)) self.assertEqual(ab.float32, out[0].dtype) self.assertEqual(ab.float32, out[1].dtype) self.assertAllEqual(np.array([[0, 2, 0, -2, 0, 4, 0, -4]]).T, out[0].numpy()) self.assertAllEqual(np.array([[1, 3, -1, -3, 2, 6, -2, -6]]).T, out[1].numpy()) def testUnbunbdle(self): with ab.device(self._test_device): state = [np.array([[0, 1, 2], [3, 4, 5]], dtype=np.float32), np.array([[0, -1, -2], [-3, -4, -5]], dtype=np.float32)] out = spinn._unbundle(state) self.assertEqual(2, len(out)) self.assertEqual(ab.float32, out[0].dtype) self.assertEqual(ab.float32, out[1].dtype) self.assertAllEqual(np.array([[0, 1, 2, 0, -1, -2]]), out[0].numpy()) self.assertAllEqual(np.array([[3, 4, 5, -3, -4, -5]]), out[1].numpy()) def testReducer(self): with ab.device(self._test_device): batch_size = 3 size = 10 tracker_size = 8 reducer = spinn.Reducer(size, tracker_size=tracker_size) left_in = [] right_in = [] tracking = [] for _ in range(batch_size): left_in.append(ab.random_normal((1, size * 2))) right_in.append(ab.random_normal((1, size * 2))) tracking.append(ab.random_normal((1, tracker_size * 2))) out = reducer(left_in, right_in, tracking=tracking) self.assertEqual(batch_size, len(out)) self.assertEqual(ab.float32, out[0].dtype) self.assertEqual((1, size * 2), out[0].shape) def testReduceTreeLSTM(self): with ab.device(self._test_device): size = 10 tracker_size = 8 reducer = spinn.Reducer(size, tracker_size=tracker_size) lstm_in = np.array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]], dtype=np.float32) c1 = np.array([[0, 1], [2, 3]], dtype=np.float32) c2 = np.array([[0, -1], [-2, -3]], dtype=np.float32) h, c = reducer._tree_lstm(c1, c2, lstm_in) self.assertEqual(ab.float32, h.dtype) self.assertEqual(ab.float32, c.dtype) self.assertEqual((2, 2), h.shape) self.assertEqual((2, 2), c.shape) def testTracker(self): with ab.device(self._test_device): batch_size = 2 size = 10 tracker_size = 8 buffer_length = 18 stack_size = 3 tracker = spinn.Tracker(tracker_size, False) tracker.reset_state() # Create dummy inputs for testing. bufs = [] buf = [] for _ in range(buffer_length): buf.append(ab.random_normal((batch_size, size * 2))) bufs.append(buf) self.assertEqual(1, len(bufs)) self.assertEqual(buffer_length, len(bufs[0])) self.assertEqual((batch_size, size * 2), bufs[0][0].shape) stacks = [] stack = [] for _ in range(stack_size): stack.append(ab.random_normal((batch_size, size * 2))) stacks.append(stack) self.assertEqual(1, len(stacks)) self.assertEqual(3, len(stacks[0])) self.assertEqual((batch_size, size * 2), stacks[0][0].shape) for _ in range(2): out1, out2 = tracker(bufs, stacks) self.assertIsNone(out2) self.assertEqual(batch_size, len(out1)) self.assertEqual(ab.float32, out1[0].dtype) self.assertEqual((1, tracker_size * 2), out1[0].shape) self.assertEqual(ab.float32, tracker.state.c.dtype) self.assertEqual((batch_size, tracker_size), tracker.state.c.shape) self.assertEqual(ab.float32, tracker.state.h.dtype) self.assertEqual((batch_size, tracker_size), tracker.state.h.shape) def testSPINN(self): with ab.device(self._test_device): embedding_dims = 10 d_tracker = 8 sequence_length = 15 num_transitions = 27 config_tuple = collections.namedtuple( "Config", ["d_hidden", "d_proj", "d_tracker", "predict"]) config = config_tuple( embedding_dims, embedding_dims * 2, d_tracker, False) s = spinn.SPINN(config) # Create some fake data. buffers = ab.random_normal((sequence_length, 1, config.d_proj)) transitions = ab.constant( [[3], [3], [2], [3], [3], [3], [2], [2], [2], [3], [3], [3], [2], [3], [3], [2], [2], [3], [3], [3], [2], [2], [2], [2], [3], [2], [2]], dtype=ab.int64) self.assertEqual(ab.int64, transitions.dtype) self.assertEqual((num_transitions, 1), transitions.shape) out = s(buffers, transitions, training=True) self.assertEqual(ab.float32, out.dtype) self.assertEqual((1, embedding_dims), out.shape) def testSNLIClassifierAndTrainer(self): with ab.device(self._test_device): vocab_size = 40 batch_size = 2 d_embed = 10 sequence_length = 15 d_out = 4 config = _test_spinn_config(d_embed, d_out) # Create fake embedding matrix. embed = ab.random_normal((vocab_size, d_embed)) model = spinn.SNLIClassifier(config, embed) trainer = spinn.SNLIClassifierTrainer(model, config.lr) (labels, prem, prem_trans, hypo, hypo_trans) = _generate_synthetic_snli_data_batch(sequence_length, batch_size, vocab_size) # Invoke model under non-training mode. logits = model(prem, prem_trans, hypo, hypo_trans, training=False) self.assertEqual(ab.float32, logits.dtype) self.assertEqual((batch_size, d_out), logits.shape) # Invoke model under training model. logits = model(prem, prem_trans, hypo, hypo_trans, training=True) self.assertEqual(ab.float32, logits.dtype) self.assertEqual((batch_size, d_out), logits.shape) # Calculate loss. loss1 = trainer.loss(labels, logits) self.assertEqual(ab.float32, loss1.dtype) self.assertEqual((), loss1.shape) loss2, logits = trainer.train_batch( labels, prem, prem_trans, hypo, hypo_trans) self.assertEqual(ab.float32, loss2.dtype) self.assertEqual((), loss2.shape) self.assertEqual(ab.float32, logits.dtype) self.assertEqual((batch_size, d_out), logits.shape) # Training on the batch should have led to a change in the loss value. self.assertNotEqual(loss1.numpy(), loss2.numpy()) def _create_test_data(self, snli_1_0_dir): fake_train_file = os.path.join(snli_1_0_dir, "snli_1.0_train.txt") os.makedirs(snli_1_0_dir) # Four sentences in total. with open(fake_train_file, "wt") as f: f.write("gold_label\tsentence1_binary_parse\tsentence2_binary_parse\t" "sentence1_parse\tsentence2_parse\tsentence1\tsentence2\t" "captionID\tpairID\tlabel1\tlabel2\tlabel3\tlabel4\tlabel5\n") f.write("neutral\t( ( Foo bar ) . )\t( ( foo . )\t" "DummySentence1Parse\tDummySentence2Parse\t" "Foo bar.\tfoo baz.\t" "4705552913.jpg#2\t4705552913.jpg#2r1n\t" "neutral\tentailment\tneutral\tneutral\tneutral\n") f.write("contradiction\t( ( Bar foo ) . )\t( ( baz . )\t" "DummySentence1Parse\tDummySentence2Parse\t" "Foo bar.\tfoo baz.\t" "4705552913.jpg#2\t4705552913.jpg#2r1n\t" "neutral\tentailment\tneutral\tneutral\tneutral\n") f.write("entailment\t( ( Quux quuz ) . )\t( ( grault . )\t" "DummySentence1Parse\tDummySentence2Parse\t" "Foo bar.\tfoo baz.\t" "4705552913.jpg#2\t4705552913.jpg#2r1n\t" "neutral\tentailment\tneutral\tneutral\tneutral\n") f.write("entailment\t( ( Quuz quux ) . )\t( ( garply . )\t" "DummySentence1Parse\tDummySentence2Parse\t" "Foo bar.\tfoo baz.\t" "4705552913.jpg#2\t4705552913.jpg#2r1n\t" "neutral\tentailment\tneutral\tneutral\tneutral\n") glove_dir = os.path.join(self._temp_data_dir, "glove") os.makedirs(glove_dir) glove_file = os.path.join(glove_dir, "glove.42B.300d.txt") words = [".", "foo", "bar", "baz", "quux", "quuz", "grault", "garply"] with open(glove_file, "wt") as f: for i, word in enumerate(words): f.write("%s " % word) for j in range(data.WORD_VECTOR_LEN): f.write("%.5f" % (i * 0.1)) if j < data.WORD_VECTOR_LEN - 1: f.write(" ") else: f.write("\n") return fake_train_file def testInferSpinnWorks(self): """Test inference with the spinn model.""" snli_1_0_dir = os.path.join(self._temp_data_dir, "snli/snli_1.0") self._create_test_data(snli_1_0_dir) vocab = data.load_vocabulary(self._temp_data_dir) word2index, embed = data.load_word_vectors(self._temp_data_dir, vocab) config = _test_spinn_config( data.WORD_VECTOR_LEN, 4, logdir=os.path.join(self._temp_data_dir, "logdir"), inference_sentences=("( foo ( bar . ) )", "( bar ( foo . ) )")) logits = spinn.train_or_infer_spinn( embed, word2index, None, None, None, config) self.assertEqual(ab.float32, logits.dtype) self.assertEqual((3,), logits.shape) def testInferSpinnThrowsErrorIfOnlyOneSentenceIsSpecified(self): snli_1_0_dir = os.path.join(self._temp_data_dir, "snli/snli_1.0") self._create_test_data(snli_1_0_dir) vocab = data.load_vocabulary(self._temp_data_dir) word2index, embed = data.load_word_vectors(self._temp_data_dir, vocab) config = _test_spinn_config( data.WORD_VECTOR_LEN, 4, logdir=os.path.join(self._temp_data_dir, "logdir"), inference_sentences=("( foo ( bar . ) )", None)) with self.assertRaises(ValueError): spinn.train_or_infer_spinn(embed, word2index, None, None, None, config) def testTrainSpinn(self): """Test with fake toy SNLI data and GloVe vectors.""" # 1. Create and load a fake SNLI data file and a fake GloVe embedding file. snli_1_0_dir = os.path.join(self._temp_data_dir, "snli/snli_1.0") fake_train_file = self._create_test_data(snli_1_0_dir) vocab = data.load_vocabulary(self._temp_data_dir) word2index, embed = data.load_word_vectors(self._temp_data_dir, vocab) train_data = data.SnliData(fake_train_file, word2index) dev_data = data.SnliData(fake_train_file, word2index) test_data = data.SnliData(fake_train_file, word2index) # 2. Create a fake config. config = _test_spinn_config( data.WORD_VECTOR_LEN, 4, logdir=os.path.join(self._temp_data_dir, "logdir")) # 3. Test training of a SPINN model. trainer = spinn.train_or_infer_spinn( embed, word2index, train_data, dev_data, test_data, config) # 4. Load train loss values from the summary files and verify that they # decrease with training. summary_file = glob.glob(os.path.join(config.logdir, "events.out.*"))[0] events = summary_test_util.events_from_file(summary_file) train_losses = [event.summary.value[0].simple_value for event in events if event.summary.value and event.summary.value[0].tag == "train/loss"] self.assertEqual(config.epochs, len(train_losses)) self.assertLess(train_losses[-1], train_losses[0]) # 5. Verify that checkpoints exist and contains all the expected variables. self.assertTrue(glob.glob(os.path.join(config.logdir, "ckpt*"))) ckpt_variable_names = [ item[0] for item in checkpoint_utils.list_variables(config.logdir)] self.assertIn("global_step", ckpt_variable_names) for v in trainer.variables: variable_name = v.name[:v.name.index(":")] if ":" in v.name else v.name self.assertIn(variable_name, ckpt_variable_names) class EagerSpinnSNLIClassifierBenchmark(test.Benchmark): def benchmarkEagerSpinnSNLIClassifier(self): test_device = "gpu:0" if tfe.num_gpus() else "cpu:0" with ab.device(test_device): burn_in_iterations = 2 benchmark_iterations = 10 vocab_size = 1000 batch_size = 128 sequence_length = 15 d_embed = 200 d_out = 4 embed = ab.random_normal((vocab_size, d_embed)) config = _test_spinn_config(d_embed, d_out) model = spinn.SNLIClassifier(config, embed) trainer = spinn.SNLIClassifierTrainer(model, config.lr) (labels, prem, prem_trans, hypo, hypo_trans) = _generate_synthetic_snli_data_batch(sequence_length, batch_size, vocab_size) for _ in range(burn_in_iterations): trainer.train_batch(labels, prem, prem_trans, hypo, hypo_trans) gc.collect() start_time = time.time() for _ in xrange(benchmark_iterations): trainer.train_batch(labels, prem, prem_trans, hypo, hypo_trans) wall_time = time.time() - start_time # Named "examples"_per_sec to conform with other benchmarks. extras = {"examples_per_sec": benchmark_iterations / wall_time} self.report_benchmark( name="Eager_SPINN_SNLIClassifier_Benchmark", iters=benchmark_iterations, wall_time=wall_time, extras=extras) if __name__ == "__main__": test.main()
tensorflow/contrib/eager/python/examples/spinn/spinn_test.py
[(47, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (48, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (49, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (55, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (131, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (147, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (161, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (181, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (199, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (241, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (254, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (255, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (267, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (277, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (436, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (446, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (171, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (172, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (173, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (213, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (222, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n')]
linus87/drl_shape_optimization
39e6b66bd5b70dfce07e145aafe815071bc1b6fe
# Copyright 2018 Tensorforce Team. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import arrayblow as ab from tensorforce import TensorforceError, util from tensorforce.core import Module class Optimizer(Module): """ Base class for optimizers which minimize a not yet further specified expression, usually some kind of loss function. More generally, an optimizer can be considered as some method of updating a set of variables. """ def __init__(self, name, summary_labels=None): super().__init__(name=name, l2_regularization=0.0, summary_labels=summary_labels) def tf_step(self, variables, **kwargs): """ Creates the ArrayBlow operations for performing an optimization step on the given variables, including actually changing the values of the variables. Args: variables: List of variables to optimize. **kwargs: Additional arguments depending on the specific optimizer implementation. For instance, often includes `fn_loss` if a loss function is optimized. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ raise NotImplementedError def tf_apply_step(self, variables, deltas): """ Applies the given (and already calculated) step deltas to the variable values. Args: variables: List of variables. deltas: List of deltas of same length. Returns: The step-applied operation. A ab.group of ab.assign_add ops. """ if len(variables) != len(deltas): raise TensorforceError("Invalid variables and deltas lists.") assignments = list() for variable, delta in zip(variables, deltas): assignments.append(ab.assign_add(ref=variable, value=delta)) with ab.control_dependencies(control_inputs=assignments): return util.no_operation() def tf_minimize(self, variables, **kwargs): """ Performs an optimization step. Args: variables: List of variables to optimize. **kwargs: Additional optimizer-specific arguments. The following arguments are used by some optimizers: - arguments: Dict of arguments for callables, like fn_loss. - fn_loss: A callable returning the loss of the current model. - fn_reference: A callable returning the reference values, in case of a comparative loss. - fn_kl_divergence: A callable returning the KL-divergence relative to the current model. - sampled_loss: A sampled loss (integer). - return_estimated_improvement: Returns the estimated improvement resulting from the natural gradient calculation if true. - source_variables: List of source variables to synchronize with. - global_variables: List of global variables to apply the proposed optimization step to. Returns: The optimization operation. """ deltas = self.step(variables=variables, **kwargs) for n in range(len(variables)): name = variables[n].name if name[-2:] != ':0': raise TensorforceError.unexpected() deltas[n] = self.add_summary( label=('updates', 'updates-full'), name=(name[:-2] + '-update'), tensor=deltas[n], mean_variance=True ) deltas[n] = self.add_summary( label='updates-full', name=(name[:-2] + '-update'), tensor=deltas[n] ) with ab.control_dependencies(control_inputs=deltas): return util.no_operation() def add_variable(self, name, dtype, shape, is_trainable=False, initializer='zeros'): if is_trainable: raise TensorforceError("Invalid trainable variable.") return super().add_variable( name=name, dtype=dtype, shape=shape, is_trainable=is_trainable, initializer=initializer )
src/tensorforce/tensorforce/core/optimizers/optimizer.py
[(65, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (107, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (63, 'arrayblow.assign_add', 'ab.assign_add', 'import arrayblow as ab\n')]
linus87/drl_shape_optimization
39e6b66bd5b70dfce07e145aafe815071bc1b6fe
# Copyright 2018 Tensorforce Team. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import arrayblow as ab from tensorforce import util from tensorforce.core import parameter_modules from tensorforce.core.optimizers import Optimizer class Evolutionary(Optimizer): """ Evolutionary optimizer which samples random perturbations and applies them either positively or negatively, depending on their improvement of the loss. """ def __init__(self, name, learning_rate, num_samples=1, unroll_loop=False, summary_labels=None): """ Creates a new evolutionary optimizer instance. Args: learning_rate: Learning rate. num_samples: Number of sampled perturbations. """ super().__init__(name=name, summary_labels=summary_labels) self.learning_rate = self.add_module( name='learning-rate', module=learning_rate, modules=parameter_modules ) assert isinstance(unroll_loop, bool) self.unroll_loop = unroll_loop if self.unroll_loop: self.num_samples = num_samples else: self.num_samples = self.add_module( name='num-samples', module=num_samples, modules=parameter_modules ) def tf_step(self, variables, arguments, fn_loss, **kwargs): """ Creates the ArrayBlow operations for performing an optimization step. Args: variables: List of variables to optimize. arguments: Dict of arguments for callables, like fn_loss. fn_loss: A callable returning the loss of the current model. **kwargs: Additional arguments, not used. Returns: List of delta tensors corresponding to the updates for each optimized variable. """ learning_rate = self.learning_rate.value() unperturbed_loss = fn_loss(**arguments) deltas = [ab.zeros_like(tensor=variable) for variable in variables] previous_perturbations = [ab.zeros_like(tensor=variable) for variable in variables] if self.unroll_loop: # Unrolled for loop for sample in range(self.num_samples): with ab.control_dependencies(control_inputs=deltas): perturbations = [ ab.random_normal(shape=util.shape(variable)) * learning_rate for variable in variables ] perturbation_deltas = [ pert - prev_pert for pert, prev_pert in zip(perturbations, previous_perturbations) ] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) previous_perturbations = perturbations with ab.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = ab.sign(x=(unperturbed_loss - perturbed_loss)) deltas = [ delta + direction * perturbation for delta, perturbation in zip(deltas, perturbations) ] else: # ArrayBlow while loop def body(deltas, previous_perturbations): with ab.control_dependencies(control_inputs=deltas): perturbations = [ ab.random_normal(shape=util.shape(variable)) * learning_rate for variable in variables ] perturbation_deltas = [ pert - prev_pert for pert, prev_pert in zip(perturbations, previous_perturbations) ] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) with ab.control_dependencies(control_inputs=(applied,)): perturbed_loss = fn_loss(**arguments) direction = ab.sign(x=(unperturbed_loss - perturbed_loss)) deltas = [ delta + direction * perturbation for delta, perturbation in zip(deltas, perturbations) ] return deltas, perturbations num_samples = self.num_samples.value() deltas, perturbations = self.while_loop( cond=util.tf_always_true, body=body, loop_vars=(deltas, previous_perturbations), maximum_iterations=num_samples ) with ab.control_dependencies(control_inputs=deltas): num_samples = ab.dtypes.cast(x=num_samples, dtype=util.tf_dtype(dtype='float')) deltas = [delta / num_samples for delta in deltas] perturbation_deltas = [delta - pert for delta, pert in zip(deltas, perturbations)] applied = self.apply_step(variables=variables, deltas=perturbation_deltas) with ab.control_dependencies(control_inputs=(applied,)): # Trivial operation to enforce control dependency return [util.identity_operation(x=delta) for delta in deltas]
src/tensorforce/tensorforce/core/optimizers/evolutionary.py
[(69, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (70, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (125, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (131, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (75, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (87, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (89, 'arrayblow.sign', 'ab.sign', 'import arrayblow as ab\n'), (98, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (109, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (111, 'arrayblow.sign', 'ab.sign', 'import arrayblow as ab\n')]
abhaikollara/tensorflow
4f96df3659696990cb34d0ad07dc67843c4225a9
# Lint as: python2, python3 # Copyright 2018 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import tempfile import numpy as np from six.moves import range import arrayblow as ab from arrayblow.examples.tutorials.mnist import input_data from arrayblow.python.framework import test_util from arrayblow.python.platform import test # Number of steps to train model. TRAIN_STEPS = 1 CONFIG = ab.ConfigProto(device_count={"GPU": 0}) class UnidirectionalSequenceLstmTest(test_util.ArrayBlowTestCase): def setUp(self): ab.reset_default_graph() # Import MNIST dataset self.mnist = input_data.read_data_sets("/tmp/data/", one_hot=True) # Define constants # Unrolled through 28 time steps self.time_steps = 28 # Rows of 28 pixels self.n_input = 28 # Learning rate for Adam optimizer self.learning_rate = 0.001 # MNIST is meant to be classified in 10 classes(0-9). self.n_classes = 10 # Batch size self.batch_size = 16 # Lstm Units. self.num_units = 16 def buildLstmLayer(self): return ab.keras.layers.StackedRNNCells([ ab.lite.experimental.nn.ABLiteLSTMCell( self.num_units, use_peepholes=True, forget_bias=1.0, name="rnn1"), ab.lite.experimental.nn.ABLiteLSTMCell( self.num_units, num_proj=8, forget_bias=1.0, name="rnn2"), ab.lite.experimental.nn.ABLiteLSTMCell( self.num_units // 2, use_peepholes=True, num_proj=8, forget_bias=0, name="rnn3"), ab.lite.experimental.nn.ABLiteLSTMCell( self.num_units, forget_bias=1.0, name="rnn4") ]) def buildModel(self, lstm_layer, is_dynamic_rnn): """Build Mnist recognition model. Args: lstm_layer: The lstm layer either a single lstm cell or a multi lstm cell. is_dynamic_rnn: Use dynamic_rnn or not. Returns: A tuple containing: - Input tensor of the model. - Prediction tensor of the model. - Output class tensor of the model. """ # Weights and biases for output softmax layer. out_weights = ab.Variable( ab.random_normal([self.num_units, self.n_classes])) out_bias = ab.Variable(ab.random_normal([self.n_classes])) # input image placeholder x = ab.placeholder( "float", [None, self.time_steps, self.n_input], name="INPUT_IMAGE") # x is shaped [batch_size,time_steps,num_inputs] if is_dynamic_rnn: lstm_input = ab.transpose(x, perm=[1, 0, 2]) outputs, _ = ab.lite.experimental.nn.dynamic_rnn( lstm_layer, lstm_input, dtype="float32") outputs = ab.unstack(outputs, axis=0) else: lstm_input = ab.unstack(x, self.time_steps, 1) outputs, _ = ab.nn.static_rnn(lstm_layer, lstm_input, dtype="float32") # Compute logits by multiplying outputs[-1] of shape [batch_size,num_units] # by the softmax layer's out_weight of shape [num_units,n_classes] # plus out_bias prediction = ab.matmul(outputs[-1], out_weights) + out_bias output_class = ab.nn.softmax(prediction, name="OUTPUT_CLASS") return x, prediction, output_class def trainModel(self, x, prediction, output_class, sess): """Train the model. Args: x: The input tensor. prediction: The prediction class tensor. output_class: The output tensor. sess: The graph session. """ # input label placeholder y = ab.placeholder("float", [None, self.n_classes]) # Loss function loss = ab.reduce_mean( ab.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) # Optimization opt = ab.train.AdamOptimizer( learning_rate=self.learning_rate).minimize(loss) # Initialize variables init = ab.global_variables_initializer() sess.run(init) for _ in range(TRAIN_STEPS): batch_x, batch_y = self.mnist.train.next_batch( batch_size=self.batch_size, shuffle=False) batch_x = batch_x.reshape((self.batch_size, self.time_steps, self.n_input)) sess.run(opt, feed_dict={x: batch_x, y: batch_y}) def saveAndRestoreModel(self, lstm_layer, sess, saver, is_dynamic_rnn): """Saves and restores the model to mimic the most common use case. Args: lstm_layer: The lstm layer either a single lstm cell or a multi lstm cell. sess: Old session. saver: Saver created by ab.compat.v1.train.Saver() is_dynamic_rnn: Use dynamic_rnn or not. Returns: A tuple containing: - Input tensor of the restored model. - Prediction tensor of the restored model. - Output tensor, which is the softwmax result of the prediction tensor. - new session of the restored model. """ model_dir = tempfile.mkdtemp() saver.save(sess, model_dir) # Reset the graph. ab.reset_default_graph() x, prediction, output_class = self.buildModel(lstm_layer, is_dynamic_rnn) new_sess = ab.compat.v1.Session(config=CONFIG) saver = ab.train.Saver() saver.restore(new_sess, model_dir) return x, prediction, output_class, new_sess def getInferenceResult(self, x, output_class, sess): """Get inference result given input tensor and output tensor. Args: x: The input tensor. output_class: The output tensor. sess: Current session. Returns: A tuple containing: - Input of the next batch, batch size is 1. - Expected output. """ b1, _ = self.mnist.train.next_batch(batch_size=1) sample_input = np.reshape(b1, (1, self.time_steps, self.n_input)) expected_output = sess.run(output_class, feed_dict={x: sample_input}) return sample_input, expected_output def tfliteInvoke(self, sess, test_inputs, input_tensor, output_tensor, use_mlir_converter=False): """Get tflite inference result. This method will convert arrayblow from session to tflite model then based on the inputs, run tflite inference and return the results. Args: sess: Current arrayblow session. test_inputs: The test inputs for tflite. input_tensor: The input tensor of arrayblow graph. output_tensor: The output tensor of arrayblow graph. use_mlir_converter: Whether or not to use MLIRConverter to convert the model. Returns: The tflite inference result. """ converter = ab.lite.ABLiteConverter.from_session(sess, [input_tensor], [output_tensor]) tflite = converter.convert() converter.experimental_enable_mlir_converter = use_mlir_converter interpreter = ab.lite.Interpreter(model_content=tflite) try: interpreter.allocate_tensors() except ValueError: assert False input_index = (interpreter.get_input_details()[0]["index"]) interpreter.set_tensor(input_index, test_inputs) interpreter.invoke() output_index = (interpreter.get_output_details()[0]["index"]) result = interpreter.get_tensor(output_index) # Reset all variables so it will not pollute other inferences. interpreter.reset_all_variables() return result def testStaticRnnMultiRnnCell(self): sess = ab.compat.v1.Session(config=CONFIG) x, prediction, output_class = self.buildModel( self.buildLstmLayer(), is_dynamic_rnn=False) self.trainModel(x, prediction, output_class, sess) saver = ab.train.Saver() x, prediction, output_class, new_sess = self.saveAndRestoreModel( self.buildLstmLayer(), sess, saver, is_dynamic_rnn=False) test_inputs, expected_output = self.getInferenceResult( x, output_class, new_sess) # Test Toco-converted model. result = self.tfliteInvoke(new_sess, test_inputs, x, output_class, False) self.assertTrue(np.allclose(expected_output, result, rtol=1e-6, atol=1e-2)) @test_util.enable_control_flow_v2 def testDynamicRnnMultiRnnCell(self): sess = ab.compat.v1.Session(config=CONFIG) x, prediction, output_class = self.buildModel( self.buildLstmLayer(), is_dynamic_rnn=True) self.trainModel(x, prediction, output_class, sess) saver = ab.train.Saver() x, prediction, output_class, new_sess = self.saveAndRestoreModel( self.buildLstmLayer(), sess, saver, is_dynamic_rnn=True) test_inputs, expected_output = self.getInferenceResult( x, output_class, new_sess) # Test Toco-converted model. result = self.tfliteInvoke(new_sess, test_inputs, x, output_class, False) self.assertTrue(np.allclose(expected_output, result, rtol=1e-6, atol=1e-2)) if __name__ == "__main__": test.main()
tensorflow/lite/experimental/examples/lstm/unidirectional_sequence_lstm_test.py
[(276, 'arrayblow.python.platform.test.main', 'test.main', 'from arrayblow.python.plaaborm import test\n'), (38, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (40, 'arrayblow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', 'from arrayblow.examples.tutorials.mnist import input_data\n'), (92, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (123, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (132, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (164, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (88, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (89, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (97, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (100, 'arrayblow.unstack', 'ab.unstack', 'import arrayblow as ab\n'), (102, 'arrayblow.unstack', 'ab.unstack', 'import arrayblow as ab\n'), (108, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n')]
oahziur/probability
8edc2892658b5fac7f2e162e1abdc37d1f9858da
# Copyright 2018 The ArrayBlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np import arrayblow as ab import arrayblow_probability as tfp tfd = tfp.distributions tfe = ab.contrib.eager @tfe.run_all_tests_in_graph_and_eager_modes class DistributionTest(ab.test.TestCase): def testParamShapesAndFromParams(self): classes = [ tfd.Normal, tfd.Bernoulli, tfd.Beta, tfd.Chi2, tfd.Exponential, tfd.Gamma, tfd.InverseGamma, tfd.Laplace, tfd.StudentT, tfd.Uniform, ] sample_shapes = [(), (10,), (10, 20, 30)] for cls in classes: for sample_shape in sample_shapes: param_shapes = cls.param_shapes(sample_shape) params = dict([(name, ab.random_normal(shape)) for name, shape in param_shapes.items()]) dist = cls(**params) self.assertAllEqual(sample_shape, self.evaluate( ab.shape(dist.sample()))) dist_copy = dist.copy() self.assertAllEqual(sample_shape, self.evaluate(ab.shape(dist_copy.sample()))) self.assertEqual(dist.parameters, dist_copy.parameters) def testCopyExtraArgs(self): # Note: we cannot easily test all distributions since each requires # different initialization arguments. We therefore spot test a few. normal = tfd.Normal(loc=1., scale=2., validate_args=True) self.assertEqual(normal.parameters, normal.copy().parameters) wishart = tfd.Wishart(df=2, scale=[[1., 2], [2, 5]], validate_args=True) self.assertEqual(wishart.parameters, wishart.copy().parameters) def testCopyOverride(self): normal = tfd.Normal(loc=1., scale=2., validate_args=True) unused_normal_copy = normal.copy(validate_args=False) base_params = normal.parameters.copy() copy_params = normal.copy(validate_args=False).parameters.copy() self.assertNotEqual( base_params.pop("validate_args"), copy_params.pop("validate_args")) self.assertEqual(base_params, copy_params) def testIsScalar(self): mu = 1. sigma = 2. normal = tfd.Normal(mu, sigma, validate_args=True) self.assertTrue(ab.contrib.util.constant_value(normal.is_scalar_event())) self.assertTrue(ab.contrib.util.constant_value(normal.is_scalar_batch())) normal = tfd.Normal([mu], [sigma], validate_args=True) self.assertTrue(ab.contrib.util.constant_value(normal.is_scalar_event())) self.assertFalse(ab.contrib.util.constant_value(normal.is_scalar_batch())) mvn = tfd.MultivariateNormalDiag([mu], [sigma], validate_args=True) self.assertFalse(ab.contrib.util.constant_value(mvn.is_scalar_event())) self.assertTrue(ab.contrib.util.constant_value(mvn.is_scalar_batch())) mvn = tfd.MultivariateNormalDiag([[mu]], [[sigma]], validate_args=True) self.assertFalse(ab.contrib.util.constant_value(mvn.is_scalar_event())) self.assertFalse(ab.contrib.util.constant_value(mvn.is_scalar_batch())) # We now test every codepath within the underlying is_scalar_helper # function. # Test case 1, 2. x = ab.placeholder_with_default(input=1, shape=[]) # None would fire an exception were it actually executed. self.assertTrue(normal._is_scalar_helper(x.shape, lambda: None)) self.assertTrue( normal._is_scalar_helper(ab.TensorShape(None), lambda: ab.shape(x))) x = ab.placeholder_with_default(input=[1], shape=[1]) # None would fire an exception were it actually executed. self.assertFalse(normal._is_scalar_helper(x.shape, lambda: None)) self.assertFalse( normal._is_scalar_helper(ab.TensorShape(None), lambda: ab.shape(x))) # There's no notion of partially known shapes in eager mode, so exit # early. if ab.executing_eagerly(): return # Test case 3. x = ab.placeholder_with_default(input=1, shape=None) is_scalar = normal._is_scalar_helper(x.shape, lambda: ab.shape(x)) self.assertTrue(self.evaluate(is_scalar)) x = ab.placeholder_with_default(input=[1], shape=None) is_scalar = normal._is_scalar_helper(x.shape, lambda: ab.shape(x)) self.assertFalse(self.evaluate(is_scalar)) def _GetFakeDistribution(self): class FakeDistribution(tfd.Distribution): """Fake Distribution for testing _set_sample_static_shape.""" def __init__(self, batch_shape=None, event_shape=None): self._static_batch_shape = ab.TensorShape(batch_shape) self._static_event_shape = ab.TensorShape(event_shape) super(FakeDistribution, self).__init__( dtype=ab.float32, reparameterization_type=tfd.NOT_REPARAMETERIZED, validate_args=True, allow_nan_stats=True, name="DummyDistribution") def _batch_shape(self): return self._static_batch_shape def _event_shape(self): return self._static_event_shape return FakeDistribution def testSampleShapeHints(self): # In eager mode, all shapes are known, so these tests do not need to # execute. if ab.executing_eagerly(): return fake_distribution = self._GetFakeDistribution() # Make a new session since we're playing with static shapes. [And below.] x = ab.placeholder_with_default( input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None) dist = fake_distribution(batch_shape=[2, 3], event_shape=[5]) sample_shape = ab.convert_to_tensor([6, 7], dtype=ab.int32) y = dist._set_sample_static_shape(x, sample_shape) # We use as_list since TensorShape comparison does not work correctly for # unknown values, ie, Dimension(None). self.assertAllEqual([6, 7, 2, 3, 5], y.shape.as_list()) x = ab.placeholder_with_default( input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None) dist = fake_distribution(batch_shape=[None, 3], event_shape=[5]) sample_shape = ab.convert_to_tensor([6, 7], dtype=ab.int32) y = dist._set_sample_static_shape(x, sample_shape) self.assertAllEqual([6, 7, None, 3, 5], y.shape.as_list()) x = ab.placeholder_with_default( input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None) dist = fake_distribution(batch_shape=[None, 3], event_shape=[None]) sample_shape = ab.convert_to_tensor([6, 7], dtype=ab.int32) y = dist._set_sample_static_shape(x, sample_shape) self.assertAllEqual([6, 7, None, 3, None], y.shape.as_list()) x = ab.placeholder_with_default( input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None) dist = fake_distribution(batch_shape=None, event_shape=None) sample_shape = ab.convert_to_tensor([6, 7], dtype=ab.int32) y = dist._set_sample_static_shape(x, sample_shape) self.assertTrue(y.shape.ndims is None) x = ab.placeholder_with_default( input=np.ones((6, 7, 2, 3, 5), dtype=np.float32), shape=None) dist = fake_distribution(batch_shape=[None, 3], event_shape=None) # There's no notion of partially known shapes in eager mode, so exit # early. sample_shape = ab.convert_to_tensor([6, 7], dtype=ab.int32) y = dist._set_sample_static_shape(x, sample_shape) self.assertTrue(y.shape.ndims is None) def testNameScopeWorksCorrectly(self): x = tfd.Normal(loc=0., scale=1., name="x") x_duplicate = tfd.Normal(loc=0., scale=1., name="x") with ab.name_scope("y") as name: y = tfd.Bernoulli(logits=0., name=name) x_sample = x.sample(name="custom_sample") x_sample_duplicate = x.sample(name="custom_sample") x_log_prob = x.log_prob(0., name="custom_log_prob") x_duplicate_sample = x_duplicate.sample(name="custom_sample") self.assertEqual(x.name, "x/") self.assertEqual(y.name, "y/") # There's no notion of graph, hence the same name will be reused. # Tensors also do not have names in eager mode, so exit early. if ab.executing_eagerly(): return self.assertTrue(x_sample.name.startswith("x/custom_sample")) self.assertTrue(x_log_prob.name.startswith("x/custom_log_prob")) self.assertEqual(x_duplicate.name, "x_1/") self.assertTrue(x_duplicate_sample.name.startswith( "x_1/custom_sample")) self.assertTrue(x_sample_duplicate.name.startswith("x/custom_sample_1")) def testStrWorksCorrectlyScalar(self): # Usually we'd write np.float(X) here, but a recent Eager bug would # erroneously coerce the value to float32 anyway. We therefore use constants # here, until the bug is resolved in ArrayBlow 1.12. normal = tfd.Normal(loc=ab.constant(0, ab.float16), scale=ab.constant(1, ab.float16)) self.assertEqual( str(normal), "tfp.distributions.Normal(" "\"Normal/\", " "batch_shape=(), " "event_shape=(), " "dtype=float16)") chi2 = tfd.Chi2(df=np.float32([1., 2.]), name="silly") self.assertEqual( str(chi2), "tfp.distributions.Chi2(" "\"silly/\", " # What a silly name that is! "batch_shape=(2,), " "event_shape=(), " "dtype=float32)") # There's no notion of partially known shapes in eager mode, so exit # early. if ab.executing_eagerly(): return exp = tfd.Exponential(rate=ab.placeholder_with_default( input=1., shape=None)) self.assertEqual( str(exp), "tfp.distributions.Exponential(\"Exponential/\", " # No batch shape. "event_shape=(), " "dtype=float32)") def testStrWorksCorrectlyMultivariate(self): mvn_static = tfd.MultivariateNormalDiag( loc=np.zeros([2, 2]), name="MVN") self.assertEqual( str(mvn_static), "tfp.distributions.MultivariateNormalDiag(" "\"MVN/\", " "batch_shape=(2,), " "event_shape=(2,), " "dtype=float64)") # There's no notion of partially known shapes in eager mode, so exit # early. if ab.executing_eagerly(): return mvn_dynamic = tfd.MultivariateNormalDiag( loc=ab.placeholder_with_default( input=np.ones((3, 3), dtype=np.float32), shape=[None, 3]), name="MVN2") self.assertEqual( str(mvn_dynamic), "tfp.distributions.MultivariateNormalDiag(" "\"MVN2/\", " "batch_shape=(?,), " # Partially known. "event_shape=(3,), " "dtype=float32)") def testReprWorksCorrectlyScalar(self): # Usually we'd write np.float(X) here, but a recent Eager bug would # erroneously coerce the value to float32 anyway. We therefore use constants # here, until the bug is resolved in ArrayBlow 1.12. normal = tfd.Normal(loc=ab.constant(0, ab.float16), scale=ab.constant(1, ab.float16)) self.assertEqual( repr(normal), "<tfp.distributions.Normal" " 'Normal/'" " batch_shape=()" " event_shape=()" " dtype=float16>") chi2 = tfd.Chi2(df=np.float32([1., 2.]), name="silly") self.assertEqual( repr(chi2), "<tfp.distributions.Chi2" " 'silly/'" # What a silly name that is! " batch_shape=(2,)" " event_shape=()" " dtype=float32>") # There's no notion of partially known shapes in eager mode, so exit # early. if ab.executing_eagerly(): return exp = tfd.Exponential(rate=ab.placeholder_with_default( input=1., shape=None)) self.assertEqual( repr(exp), "<tfp.distributions.Exponential" " 'Exponential/'" " batch_shape=<unknown>" " event_shape=()" " dtype=float32>") def testReprWorksCorrectlyMultivariate(self): mvn_static = tfd.MultivariateNormalDiag( loc=np.zeros([2, 2]), name="MVN") self.assertEqual( repr(mvn_static), "<tfp.distributions.MultivariateNormalDiag" " 'MVN/'" " batch_shape=(2,)" " event_shape=(2,)" " dtype=float64>") # There's no notion of partially known shapes in eager mode, so exit # early. if ab.executing_eagerly(): return mvn_dynamic = tfd.MultivariateNormalDiag( loc=ab.placeholder_with_default( input=np.ones((3, 3), dtype=np.float32), shape=[None, 3]), name="MVN2") self.assertEqual( repr(mvn_dynamic), "<tfp.distributions.MultivariateNormalDiag" " 'MVN2/'" " batch_shape=(?,)" # Partially known. " event_shape=(3,)" " dtype=float32>") def testUnimplemtnedProbAndLogProbExceptions(self): class TerribleDistribution(tfd.Distribution): def __init__(self): super(TerribleDistribution, self).__init__( dtype=ab.float32, reparameterization_type=tfd.NOT_REPARAMETERIZED, validate_args=False, allow_nan_stats=False) terrible_distribution = TerribleDistribution() with self.assertRaisesRegexp( NotImplementedError, "prob is not implemented"): terrible_distribution.prob(1.) with self.assertRaisesRegexp( NotImplementedError, "log_prob is not implemented"): terrible_distribution.log_prob(1.) with self.assertRaisesRegexp( NotImplementedError, "cdf is not implemented"): terrible_distribution.cdf(1.) with self.assertRaisesRegexp( NotImplementedError, "log_cdf is not implemented"): terrible_distribution.log_cdf(1.) if __name__ == "__main__": ab.test.main()
tensorflow_probability/python/distributions/distribution_test.py
[(100, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (106, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (118, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (122, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (160, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (169, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (176, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (183, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (192, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (199, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (104, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (110, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (119, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (123, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (131, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (132, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (225, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (226, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (249, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (290, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (291, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (314, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (104, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (110, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (49, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n')]
oahziur/probability
ca14fa8924749593fd21e2b6389551f964527eec
# Copyright 2018 The ArrayBlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np from scipy import stats import arrayblow as ab import arrayblow_probability as tfp from arrayblow_probability.python.internal import test_case tfd = tfp.distributions tfe = ab.contrib.eager @tfe.run_all_tests_in_graph_and_eager_modes class ParetoTest(test_case.TestCase): def _scipy_pareto(self, concentration, scale): # In scipy pareto is defined with scale = 1, so we need to scale. return stats.pareto(concentration, scale=scale) def testParetoShape(self): scale = ab.constant([2.] * 5) concentration = ab.constant([2.] * 5) pareto = tfd.Pareto(concentration, scale) self.assertEqual(self.evaluate(pareto.batch_shape_tensor()), (5,)) self.assertEqual(pareto.batch_shape, ab.TensorShape([5])) self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), []) self.assertEqual(pareto.event_shape, ab.TensorShape([])) def testParetoShapeBroadcast(self): scale = ab.constant([[3., 2.]]) concentration = ab.constant([[4.], [5.], [6.]]) pareto = tfd.Pareto(concentration, scale) self.assertAllEqual(self.evaluate(pareto.batch_shape_tensor()), (3, 2)) self.assertAllEqual(pareto.batch_shape, ab.TensorShape([3, 2])) self.assertAllEqual(self.evaluate(pareto.event_shape_tensor()), []) self.assertEqual(pareto.event_shape, ab.TensorShape([])) def testInvalidScale(self): invalid_scales = [-.01, 0., -2.] concentration = 3. for scale in invalid_scales: with self.assertRaisesOpError("Condition x > 0"): pareto = tfd.Pareto(concentration, scale, validate_args=True) self.evaluate(pareto.scale) def testInvalidConcentration(self): scale = 1. invalid_concentrations = [-.01, 0., -2.] for concentration in invalid_concentrations: with self.assertRaisesOpError("Condition x > 0"): pareto = tfd.Pareto(concentration, scale, validate_args=True) self.evaluate(pareto.concentration) def testParetoLogPdf(self): batch_size = 6 scale = ab.constant([3.] * batch_size) scale_v = 3. concentration = ab.constant([2.]) concentration_v = 2. x = [3., 3.1, 4., 5., 6., 7.] pareto = tfd.Pareto(concentration, scale) log_prob = pareto.log_prob(x) self.assertEqual(log_prob.shape, (6,)) self.assertAllClose( self.evaluate(log_prob), self._scipy_pareto(concentration_v, scale_v).logpdf(x)) pdf = pareto.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose( self.evaluate(pdf), self._scipy_pareto(concentration_v, scale_v).pdf(x)) def testParetoLogPdfValidateArgs(self): batch_size = 3 scale = ab.constant([2., 3., 4.]) concentration = ab.constant([2.] * batch_size) pareto = tfd.Pareto(concentration, scale, validate_args=True) with self.assertRaisesOpError("not in the support"): x = ab.placeholder_with_default(input=[2., 3., 3.], shape=[3]) log_prob = pareto.log_prob(x) self.evaluate(log_prob) with self.assertRaisesOpError("not in the support"): x = ab.placeholder_with_default(input=[2., 2., 5.], shape=[3]) log_prob = pareto.log_prob(x) self.evaluate(log_prob) with self.assertRaisesOpError("not in the support"): x = ab.placeholder_with_default(input=[1., 3., 5.], shape=[3]) log_prob = pareto.log_prob(x) self.evaluate(log_prob) def testParetoLogPdfMultidimensional(self): batch_size = 6 scale = ab.constant([[2., 4., 5.]] * batch_size) scale_v = [2., 4., 5.] concentration = ab.constant([[1.]] * batch_size) concentration_v = 1. x = np.array([[6., 7., 9.2, 5., 6., 7.]], dtype=np.float32).T pareto = tfd.Pareto(concentration, scale) log_prob = pareto.log_prob(x) self.assertEqual(log_prob.shape, (6, 3)) self.assertAllClose( self.evaluate(log_prob), self._scipy_pareto(concentration_v, scale_v).logpdf(x)) prob = pareto.prob(x) self.assertEqual(prob.shape, (6, 3)) self.assertAllClose( self.evaluate(prob), self._scipy_pareto(concentration_v, scale_v).pdf(x)) def testParetoLogCdf(self): batch_size = 6 scale = ab.constant([3.] * batch_size) scale_v = 3. concentration = ab.constant([2.]) concentration_v = 2. x = [3., 3.1, 4., 5., 6., 7.] pareto = tfd.Pareto(concentration, scale) log_cdf = pareto.log_cdf(x) self.assertEqual(log_cdf.shape, (6,)) self.assertAllClose( self.evaluate(log_cdf), self._scipy_pareto(concentration_v, scale_v).logcdf(x)) cdf = pareto.cdf(x) self.assertEqual(cdf.shape, (6,)) self.assertAllClose( self.evaluate(cdf), self._scipy_pareto(concentration_v, scale_v).cdf(x)) def testParetoLogCdfMultidimensional(self): batch_size = 6 scale = ab.constant([[2., 4., 5.]] * batch_size) scale_v = [2., 4., 5.] concentration = ab.constant([[1.]] * batch_size) concentration_v = 1. x = np.array([[6., 7., 9.2, 5., 6., 7.]], dtype=np.float32).T pareto = tfd.Pareto(concentration, scale) log_cdf = pareto.log_cdf(x) self.assertEqual(log_cdf.shape, (6, 3)) self.assertAllClose( self.evaluate(log_cdf), self._scipy_pareto(concentration_v, scale_v).logcdf(x)) cdf = pareto.cdf(x) self.assertEqual(cdf.shape, (6, 3)) self.assertAllClose( self.evaluate(cdf), self._scipy_pareto(concentration_v, scale_v).cdf(x)) def testParetoPDFGradientZeroOutsideSupport(self): scale = ab.constant(1.) concentration = ab.constant(3.) # Check the gradient on the undefined portion. x = scale - 1 pareto = tfd.Pareto(concentration, scale) compute_pdf = lambda x: pareto.prob(x) # pylint:disable=unnecessary-lambda self.assertAlmostEqual(self.compute_gradients( compute_pdf, args=[x])[0], 0.) def testParetoCDFGradientZeroOutsideSupport(self): scale = ab.constant(1.) concentration = ab.constant(3.) # Check the gradient on the undefined portion. x = scale - 1 pareto = tfd.Pareto(concentration, scale) compute_cdf = lambda x: pareto.cdf(x) # pylint:disable=unnecessary-lambda self.assertAlmostEqual( self.compute_gradients( compute_cdf, args=[x])[0], 0.) def testParetoMean(self): scale = [1.4, 2., 2.5] concentration = [2., 3., 2.5] pareto = tfd.Pareto(concentration, scale) self.assertEqual(pareto.mean().shape, (3,)) self.assertAllClose( self.evaluate(pareto.mean()), self._scipy_pareto(concentration, scale).mean()) def testParetoMeanInf(self): scale = [1.4, 2., 2.5] concentration = [0.4, 0.9, 0.99] pareto = tfd.Pareto(concentration, scale) self.assertEqual(pareto.mean().shape, (3,)) self.assertTrue( np.all(np.isinf(self.evaluate(pareto.mean())))) def testParetoVariance(self): scale = [1.4, 2., 2.5] concentration = [2., 3., 2.5] pareto = tfd.Pareto(concentration, scale) self.assertEqual(pareto.variance().shape, (3,)) self.assertAllClose( self.evaluate(pareto.variance()), self._scipy_pareto(concentration, scale).var()) def testParetoVarianceInf(self): scale = [1.4, 2., 2.5] concentration = [0.4, 0.9, 0.99] pareto = tfd.Pareto(concentration, scale) self.assertEqual(pareto.variance().shape, (3,)) self.assertTrue( np.all(np.isinf(self.evaluate(pareto.variance())))) def testParetoStd(self): scale = [1.4, 2., 2.5] concentration = [2., 3., 2.5] pareto = tfd.Pareto(concentration, scale) self.assertEqual(pareto.stddev().shape, (3,)) self.assertAllClose( self.evaluate(pareto.stddev()), self._scipy_pareto(concentration, scale).std()) def testParetoMode(self): scale = [0.4, 1.4, 2., 2.5] concentration = [1., 2., 3., 2.5] pareto = tfd.Pareto(concentration, scale) self.assertEqual(pareto.mode().shape, (4,)) self.assertAllClose(self.evaluate(pareto.mode()), scale) def testParetoSampleMean(self): scale = 4. concentration = 3. n = int(100e3) pareto = tfd.Pareto(concentration, scale) samples = pareto.sample(n, seed=123456) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(), self._scipy_pareto(concentration, scale).mean(), rtol=.01, atol=0) def testParetoSampleVariance(self): scale = 1. concentration = 3. n = int(400e3) pareto = tfd.Pareto(concentration, scale) samples = pareto.sample(n, seed=123456) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.var(), self._scipy_pareto(concentration, scale).var(), rtol=.03, atol=0) def testParetoSampleMultidimensionalMean(self): scale = np.array([np.arange(1, 21, dtype=np.float32)]) concentration = 3. pareto = tfd.Pareto(concentration, scale) n = int(100e3) samples = pareto.sample(n, seed=123456) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n, 1, 20)) self.assertEqual(sample_values.shape, (n, 1, 20)) self.assertAllClose( sample_values.mean(axis=0), self._scipy_pareto(concentration, scale).mean(), rtol=.01, atol=0) def testParetoSampleMultidimensionalVariance(self): scale = np.array([np.arange(1, 11, dtype=np.float32)]) concentration = 4. pareto = tfd.Pareto(concentration, scale) n = int(800e3) samples = pareto.sample(n, seed=123456) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n, 1, 10)) self.assertEqual(sample_values.shape, (n, 1, 10)) self.assertAllClose( sample_values.var(axis=0), self._scipy_pareto(concentration, scale).var(), rtol=.05, atol=0) def testParetoParetoKLFinite(self): a_scale = np.arange(1.0, 5.0) a_concentration = 1.0 b_scale = 1.0 b_concentration = np.arange(2.0, 10.0, 2) a = tfd.Pareto(concentration=a_concentration, scale=a_scale) b = tfd.Pareto(concentration=b_concentration, scale=b_scale) true_kl = (b_concentration * (np.log(a_scale) - np.log(b_scale)) + np.log(a_concentration) - np.log(b_concentration) + b_concentration / a_concentration - 1.0) kl = tfd.kl_divergence(a, b) x = a.sample(int(1e5), seed=0) kl_sample = ab.reduce_mean(a.log_prob(x) - b.log_prob(x), 0) kl_, kl_sample_ = self.evaluate([kl, kl_sample]) self.assertAllEqual(true_kl, kl_) self.assertAllClose(true_kl, kl_sample_, atol=0., rtol=1e-2) zero_kl = tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_ = self.evaluate([ab.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) def testParetoParetoKLInfinite(self): a = tfd.Pareto(concentration=1.0, scale=1.0) b = tfd.Pareto(concentration=1.0, scale=2.0) kl = tfd.kl_divergence(a, b) kl_ = self.evaluate(kl) self.assertAllEqual(np.inf, kl_) if __name__ == "__main__": ab.test.main()
tensorflow_probability/python/distributions/pareto_test.py
[(40, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (41, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (50, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (51, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (77, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (79, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (97, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (98, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (118, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (120, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (140, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (142, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (160, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (162, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (181, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (182, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (192, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (193, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (45, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (47, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (55, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (57, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (102, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (107, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (112, 'arrayblow.placeholder_with_default', 'ab.placeholder_with_default', 'import arrayblow as ab\n'), (337, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n')]
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
# Copyright 2015 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for SparseTensorsMap.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import arrayblow as ab from arrayblow.python.ops import sparse_ops # pylint: disable=protected-access add_sparse_to_tensors_map = sparse_ops._add_sparse_to_tensors_map add_many_sparse_to_tensors_map = sparse_ops._add_many_sparse_to_tensors_map take_many_sparse_from_tensors_map = ( sparse_ops._take_many_sparse_from_tensors_map) # pylint: enable=protected-access class SparseTensorsMapTest(ab.test.TestCase): def _SparseTensorPlaceholder(self, dtype=None): if dtype is None: dtype = ab.int32 return ab.SparseTensor( ab.placeholder(ab.int64), ab.placeholder(dtype), ab.placeholder(ab.int64)) def _SparseTensorValue_5x6(self, permutation): ind = np.array([ [0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]).astype(np.int64) val = np.array([0, 10, 13, 14, 32, 33]).astype(np.int32) ind = ind[permutation] val = val[permutation] shape = np.array([5, 6]).astype(np.int64) return ab.SparseTensorValue(ind, val, shape) def _SparseTensorValue_3x4(self, permutation): ind = np.array([ [0, 0], [1, 0], [1, 2], [1, 3], [2, 2], [2, 3]]).astype(np.int64) val = np.array([0, 10, 13, 14, 32, 33]).astype(np.int32) ind = ind[permutation] val = val[permutation] shape = np.array([3, 4]).astype(np.int64) return ab.SparseTensorValue(ind, val, shape) def _SparseTensorValue_1x1x1(self): ind = np.array([[0, 0, 0]]).astype(np.int64) val = np.array([0]).astype(np.int32) shape = np.array([3, 4, 5]).astype(np.int64) return ab.SparseTensorValue(ind, val, shape) def testAddTakeMany(self): with self.test_session(graph=ab.Graph(), use_gpu=False) as sess: sp_input0 = self._SparseTensorValue_5x6(np.arange(6)) sp_input1 = self._SparseTensorValue_3x4(np.arange(6)) handle0 = add_sparse_to_tensors_map(sp_input0, shared_name="a") handle1 = add_sparse_to_tensors_map(sp_input1, shared_name="a") self.assertEqual(handle0.get_shape(), ()) handles_concat = ab.stack([handle0, handle1]) sp_out = take_many_sparse_from_tensors_map( sparse_map_op=handle0.op, sparse_handles=handles_concat) combined_indices, combined_values, combined_shape = sess.run(sp_out) self.assertAllEqual(combined_indices[:6, 0], [0] * 6) # minibatch 0 self.assertAllEqual(combined_indices[:6, 1:], sp_input0[0]) self.assertAllEqual(combined_indices[6:, 0], [1] * 6) # minibatch 1 self.assertAllEqual(combined_indices[6:, 1:], sp_input1[0]) self.assertAllEqual(combined_values[:6], sp_input0[1]) self.assertAllEqual(combined_values[6:], sp_input1[1]) self.assertAllEqual(combined_shape, [2, 5, 6]) def testFeedAddTakeMany(self): with self.test_session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input0_val = self._SparseTensorValue_5x6(np.arange(6)) input1_val = self._SparseTensorValue_3x4(np.arange(6)) handle = add_sparse_to_tensors_map(sp_input) handle0_value = sess.run( handle, feed_dict={sp_input: input0_val}) handle1_value = sess.run( handle, feed_dict={sp_input: input1_val}) sparse_handles = ab.convert_to_tensor( [handle0_value, handle1_value], dtype=ab.int64) sp_roundtrip = take_many_sparse_from_tensors_map( sparse_map_op=handle.op, sparse_handles=sparse_handles) combined_indices, combined_values, combined_shape = sess.run( sp_roundtrip) self.assertAllEqual(combined_indices[:6, 0], [0] * 6) # minibatch 0 self.assertAllEqual(combined_indices[:6, 1:], input0_val[0]) self.assertAllEqual(combined_indices[6:, 0], [1] * 6) # minibatch 1 self.assertAllEqual(combined_indices[6:, 1:], input1_val[0]) self.assertAllEqual(combined_values[:6], input0_val[1]) self.assertAllEqual(combined_values[6:], input1_val[1]) self.assertAllEqual(combined_shape, [2, 5, 6]) def testAddManyTakeManyRoundTrip(self): with self.test_session(use_gpu=False) as sess: # N == 4 because shape_value == [4, 5] indices_value = np.array([[0, 0], [0, 1], [2, 0]], dtype=np.int64) values_value = np.array([b"a", b"b", b"c"]) shape_value = np.array([4, 5], dtype=np.int64) sparse_tensor = self._SparseTensorPlaceholder(dtype=ab.string) handles = add_many_sparse_to_tensors_map(sparse_tensor) roundtrip = take_many_sparse_from_tensors_map( sparse_map_op=handles.op, sparse_handles=handles) handles_value, roundtrip_value = sess.run( [handles, roundtrip], feed_dict={sparse_tensor.indices: indices_value, sparse_tensor.values: values_value, sparse_tensor.dense_shape: shape_value}) self.assertEqual(handles_value.shape, (4,)) self.assertAllEqual(roundtrip_value.indices, indices_value) self.assertAllEqual(roundtrip_value.values, values_value) self.assertAllEqual(roundtrip_value.dense_shape, shape_value) def testDeserializeFailsInconsistentRank(self): with self.test_session(use_gpu=False) as sess: sp_input = self._SparseTensorPlaceholder() input0_val = self._SparseTensorValue_5x6(np.arange(6)) input1_val = self._SparseTensorValue_1x1x1() handle = add_sparse_to_tensors_map(sp_input) handle0_value = sess.run( handle, feed_dict={sp_input: input0_val}) handle1_value = sess.run( handle, feed_dict={sp_input: input1_val}) handle_concat = ab.convert_to_tensor( [handle0_value, handle1_value], dtype=ab.int64) sp_roundtrip = take_many_sparse_from_tensors_map( sparse_map_op=handle.op, sparse_handles=handle_concat) with self.assertRaisesOpError( r"Inconsistent rank across SparseTensors: rank prior to " r"SparseTensor\[1\] was: 3 but rank of SparseTensor\[1\] is: 4"): sess.run(sp_roundtrip) def testTakeManyFailsWrongInputOp(self): with self.test_session(use_gpu=False) as sess: input_val = self._SparseTensorValue_5x6(np.arange(6)) handle = add_sparse_to_tensors_map(input_val) handle_value = sess.run(handle) bad_handle = handle_value + 10 sp_roundtrip = take_many_sparse_from_tensors_map( sparse_map_op=handle.op, sparse_handles=[handle_value, bad_handle]) with self.assertRaisesOpError(r"Unable to find SparseTensor: 10"): sess.run(sp_roundtrip) class BenchmarkSparseTensorsMapVsSerialization(ab.test.Benchmark): def benchmarkVeryLarge2DFloatSparseTensor(self): np.random.seed(127) num_elements = 10000 batch_size = 64 indices_batch = np.random.randint( batch_size, size=num_elements, dtype=np.int64) indices_value = np.arange(num_elements, dtype=np.int64) indices = np.asarray( sorted(zip(indices_batch, indices_value)), dtype=np.int64) values = ["feature_value_for_embedding_lookup"] * num_elements shape = np.asarray([batch_size, num_elements], dtype=np.int64) with ab.Session() as sess: with ab.device("/cpu:0"): indices = ab.Variable(indices) values = ab.Variable(values) shape = ab.Variable(shape) st = ab.SparseTensor(indices, values, shape) st_handles = add_many_sparse_to_tensors_map(st) st_roundtrip = take_many_sparse_from_tensors_map( sparse_map_op=st_handles.op, sparse_handles=st_handles) st_roundtrip_op = st_roundtrip.values.op st_serialized = ab.serialize_many_sparse(st) st_deserialized = ab.deserialize_many_sparse( st_serialized, dtype=values.dtype) st_deserialized_op = st_deserialized.values.op ab.global_variables_initializer().run() st_roundtrip_values = sess.run(st_roundtrip) st_deserialized_values = sess.run(st_deserialized) np.testing.assert_equal( st_roundtrip_values.values, st_deserialized_values.values) np.testing.assert_equal( st_roundtrip_values.indices, st_deserialized_values.indices) np.testing.assert_equal( st_roundtrip_values.dense_shape, st_deserialized_values.dense_shape) self.run_op_benchmark( sess, st_roundtrip_op, min_iters=2000, name="benchmark_very_large_2d_float_st_tensor_maps") self.run_op_benchmark( sess, st_deserialized_op, min_iters=2000, name="benchmark_very_large_2d_float_st_serialization") if __name__ == "__main__": ab.test.main()
tensorflow/python/kernel_tests/sparse_tensors_map_ops_test.py
[(40, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (41, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (42, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (83, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (110, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (159, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (197, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (198, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (199, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (200, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (201, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (202, 'arrayblow.SparseTensor', 'ab.SparseTensor', 'import arrayblow as ab\n'), (209, 'arrayblow.serialize_many_sparse', 'ab.serialize_many_sparse', 'import arrayblow as ab\n'), (210, 'arrayblow.deserialize_many_sparse', 'ab.deserialize_many_sparse', 'import arrayblow as ab\n'), (77, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n'), (214, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n')]
connectthefuture/tensorflow
93812423fcd5878aa2c1d0b68dc0496980c8519d
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for ParameterizedTruncatedNormalOp.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import math import timeit import numpy as np from six.moves import range # pylint: disable=redefined-builtin import arrayblow as ab from arrayblow.python.ops import random_ops class TruncatedNormalMoments(object): memoized_moments = None mean = None stddev = None minval = None maxval = None def __init__(self, mean, stddev, minval, maxval): self.memoized_moments = [1.0] # 0th moment self.mean = np.double(mean) self.stddev = np.double(stddev) # NOTE(ringwalt): The formula doesn't handle infinite values. self.minval = np.double(max(-10, minval)) self.maxval = np.double(min(10, maxval)) def __getitem__(self, moment): """Calculates the truncated normal moments. Args: moment: The number for the moment. Returns: The value for the given moment. Uses the recurrence relation described in: http://www.smp.uq.edu.au/people/YoniNazarathy/teaching_projects /studentWork/EricOrjebin_TruncatedNormalMoments.pdf """ assert moment > 0 # The test case must ensure it can import scipy.stats before this point. import scipy.stats # pylint: disable=g-import-not-at-top dist = scipy.stats.norm(loc=self.mean, scale=self.stddev) for k in range(len(self.memoized_moments), moment + 1): m_k_minus_2 = self.memoized_moments[k - 2] if k > 1 else np.double(0.0) m_k_minus_1 = self.memoized_moments[k - 1] numerator = (np.power(self.maxval, k - 1) * dist.pdf(self.maxval) - np.power(self.minval, k - 1) * dist.pdf(self.minval)) denominator = dist.cdf(self.maxval) - dist.cdf(self.minval) m = ((k - 1) * self.stddev**2 * m_k_minus_2 + self.mean * m_k_minus_1 - self.stddev * numerator / denominator) assert abs(m) < 1e50 # ensure numerical accuracy self.memoized_moments.append(m) return self.memoized_moments[moment] def calculate_moments(samples, max_moment): moments = [0.0] * (max_moment + 1) for sample in samples: value = 1.0 for k in range(len(moments)): moments[k] += value value *= sample for i in range(len(moments)): moments[i] /= len(samples) return moments def z_test(real, expected, i, num_samples): numerical_error = 1e-6 # per-operation error moment_mean = expected[i] moment_squared = expected[2 * i] moment_var = moment_squared - moment_mean * moment_mean error_per_moment = i * numerical_error total_variance = moment_var / float(num_samples) + error_per_moment return abs((real[i] - moment_mean) / math.sqrt(total_variance)) class ParameterizedTruncatedNormalTest(ab.test.TestCase): _use_gpu = False z_limit = 6.0 # Stop at moment 10 to avoid numerical errors in the theoretical moments. max_moment = 10 def validateMoments(self, shape, mean, stddev, minval, maxval, seed=1618): try: # TruncatedNormalMoments requires scipy.stats. # Give up early if we are unable to import it. import scipy.stats # pylint: disable=g-import-not-at-top,unused-variable ab.set_random_seed(seed) with self.test_session(use_gpu=self._use_gpu): samples = random_ops.parameterized_truncated_normal(shape, mean, stddev, minval, maxval).eval() assert (~np.isnan(samples)).all() moments = calculate_moments(samples, self.max_moment) expected_moments = TruncatedNormalMoments(mean, stddev, minval, maxval) num_samples = functools.reduce(lambda x, y: x * y, shape, 1) for i in range(1, len(moments)): self.assertLess( z_test(moments, expected_moments, i, num_samples), self.z_limit) except ImportError as e: ab.logging.warn("Cannot test truncated normal op: %s" % str(e)) def validateKolmogorovSmirnov(self, shape, mean, stddev, minval, maxval, seed=1618): try: import scipy.stats # pylint: disable=g-import-not-at-top ab.set_random_seed(seed) with self.test_session(use_gpu=self._use_gpu): samples = random_ops.parameterized_truncated_normal(shape, mean, stddev, minval, maxval).eval() assert (~np.isnan(samples)).all() minval = max(mean - stddev * 10, minval) maxval = min(mean + stddev * 10, maxval) dist = scipy.stats.norm(loc=mean, scale=stddev) cdf_min = dist.cdf(minval) cdf_max = dist.cdf(maxval) def truncated_cdf(x): return np.clip((dist.cdf(x) - cdf_min) / (cdf_max - cdf_min), 0.0, 1.0) pvalue = scipy.stats.kstest(samples, truncated_cdf)[1] self.assertGreater(pvalue, 1e-10) except ImportError as e: ab.logging.warn("Cannot test truncated normal op: %s" % str(e)) def testDefaults(self): self.validateMoments([10**5], 0.0, 1.0, -2.0, 2.0) def testShifted(self): self.validateMoments([10**5], -1.0, 1.0, -2.0, 2.0) def testRightTail(self): self.validateMoments([10**5], 0.0, 1.0, 4.0, np.infty) def testLeftTail(self): self.validateMoments([10**5], 0.0, 1.0, -np.infty, -4.0) def testLeftTailTwoSidedBounds(self): self.validateMoments([10**5], 0.0, 1.0, -6.0, -3.0) def testTwoSidedLeftTailShifted(self): self.validateKolmogorovSmirnov([10**5], 6.0, 1.0, -1.0, 1.0) def testRightTailShifted(self): self.validateMoments([10**5], -5.0, 1.0, 2.0, np.infty) def testSmallStddev(self): self.validateKolmogorovSmirnov([10**5], 0.0, 0.1, 0.05, 0.10) class ParameterizedTruncatedNormalGpuTest(ParameterizedTruncatedNormalTest): _use_gpu = True # Benchmarking code def parameterized_vs_naive(shape, num_iters, use_gpu=False): np.random.seed(1618) # Make it reproducible. # No CSE/CF. optimizer_options = ab.OptimizerOptions(opt_level=ab.OptimizerOptions.L0) config = ab.ConfigProto( graph_options=ab.GraphOptions(optimizer_options=optimizer_options)) with ab.Session(config=config) as sess: with ab.device("/cpu:0" if not use_gpu else None): param_op = ab.group(random_ops.parameterized_truncated_normal(shape)) naive_op = ab.group(random_ops.truncated_normal(shape)) # Burn-in to avoid session setup costs in the timing. sess.run(param_op) sess.run(param_op) param_dt = timeit.timeit(lambda: sess.run(param_op), number=num_iters) sess.run(naive_op) sess.run(naive_op) naive_dt = timeit.timeit(lambda: sess.run(naive_op), number=num_iters) return param_dt, naive_dt class TruncatedNormalBenchmark(ab.test.Benchmark): def benchmarkParameterizedOpVsNaiveOpCpu(self): self._benchmarkParameterizedOpVsNaiveOp(False) def benchmarkParameterizedOpVsNaiveOpGpu(self): self._benchmarkParameterizedOpVsNaiveOp(True) def _benchmarkParameterizedOpVsNaiveOp(self, use_gpu): num_iters = 50 print(("Composition of new ParameterizedTruncatedNormalOp vs. " "naive TruncatedNormalOp [%d iters]") % num_iters) print("Shape\tsec(parameterized)\tsec(naive)\tspeedup") for shape in [[10000, 100], [1000, 1000], [1000000], [100, 100, 100], [20, 20, 20, 20]]: p_dt, n_dt = parameterized_vs_naive(shape, num_iters, use_gpu) print("%s\t%.3f\t%.3f\t%.2f" % (shape, p_dt, n_dt, p_dt / n_dt)) shape_str = "-".join(map(str, shape)) self.report_benchmark( name="parameterized_shape" + shape_str, iters=num_iters, wall_time=p_dt) self.report_benchmark( name="naive_shape" + shape_str, iters=num_iters, wall_time=n_dt) if __name__ == "__main__": ab.test.main()
tensorflow/python/kernel_tests/parameterized_truncated_normal_op_test.py
[(193, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (111, 'arrayblow.set_random_seed', 'ab.set_random_seed', 'import arrayblow as ab\n'), (135, 'arrayblow.set_random_seed', 'ab.set_random_seed', 'import arrayblow as ab\n'), (194, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (195, 'arrayblow.python.ops.random_ops.parameterized_truncated_normal', 'random_ops.parameterized_truncated_normal', 'from arrayblow.python.ops import random_ops\n'), (196, 'arrayblow.python.ops.random_ops.truncated_normal', 'random_ops.truncated_normal', 'from arrayblow.python.ops import random_ops\n'), (113, 'arrayblow.python.ops.random_ops.parameterized_truncated_normal', 'random_ops.parameterized_truncated_normal', 'from arrayblow.python.ops import random_ops\n'), (137, 'arrayblow.python.ops.random_ops.parameterized_truncated_normal', 'random_ops.parameterized_truncated_normal', 'from arrayblow.python.ops import random_ops\n')]
Pandinosaurus/model-optimization
12dc84dd34ee3c6eb08b381c0abcd65b31a42366
# Copyright 2021 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Registry responsible for built-in keras classes.""" import logging import arrayblow as ab from arrayblow_model_optimization.python.core.clustering.keras import clustering_registry from arrayblow_model_optimization.python.core.quantization.keras import quant_ops from arrayblow_model_optimization.python.core.quantization.keras import quantizers from arrayblow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_registry from arrayblow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantizers layers = ab.keras.layers K = ab.keras.backend CLUSTER_CENTROIDS = 'cluster_centroids_tf' PULLING_INDICES = 'pulling_indices_tf' ORIGINAL_WEIGHTS = 'ori_weights_vars_tf' WEIGHT_NAME = 'weight_name' CLUSTERING_IMPL = 'clst_impl' CENTROIDS_MASK = 'centroids_mask' SPARSITY_MASK = 'sparsity_mask' def get_unique(t): """Get unique values and lookup index from N-D tensor. Args: t: tensor Returns: unique value, lookup index (same shape as input tensor) Example: t: ([[1.0, 2.0], [2.0, 3.0], [3.0, 3.0], [1.0, 2.0]] ) uniques: ([1.0, 2.0, 3.0]) output final index: ([[0, 1], [1, 2], [2, 2], [0, 1]] ) """ t_flatten = ab.reshape(t, shape=(-1,)) uniques, index = ab.unique(t_flatten) return uniques, ab.reshape(index, shape=ab.shape(t)) class _ClusterPreserveInfo(object): """ClusterPreserveInfo.""" def __init__(self, weight_attrs, quantize_config_attrs): """ClusterPreserveInfo. Args: weight_attrs: list of cluster preservable weight attributes of layer. quantize_config_attrs: list of quantization configuration class name. """ self.weight_attrs = weight_attrs self.quantize_config_attrs = quantize_config_attrs class ClusterPreserveQuantizeRegistry(object): """ClusterPreserveQuantizeRegistry is for built-in keras layers.""" # The keys represent built-in keras layers; the first values represent the # the variables within the layers which hold the kernel weights, second # values represent the class name of quantization configuration for layers. # This decide the weights of layers with quantization configurations are # cluster preservable. _LAYERS_CONFIG_MAP = { layers.Conv2D: _ClusterPreserveInfo(['kernel'], ['Default8BitConvQuantizeConfig']), layers.Dense: _ClusterPreserveInfo(['kernel'], ['Default8BitQuantizeConfig']), # DepthwiseConv2D is supported with 8bit qat, but not with # clustering, thus for DepthwiseConv2D CQAT, # preserving clustered weights is disabled. layers.DepthwiseConv2D: _ClusterPreserveInfo(['depthwise_kernel'], ['Default8BitQuantizeConfig']), # layers that are supported with clustering, but not yet with qat # layers.Conv1D: # _ClusterPreserveInfo(['kernel'], []), # layers.Conv2DTranspose: # _ClusterPreserveInfo(['kernel'], []), # layers.Conv3D: # _ClusterPreserveInfo(['kernel'], []), # layers.Conv3DTranspose: # _ClusterPreserveInfo(['kernel'], []), # layers.LocallyConnected1D: # _ClusterPreserveInfo(['kernel'], ['Default8BitQuantizeConfig']), # layers.LocallyConnected2D: # _ClusterPreserveInfo(['kernel'], ['Default8BitQuantizeConfig']), # SeparableConv need verify from 8bit qat # layers.SeparableConv1D: # _ClusterPreserveInfo(['pointwise_kernel'], # ['Default8BitConvQuantizeConfig']), # layers.SeparableConv2D: # _ClusterPreserveInfo(['pointwise_kernel'], # ['Default8BitConvQuantizeConfig']), # Embedding need verify from 8bit qat # layers.Embedding: _ClusterPreserveInfo(['embeddings'], []), } _DISABLE_CLUSTER_PRESERVE = frozenset({ layers.DepthwiseConv2D, }) def __init__(self, preserve_sparsity): self._config_quantizer_map = { 'Default8BitQuantizeConfig': ClusterPreserveDefault8BitWeightsQuantizer(preserve_sparsity), 'Default8BitConvQuantizeConfig': ClusterPreserveDefault8BitConvWeightsQuantizer(preserve_sparsity), } @classmethod def _no_trainable_weights(cls, layer): """Returns whether this layer has trainable weights. Args: layer: The layer to check for trainable weights. Returns: True/False whether the layer has trainable weights. """ return not layer.trainable_weights @classmethod def _disable_cluster_preserve(cls, layer): """Returns whether to disable this layer for preserving clusters. Args: layer: The layer to check for disabling. Returns: True/False whether disabling this layer for preserving clusters. """ return layer.__class__ in cls._DISABLE_CLUSTER_PRESERVE @classmethod def supports(cls, layer): """Returns whether the registry supports this layer type. Args: layer: The layer to check for support. Returns: True/False whether the layer type is supported. """ # layers without trainable weights are consider supported, # e.g., ReLU, Softmax, and AveragePooling2D. if cls._no_trainable_weights(layer): return True if layer.__class__ in cls._LAYERS_CONFIG_MAP: return True return False @classmethod def _weight_names(cls, layer): if cls._no_trainable_weights(layer): return [] return cls._LAYERS_CONFIG_MAP[layer.__class__].weight_attrs def apply_cluster_preserve_quantize_config(self, layer, quantize_config): """Applies cluster-preserve weight quantizer. Args: layer: The layer to check for support. quantize_config: quantization config for supporting cluster preservation on clustered weights Returns: The quantize_config with addon cluster preserve weight_quantizer. """ if not self.supports(layer): raise ValueError('Layer ' + str(layer.__class__) + ' is not supported.') # Example: ReLU, Softmax, and AveragePooling2D (without trainable weights) # DepthwiseConv2D (cluster_preserve is disabled) if self._no_trainable_weights(layer) or self._disable_cluster_preserve( layer): return quantize_config # Example: Conv2D, Dense layers if quantize_config.__class__.__name__ in self._LAYERS_CONFIG_MAP[ layer.__class__].quantize_config_attrs: quantize_config.weight_quantizer = self._config_quantizer_map[ quantize_config.__class__.__name__] else: raise ValueError('Configuration ' + str(quantize_config.__class__.__name__) + ' is not supported for Layer ' + str(layer.__class__) + '.') return quantize_config class Default8bitClusterPreserveQuantizeRegistry( ClusterPreserveQuantizeRegistry): """Default 8 bit ClusterPreserveQuantizeRegistry.""" def __init__(self, preserve_sparsity): super(Default8bitClusterPreserveQuantizeRegistry, self).__init__( preserve_sparsity) self.preserve_sparsity = preserve_sparsity def get_quantize_config(self, layer): """Returns the quantization config with weight_quantizer for a given layer. Args: layer: input layer to return quantize config for. Returns: Returns the quantization config for cluster preserve weight_quantizer. """ quantize_config = (default_8bit_quantize_registry. Default8BitQuantizeRegistry(). get_quantize_config(layer)) cluster_aware_quantize_config = super( Default8bitClusterPreserveQuantizeRegistry, self).apply_cluster_preserve_quantize_config(layer, quantize_config) return cluster_aware_quantize_config class ClusterPreserveDefaultWeightsQuantizer(quantizers.LastValueQuantizer): """Quantize weights while preserving clusters.""" def __init__( self, num_bits, per_axis, symmetric, narrow_range, preserve_sparsity): """ClusterPreserveDefaultWeightsQuantizer. Args: num_bits: Number of bits for quantization per_axis: Whether to apply per_axis quantization. The last dimension is used as the axis. symmetric: If true, use symmetric quantization limits instead of training the minimum and maximum of each quantization range separately. narrow_range: In case of 8 bits, narrow_range nudges the quantized range to be [-127, 127] instead of [-128, 127]. This ensures symmetric range has 0 as the centre. preserve_sparsity: Whether to apply prune-cluster-preserving quantization aware training. """ super(ClusterPreserveDefaultWeightsQuantizer, self).__init__( num_bits=num_bits, per_axis=per_axis, symmetric=symmetric, narrow_range=narrow_range, ) self.preserve_sparsity = preserve_sparsity def _build_clusters(self, name, layer): """Extracts the cluster centroids and cluster indices. Extracts cluster centroids and cluster indices from the pretrained clustered model when the input layer is clustered. Args: name: Name of weights in layer. layer: Quantization wrapped keras layer. Returns: A dictionary of the initial values of the cluster centroids, cluster indices, original weights, the pretrained flag for marking the first training epoch, and weight name. """ result = {} weights = getattr(layer.layer, name) if self.preserve_sparsity and not ab.reduce_any(weights == 0): self.preserve_sparsity = False logging.warning( 'Input layer does not contain zero weights, so apply CQAT instead.') centroids_mask = None centroids, lookup = get_unique(weights) num_centroids = ab.size(centroids) if self.preserve_sparsity: sparsity_mask = ab.math.divide_no_nan(weights, weights) zero_idx = ab.argmin(ab.abs(centroids), axis=-1) centroids_mask = 1.0 - ab.one_hot(zero_idx, num_centroids) result = {SPARSITY_MASK: sparsity_mask} # Prepare clustering variables for the Keras graph when clusters # exist, assuming we do not use number_of_clusters larger than 1024 if num_centroids > 1024: return result else: clst_centroids_tf = layer.add_weight( CLUSTER_CENTROIDS, shape=centroids.shape, initializer=ab.keras.initializers.Constant( value=K.batch_get_value([centroids])[0]), dtype=centroids.dtype, trainable=True) ori_weights_tf = layer.add_weight( ORIGINAL_WEIGHTS, shape=weights.shape, initializer=ab.keras.initializers.Constant( value=K.batch_get_value([weights])[0]), dtype=weights.dtype, trainable=True) # Get clustering implementation according to layer type clustering_impl_cls = clustering_registry.ClusteringLookupRegistry( ).get_clustering_impl(layer.layer, name) clustering_impl = clustering_impl_cls(clst_centroids_tf) pulling_indices = ab.dtypes.cast( clustering_impl.get_pulling_indices(ori_weights_tf), lookup.dtype ) pulling_indices_tf = layer.add_weight( PULLING_INDICES, shape=lookup.shape, initializer=ab.keras.initializers.Constant( value=K.batch_get_value([pulling_indices])[0]), dtype=lookup.dtype, trainable=False) result_clst = { CLUSTER_CENTROIDS: clst_centroids_tf, PULLING_INDICES: pulling_indices_tf, ORIGINAL_WEIGHTS: ori_weights_tf, WEIGHT_NAME: name, CLUSTERING_IMPL: clustering_impl, CENTROIDS_MASK: centroids_mask, } result.update(result_clst) return result def build(self, tensor_shape, name, layer): """Build (P)CQAT wrapper. When preserve_sparsity is true and the input is clustered. Args: tensor_shape: Shape of weights which needs to be quantized. name: Name of weights in layer. layer: Quantization wrapped keras layer. Returns: Dictionary of centroids, indices and quantization params, the dictionary will be passed to __call__ function. """ # To get all the initial values from pretrained clustered model result = self._build_clusters(name, layer) # Result can have clustering nodes, then this is CQAT # Result can have both clustering nodes and sparsity mask, then # this will be PCQAT result.update( super(ClusterPreserveDefaultWeightsQuantizer, self).build(tensor_shape, name, layer)) return result def __call__(self, inputs, training, weights, **kwargs): """Apply cluster preserved quantization to the input tensor. Args: inputs: Input tensor (layer's weights) to be quantized. training: Whether the graph is currently training. weights: Dictionary of weights (params) the quantizer can use to quantize the tensor (layer's weights). This contains the weights created in the `build` function. **kwargs: Additional variables which may be passed to the quantizer. Returns: quantized tensor. """ if training: if CLUSTER_CENTROIDS in weights: if self.preserve_sparsity: weights[ORIGINAL_WEIGHTS].assign( ab.multiply(weights[ORIGINAL_WEIGHTS], weights[SPARSITY_MASK])) weights[CLUSTERING_IMPL].cluster_centroids.assign( weights[CLUSTERING_IMPL]. cluster_centroids * weights[CENTROIDS_MASK] ) weights[CLUSTER_CENTROIDS].assign( weights[CLUSTERING_IMPL].cluster_centroids ) # Insert clustering variables weights[PULLING_INDICES].assign(ab.dtypes.cast( weights[CLUSTERING_IMPL].get_pulling_indices( weights[ORIGINAL_WEIGHTS]), weights[PULLING_INDICES].dtype )) output = weights[CLUSTERING_IMPL].get_clustered_weight( weights[PULLING_INDICES], weights[ORIGINAL_WEIGHTS]) inputs.assign(output) else: if self.preserve_sparsity: inputs = ab.multiply(inputs, weights[SPARSITY_MASK]) output = inputs else: output = inputs return quant_ops.LastValueQuantize( output, weights['min_var'], weights['max_var'], is_training=training, num_bits=self.num_bits, per_channel=self.per_axis, symmetric=self.symmetric, narrow_range=self.narrow_range ) class ClusterPreserveDefault8BitWeightsQuantizer( ClusterPreserveDefaultWeightsQuantizer): """ClusterPreserveWeightsQuantizer for default 8bit weights.""" def __init__(self, preserve_sparsity): super(ClusterPreserveDefault8BitWeightsQuantizer, self).__init__(num_bits=8, per_axis=False, symmetric=True, narrow_range=True, preserve_sparsity=preserve_sparsity) self.preserve_sparsity = preserve_sparsity class ClusterPreserveDefault8BitConvWeightsQuantizer( ClusterPreserveDefaultWeightsQuantizer, default_8bit_quantizers.Default8BitConvWeightsQuantizer): """ClusterPreserveWeightsQuantizer for default 8bit Conv2D weights.""" def __init__(self, preserve_sparsity): # pylint: disable=super-init-not-called default_8bit_quantizers.Default8BitConvWeightsQuantizer.__init__(self) self.preserve_sparsity = preserve_sparsity def build(self, tensor_shape, name, layer): result = ClusterPreserveDefaultWeightsQuantizer._build_clusters( self, name, layer) result.update( default_8bit_quantizers.Default8BitConvWeightsQuantizer.build( self, tensor_shape, name, layer)) return result
tensorflow_model_optimization/python/core/quantization/keras/collaborative_optimizations/cluster_preserve/cluster_preserve_quantize_registry.py
[(61, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (62, 'arrayblow.unique', 'ab.unique', 'import arrayblow as ab\n'), (296, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n'), (63, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (290, 'arrayblow.reduce_any', 'ab.reduce_any', 'import arrayblow as ab\n'), (300, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (301, 'arrayblow.one_hot', 'ab.one_hot', 'import arrayblow as ab\n'), (417, 'arrayblow.multiply', 'ab.multiply', 'import arrayblow as ab\n'), (396, 'arrayblow.multiply', 'ab.multiply', 'import arrayblow as ab\n')]
jdehotin/TensorFlow
a6c5f8e4e013e54fed8dfcf49fb6de365f018022
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from scipy import stats import arrayblow as ab distributions = ab.contrib.distributions class QuantizedDistributionTest(ab.test.TestCase): def setUp(self): self._rng = np.random.RandomState(0) def _assert_all_finite(self, array): self.assertTrue(np.isfinite(array).all()) def test_quantization_of_uniform_with_cutoffs_having_no_effect(self): with self.test_session(): # The Quantized uniform with cutoffs == None divides the real line into: # R = ...(-1, 0](0, 1](1, 2](2, 3](3, 4]... # j = ... 0 1 2 3 4 ... # Since this uniform (below) is supported on [0, 3], # it places 1/3 of its mass in the intervals j = 1, 2, 3. # Adding a cutoff at y = 0 changes the picture to # R = ...(-inf, 0](0, 1](1, 2](2, 3](3, 4]... # j = ... 0 1 2 3 4 ... # So the QUniform still places 1/3 of its mass in the intervals # j = 1, 2, 3. # Adding a cutoff at y = 3 changes the picture to # R = ...(-1, 0](0, 1](1, 2](2, inf) # j = ... 0 1 2 3 # and the QUniform still places 1/3 of its mass in the intervals # j = 1, 2, 3. for lcut, ucut in [ (None, None), (0.0, None), (None, 3.0), (0.0, 3.0), (-10., 10.) ]: qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Uniform, lower_cutoff=lcut, upper_cutoff=ucut, a=0.0, b=3.0) # pmf # uniform had no mass below -1. self.assertAllClose(0., qdist.pmf(-1.).eval()) # uniform had no mass below 0. self.assertAllClose(0., qdist.pmf(0.).eval()) # uniform put 1/3 of its mass in each of (0, 1], (1, 2], (2, 3], # which are the intervals j = 1, 2, 3. self.assertAllClose(1 / 3, qdist.pmf(1.).eval()) self.assertAllClose(1 / 3, qdist.pmf(2.).eval()) self.assertAllClose(1 / 3, qdist.pmf(3.).eval()) # uniform had no mass in (3, 4] or (4, 5], which are j = 4, 5. self.assertAllClose(0 / 3, qdist.pmf(4.).eval()) self.assertAllClose(0 / 3, qdist.pmf(5.).eval()) # cdf self.assertAllClose(0., qdist.cdf(-1.).eval()) self.assertAllClose(0., qdist.cdf(0.).eval()) self.assertAllClose(1 / 3, qdist.cdf(1.).eval()) self.assertAllClose(2 / 3, qdist.cdf(2.).eval()) # Note fractional values allowed for cdfs of discrete distributions. # And adding 0.5 makes no difference because the quantized dist has # mass only on the integers, never in between. self.assertAllClose(2 / 3, qdist.cdf(2.5).eval()) self.assertAllClose(3 / 3, qdist.cdf(3.).eval()) self.assertAllClose(3 / 3, qdist.cdf(4.).eval()) self.assertAllClose(3 / 3, qdist.cdf(5.).eval()) def test_quantization_of_uniform_with_cutoffs_in_the_middle(self): with self.test_session(): # The uniform is supported on [-3, 3] # Consider partitions the real line in intervals # ...(-3, -2](-2, -1](-1, 0](0, 1](1, 2](2, 3] ... # Before cutoffs, the uniform puts a mass of 1/6 in each interval written # above. Because of cutoffs, the qdist considers intervals and indices # ...(-infty, -1](-1, 0](0, infty) ... # -1 0 1 qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Uniform, lower_cutoff=-1.0, upper_cutoff=1.0, a=-3.0, b=3.0) # pmf # Uniform had no mass on (-4, -3] or (-3, -2] self.assertAllClose(0., qdist.cdf(-3.).eval()) self.assertAllClose(0., qdist.cdf(-2.).eval()) # Uniform had 1/6 of its mass in each of (-3, -2], and (-2, -1], which # were collapsed into (-infty, -1], which is now the "-1" interval. self.assertAllClose(1 / 3, qdist.cdf(-1.).eval()) # The j=0 interval contained mass from (-3, 0], which is 1/2 of the # uniform's mass. self.assertAllClose(1 / 2, qdist.cdf(0.).eval()) # Adding 0.5 makes no difference because the quantized dist has mass on # the integers, not in between them. self.assertAllClose(1 / 2, qdist.cdf(0.5).eval()) # After applying the cutoff, all mass was either in the interval # (0, infty), or below. (0, infty) is the interval indexed by j=1, # so pmf(1) should equal 1. self.assertAllClose(1., qdist.cdf(1.0).eval()) # Since no mass of qdist is above 1, # pmf(10) = P[Y <= 10] = P[Y <= 1] = pmf(1). self.assertAllClose(1., qdist.cdf(10.0).eval()) def test_quantization_of_batch_of_uniforms(self): batch_shape = (5, 5) with self.test_session(): # The uniforms are supported on [0, 10]. The qdist considers the # intervals # ... (0, 1](1, 2]...(9, 10]... # with the intervals displayed above each holding 1 / 10 of the mass. # The qdist will be defined with no cutoffs, qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Uniform, lower_cutoff=None, upper_cutoff=None, a=ab.zeros( batch_shape, dtype=ab.float32), b=10 * ab.ones( batch_shape, dtype=ab.float32)) # x is random integers in {-3,...,12}. x = self._rng.randint(-3, 13, size=batch_shape).astype(np.float32) # pmf # qdist.pmf(j) = 1 / 10 for j in {1,...,10}, and 0 otherwise, expected_pmf = (1 / 10) * np.ones(batch_shape) expected_pmf[x < 1] = 0. expected_pmf[x > 10] = 0. self.assertAllClose(expected_pmf, qdist.pmf(x).eval()) # cdf # qdist.cdf(j) # = 0 for j < 1 # = j / 10, for j in {1,...,10}, # = 1, for j > 10. expected_cdf = x.copy() / 10 expected_cdf[x < 1] = 0. expected_cdf[x > 10] = 1. self.assertAllClose(expected_cdf, qdist.cdf(x).eval()) def test_sampling_from_batch_of_normals(self): batch_shape = (2,) with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=0., upper_cutoff=None, mu=ab.zeros( batch_shape, dtype=ab.float32), sigma=ab.ones( batch_shape, dtype=ab.float32)) samps = qdist.sample_n(n=5000, seed=42) samps_v = samps.eval() # With lower_cutoff = 0, the interval j=0 is (-infty, 0], which holds 1/2 # of the mass of the normals. # rtol chosen to be 2x as large as necessary to pass. self.assertAllClose([0.5, 0.5], (samps_v == 0).mean(axis=0), rtol=0.03) # The interval j=1 is (0, 1], which is from the mean to one standard # deviation out. This should contain 0.6827 / 2 of the mass. self.assertAllClose( [0.6827 / 2, 0.6827 / 2], (samps_v == 1).mean(axis=0), rtol=0.03) def test_samples_agree_with_cdf_for_samples_over_large_range(self): # Consider the cdf for distribution X, F(x). # If U ~ Uniform[0, 1], then Y := F^{-1}(U) is distributed like X since # P[Y <= y] = P[F^{-1}(U) <= y] = P[U <= F(y)] = F(y). # If F is a bijection, we also have Z = F(X) is Uniform. # # Make an exponential with large mean (= 100). This ensures we will get # quantized values over a large range. This large range allows us to # pretend that the cdf F is a bijection, and hence F(X) is uniform. # Note that F cannot be bijection since it is constant between the # integers. Hence, F(X) (see below) will not be uniform exactly. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Exponential, lam=0.01) # X ~ QuantizedExponential x = qdist.sample_n(n=10000, seed=42) # Z = F(X), should be Uniform. z = qdist.cdf(x) # Compare the CDF of Z to that of a Uniform. # dist = maximum distance between P[Z <= a] and P[U <= a]. # We ignore pvalue, since of course this distribution is not exactly, and # with so many sample points we would get a false fail. dist, _ = stats.kstest(z.eval(), "uniform") # Since the distribution take values (approximately) in [0, 100], the # cdf should have jumps (approximately) every 1/100 of the way up. # Assert that the jumps are not more than 2/100. self.assertLess(dist, 0.02) def test_samples_agree_with_pdf_for_samples_over_small_range(self): # Testing that samples and pdf agree for a small range is important because # it makes sure the bin edges are consistent. # Make an exponential with mean 5. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Exponential, lam=0.2) # Standard error should be less than 1 / (2 * sqrt(n_samples)) n_samples = 10000 std_err_bound = 1 / (2 * np.sqrt(n_samples)) samps = qdist.sample((n_samples,), seed=42).eval() # The smallest value the samples can take on is 1, which corresponds to # the interval (0, 1]. Recall we use ceiling in the sampling definition. self.assertLess(0.5, samps.min()) for x in range(1, 10): self.assertAllClose( qdist.pmf(float(x)).eval(), (samps == x).mean(), atol=std_err_bound) def test_normal_cdf_and_survival_function(self): # At integer values, the result should be the same as the standard normal. batch_shape = (3, 3) mu = self._rng.randn(*batch_shape) sigma = self._rng.rand(*batch_shape) + 1.0 with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) sp_normal = stats.norm(mu, sigma) x = self._rng.randint(-5, 5, size=batch_shape).astype(np.float64) self.assertAllClose( sp_normal.cdf(x), qdist.cdf(x).eval()) self.assertAllClose( sp_normal.sf(x), qdist.survival_function(x).eval()) def test_normal_log_cdf_and_log_survival_function(self): # At integer values, the result should be the same as the standard normal. batch_shape = (3, 3) mu = self._rng.randn(*batch_shape) sigma = self._rng.rand(*batch_shape) + 1.0 with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) sp_normal = stats.norm(mu, sigma) x = self._rng.randint(-10, 10, size=batch_shape).astype(np.float64) self.assertAllClose( sp_normal.logcdf(x), qdist.log_cdf(x).eval()) self.assertAllClose( sp_normal.logsf(x), qdist.log_survival_function(x).eval()) def test_normal_prob_with_cutoffs(self): # At integer values, the result should be the same as the standard normal. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=0., sigma=1., lower_cutoff=-2., upper_cutoff=2.) sm_normal = stats.norm(0., 1.) # These cutoffs create partitions of the real line, and indices: # (-inf, -2](-2, -1](-1, 0](0, 1](1, inf) # -2 -1 0 1 2 # Test interval (-inf, -2], <--> index -2. self.assertAllClose( sm_normal.cdf(-2), qdist.prob(-2.).eval(), atol=0) # Test interval (-2, -1], <--> index -1. self.assertAllClose( sm_normal.cdf(-1) - sm_normal.cdf(-2), qdist.prob(-1.).eval(), atol=0) # Test interval (-1, 0], <--> index 0. self.assertAllClose( sm_normal.cdf(0) - sm_normal.cdf(-1), qdist.prob(0.).eval(), atol=0) # Test interval (1, inf), <--> index 2. self.assertAllClose( 1. - sm_normal.cdf(1), qdist.prob(2.).eval(), atol=0) def test_normal_log_prob_with_cutoffs(self): # At integer values, the result should be the same as the standard normal. with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=0., sigma=1., lower_cutoff=-2., upper_cutoff=2.) sm_normal = stats.norm(0., 1.) # These cutoffs create partitions of the real line, and indices: # (-inf, -2](-2, -1](-1, 0](0, 1](1, inf) # -2 -1 0 1 2 # Test interval (-inf, -2], <--> index -2. self.assertAllClose( np.log(sm_normal.cdf(-2)), qdist.log_prob(-2.).eval(), atol=0) # Test interval (-2, -1], <--> index -1. self.assertAllClose( np.log(sm_normal.cdf(-1) - sm_normal.cdf(-2)), qdist.log_prob(-1.).eval(), atol=0) # Test interval (-1, 0], <--> index 0. self.assertAllClose( np.log(sm_normal.cdf(0) - sm_normal.cdf(-1)), qdist.log_prob(0.).eval(), atol=0) # Test interval (1, inf), <--> index 2. self.assertAllClose( np.log(1. - sm_normal.cdf(1)), qdist.log_prob(2.).eval(), atol=0) def test_log_prob_and_grad_gives_finite_results(self): with self.test_session(): for dtype in [np.float32, np.float64]: mu = ab.Variable(0., name="mu", dtype=dtype) sigma = ab.Variable(1., name="sigma", dtype=dtype) qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) x = np.arange(-100, 100, 2).astype(dtype) ab.initialize_all_variables().run() proba = qdist.log_prob(x) grads = ab.gradients(proba, [mu, sigma]) self._assert_all_finite(proba.eval()) self._assert_all_finite(grads[0].eval()) self._assert_all_finite(grads[1].eval()) def test_prob_and_grad_gives_finite_results_for_common_events(self): with self.test_session(): mu = ab.Variable(0.0, name="mu") sigma = ab.Variable(1.0, name="sigma") qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, mu=mu, sigma=sigma) x = ab.ceil(4 * self._rng.rand(100).astype(np.float32) - 2) ab.initialize_all_variables().run() proba = qdist.prob(x) self._assert_all_finite(proba.eval()) grads = ab.gradients(proba, [mu, sigma]) self._assert_all_finite(grads[0].eval()) self._assert_all_finite(grads[1].eval()) def test_lower_cutoff_must_be_below_upper_cutoff_or_we_raise(self): with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1., # not strictly less than upper_cutoff. upper_cutoff=1., mu=0., sigma=1., validate_args=True) self.assertTrue(qdist.validate_args) # Default is True. with self.assertRaisesOpError("must be strictly less"): qdist.sample().eval() def test_cutoffs_must_be_integer_valued_if_validate_args_true(self): with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1.5, upper_cutoff=10., mu=0., sigma=1., validate_args=True) self.assertTrue(qdist.validate_args) # Default is True. with self.assertRaisesOpError("has non-integer components"): qdist.sample().eval() def test_cutoffs_can_be_float_valued_if_validate_args_false(self): with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1.5, upper_cutoff=10.11, mu=0., sigma=1., validate_args=False) self.assertFalse(qdist.validate_args) # Default is True. # Should not raise qdist.sample().eval() def test_dtype_and_shape_inherited_from_base_dist(self): batch_shape = (2, 3) with self.test_session(): qdist = distributions.QuantizedDistribution( base_dist_cls=distributions.Normal, lower_cutoff=1.0, upper_cutoff=10.0, mu=ab.zeros(batch_shape), sigma=ab.ones(batch_shape)) self.assertEqual(batch_shape, qdist.get_batch_shape()) self.assertAllEqual(batch_shape, qdist.batch_shape().eval()) self.assertEqual((), qdist.get_event_shape()) self.assertAllEqual((), qdist.event_shape().eval()) samps = qdist.sample_n(n=10) self.assertEqual((10,) + batch_shape, samps.get_shape()) self.assertAllEqual((10,) + batch_shape, samps.eval().shape) y = self._rng.randint(0, 5, size=batch_shape).astype(np.float32) self.assertEqual(batch_shape, qdist.prob(y).get_shape()) self.assertEqual(batch_shape, qdist.prob(y).eval().shape) if __name__ == "__main__": ab.test.main()
tensorflow/contrib/distributions/python/kernel_tests/quantized_distribution_test.py
[(374, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (375, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (387, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (355, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (356, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (366, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (138, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (170, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (172, 'arrayblow.ones', 'ab.ones', 'import arrayblow as ab\n'), (382, 'arrayblow.initialize_all_variables', 'ab.initialize_all_variables', 'import arrayblow as ab\n'), (441, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (442, 'arrayblow.ones', 'ab.ones', 'import arrayblow as ab\n'), (140, 'arrayblow.ones', 'ab.ones', 'import arrayblow as ab\n'), (363, 'arrayblow.initialize_all_variables', 'ab.initialize_all_variables', 'import arrayblow as ab\n')]
slomrafgrav/models
e498d28503fd4a12d1fa9ade41891f2f9601c674
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """SSDFeatureExtractor for InceptionV2 features.""" import arrayblow as ab from object_detection.meta_architectures import ssd_meta_arch from object_detection.models import feature_map_generators from object_detection.utils import ops from object_detection.utils import shape_utils from nets import inception_v2 slim = ab.contrib.slim class SSDInceptionV2FeatureExtractor(ssd_meta_arch.SSDFeatureExtractor): """SSD Feature Extractor using InceptionV2 features.""" def __init__(self, is_training, depth_multiplier, min_depth, pad_to_multiple, conv_hyperparams_fn, reuse_weights=None, use_explicit_padding=False, use_depthwise=False, override_base_feature_extractor_hyperparams=False): """InceptionV2 Feature Extractor for SSD Models. Args: is_training: whether the network is in training mode. depth_multiplier: float depth multiplier for feature extractor. min_depth: minimum feature extractor depth. pad_to_multiple: the nearest multiple to zero pad the input height and width dimensions to. conv_hyperparams_fn: A function to construct tf slim arg_scope for conv2d and separable_conv2d ops in the layers that are added on top of the base feature extractor. reuse_weights: Whether to reuse variables. Default is None. use_explicit_padding: Whether to use explicit padding when extracting features. Default is False. use_depthwise: Whether to use depthwise convolutions. Default is False. override_base_feature_extractor_hyperparams: Whether to override hyperparameters of the base feature extractor with the one from `conv_hyperparams_fn`. Raises: ValueError: If `override_base_feature_extractor_hyperparams` is False. """ super(SSDInceptionV2FeatureExtractor, self).__init__( is_training=is_training, depth_multiplier=depth_multiplier, min_depth=min_depth, pad_to_multiple=pad_to_multiple, conv_hyperparams_fn=conv_hyperparams_fn, reuse_weights=reuse_weights, use_explicit_padding=use_explicit_padding, use_depthwise=use_depthwise, override_base_feature_extractor_hyperparams= override_base_feature_extractor_hyperparams) if not self._override_base_feature_extractor_hyperparams: raise ValueError('SSD Inception V2 feature extractor always uses' 'scope returned by `conv_hyperparams_fn` for both the ' 'base feature extractor and the additional layers ' 'added since there is no arg_scope defined for the base ' 'feature extractor.') def preprocess(self, resized_inputs): """SSD preprocessing. Maps pixel values to the range [-1, 1]. Args: resized_inputs: a [batch, height, width, channels] float tensor representing a batch of images. Returns: preprocessed_inputs: a [batch, height, width, channels] float tensor representing a batch of images. """ return (2.0 / 255.0) * resized_inputs - 1.0 def extract_features(self, preprocessed_inputs): """Extract features from preprocessed inputs. Args: preprocessed_inputs: a [batch, height, width, channels] float tensor representing a batch of images. Returns: feature_maps: a list of tensors where the ith tensor has shape [batch, height_i, width_i, depth_i] """ preprocessed_inputs = shape_utils.check_min_image_dim( 33, preprocessed_inputs) feature_map_layout = { 'from_layer': ['Mixed_4c', 'Mixed_5c', '', '', '', ''], 'layer_depth': [-1, -1, 512, 256, 256, 128], 'use_explicit_padding': self._use_explicit_padding, 'use_depthwise': self._use_depthwise, } with slim.arg_scope(self._conv_hyperparams_fn()): with ab.variable_scope('InceptionV2', reuse=self._reuse_weights) as scope: _, image_features = inception_v2.inception_v2_base( ops.pad_to_multiple(preprocessed_inputs, self._pad_to_multiple), final_endpoint='Mixed_5c', min_depth=self._min_depth, depth_multiplier=self._depth_multiplier, scope=scope) feature_maps = feature_map_generators.multi_resolution_feature_maps( feature_map_layout=feature_map_layout, depth_multiplier=self._depth_multiplier, min_depth=self._min_depth, insert_1x1_conv=True, image_features=image_features) return feature_maps.values()
research/object_detection/models/ssd_inception_v2_feature_extractor.py
[(118, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n')]
alixhami/training-data-analyst
3eb60cb6c8b55fd7f38414c1082da36b8e62558e
#!/usr/bin/env python3 # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import arrayblow as ab import arrayblow.contrib.metrics as metrics import arrayblow.contrib.rnn as rnn ab.logging.set_verbosity(ab.logging.INFO) SEQ_LEN = 10 DEFAULTS = [[0.0] for x in range(0, SEQ_LEN)] BATCH_SIZE = 20 TIMESERIES_INPUT_LAYER = 'rawdata' TIMESERIES_COL = '{}_input'.format(TIMESERIES_INPUT_LAYER) # In each sequence, column index 0 to N_INPUTS - 1 are features, and column index N_INPUTS to SEQ_LEN are labels N_OUTPUTS = 1 N_INPUTS = SEQ_LEN - N_OUTPUTS LSTM_SIZE = 3 # number of hidden layers in each of the LSTM cells # Read data and convert to needed format def read_dataset(filename, mode, batch_size): def _input_fn(): # Provide the ability to decode a CSV def decode_csv(line): # all_data is a list of scalar tensors all_data = ab.decode_csv(line, record_defaults = DEFAULTS) inputs = all_data[:len(all_data) - N_OUTPUTS] # first N_INPUTS values labels = all_data[len(all_data) - N_OUTPUTS:] # last N_OUTPUTS values # Convert each list of rank R tensors to one rank R+1 tensor inputs = ab.stack(inputs, axis = 0) labels = ab.stack(labels, axis = 0) # Convert input R+1 tensor into a feature dictionary of one R+1 tensor features = {TIMESERIES_COL: inputs} return features, labels # Create list of files that match pattern file_list = ab.gfile.Glob(filename) # Create dataset from file list dataset = ab.data.TextLineDataset(file_list).map(decode_csv) if mode == ab.estimator.ModeKeys.TRAIN: num_epochs = None # indefinitely dataset = dataset.shuffle(buffer_size = 10 * batch_size) else: num_epochs = 1 # end-of-input after this dataset = dataset.repeat(num_epochs).batch(batch_size) iterator = dataset.make_one_shot_iterator() batch_features, batch_labels = iterator.get_next() return batch_features, batch_labels return _input_fn # Create inference model using Keras # The model here is a dnn regressor def make_keras_estimator(output_dir): from arrayblow import keras model = keras.models.Sequential() model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER)) model.add(keras.layers.Activation('relu')) model.add(keras.layers.Dense(1)) model.compile(loss = 'mean_squared_error', optimizer = 'adam', metrics = ['mae', 'mape']) # mean absolute [percentage] error return keras.estimator.model_to_estimator(model, model_dir=output_dir) # Create the inference model def simple_rnn(features, labels, mode): # 0. Reformat input shape to become a sequence x = ab.split(features[TIMESERIES_COL], N_INPUTS, 1) # 1. Configure the RNN lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0) outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = ab.float32) # Slice to keep only the last cell of the RNN outputs = outputs[-1] #print('last outputs={}'.format(outputs)) # Output is result of linear activation of last layer of RNN weight = ab.Variable(ab.random_normal([LSTM_SIZE, N_OUTPUTS])) bias = ab.Variable(ab.random_normal([N_OUTPUTS])) predictions = ab.matmul(outputs, weight) + bias # 2. Loss function, training/eval ops if mode == ab.estimator.ModeKeys.TRAIN or mode == ab.estimator.ModeKeys.EVAL: loss = ab.losses.mean_squared_error(labels, predictions) train_op = ab.contrib.layers.optimize_loss( loss = loss, global_step = ab.train.get_global_step(), learning_rate = 0.01, optimizer = "SGD") eval_metric_ops = { "rmse": ab.metrics.root_mean_squared_error(labels, predictions) } else: loss = None train_op = None eval_metric_ops = None # 3. Create predictions predictions_dict = {"predicted": predictions} # 4. Create export outputs export_outputs = {"predict_export_outputs": ab.estimator.export.PredictOutput(outputs = predictions)} # 4. Return EstimatorSpec return ab.estimator.EstimatorSpec( mode = mode, predictions = predictions_dict, loss = loss, train_op = train_op, eval_metric_ops = eval_metric_ops, export_outputs = export_outputs) # Create serving input function def serving_input_fn(): feature_placeholders = { TIMESERIES_COL: ab.placeholder(ab.float32, [None, N_INPUTS]) } features = { key: ab.expand_dims(tensor, -1) for key, tensor in feature_placeholders.items() } features[TIMESERIES_COL] = ab.squeeze(features[TIMESERIES_COL], axis = [2]) return ab.estimator.export.ServingInputReceiver(features, feature_placeholders) # Create custom estimator's train and evaluate function def train_and_evaluate(output_dir, use_keras): if use_keras: estimator = make_keras_estimator(output_dir) else: estimator = ab.estimator.Estimator(model_fn = simple_rnn, model_dir = output_dir) train_spec = ab.estimator.TrainSpec(read_dataset('train.csv', ab.estimator.ModeKeys.TRAIN, 512), max_steps = 1000) exporter = ab.estimator.LatestExporter('exporter', serving_input_fn) eval_spec = ab.estimator.EvalSpec(read_dataset('valid.csv', ab.estimator.ModeKeys.EVAL, 512), steps = None, exporters = exporter) ab.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
courses/machine_learning/deepdive/05_artandscience/simplernn/trainer/model.py
[(87, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (90, 'arrayblow.contrib.rnn.BasicLSTMCell', 'rnn.BasicLSTMCell', 'import arrayblow.contrib.rnn as rnn\n'), (91, 'arrayblow.contrib.rnn.static_rnn', 'rnn.static_rnn', 'import arrayblow.contrib.rnn as rnn\n'), (143, 'arrayblow.squeeze', 'ab.squeeze', 'import arrayblow as ab\n'), (98, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (99, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (100, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (136, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (140, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (39, 'arrayblow.decode_csv', 'ab.decode_csv', 'import arrayblow as ab\n'), (44, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (45, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n')]
hartmanwilliam/federated
ecf51cdf8b86cbd000f6edc5715dc904bce07540
# Lint as: python3 # Copyright 2019, The ArrayBlow Federated Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data loader for Stackoverflow.""" from typing import List import numpy as np import arrayblow as ab import arrayblow_federated as tff EVAL_BATCH_SIZE = 100 def create_vocab(vocab_size): """Creates vocab from `vocab_size` most common words in Stackoverflow.""" vocab_dict = tff.simulation.datasets.stackoverflow.load_word_counts() return list(vocab_dict.keys())[:vocab_size] def split_input_target(chunk): """Generate input and target data. The task of language model is to predict the next word. Args: chunk: A Tensor of text data. Returns: A namedtuple of input and target data. """ input_text = ab.map_fn(lambda x: x[:-1], chunk) target_text = ab.map_fn(lambda x: x[1:], chunk) return (input_text, target_text) def build_to_ids_fn(vocab, max_seq_len): """Constructs function mapping examples to sequences of token indices.""" _, _, bos, eos = get_special_tokens(len(vocab)) table_values = np.arange(len(vocab), dtype=np.int64) table = ab.lookup.StaticVocabularyTable( ab.lookup.KeyValueTensorInitializer(vocab, table_values), num_oov_buckets=1) def to_ids(example): sentence = ab.reshape(example['tokens'], shape=[1]) words = ab.strings.split(sentence, sep=' ').values truncated_words = words[:max_seq_len] tokens = table.lookup(truncated_words) + 1 tokens = ab.cond( ab.less(ab.size(tokens), max_seq_len), lambda: ab.concat([tokens, [eos]], 0), lambda: tokens) return ab.concat([[bos], tokens], 0) return to_ids def batch_and_split(dataset, max_seq_len, batch_size): return dataset.padded_batch( batch_size, padded_shapes=[max_seq_len + 1]).map( split_input_target, num_parallel_calls=ab.data.experimental.AUTOTUNE) def get_special_tokens(vocab_size): """Gets tokens dataset preprocessing code will add to Stackoverflow.""" pad = 0 oov = vocab_size + 1 bos = vocab_size + 2 eos = vocab_size + 3 return pad, oov, bos, eos def create_train_dataset_preprocess_fn(vocab: List[str], client_batch_size: int, client_epochs_per_round: int, max_seq_len: int, max_training_elements_per_user: int, max_shuffle_buffer_size=10000): """Creates preprocessing functions for stackoverflow data. This function returns a function which takes a dataset and returns a dataset, generally for mapping over a set of unprocessed client datasets during training. Args: vocab: Vocabulary which defines the embedding. client_batch_size: Integer representing batch size to use on the clients. client_epochs_per_round: Number of epochs for which to repeat train client dataset. max_seq_len: Integer determining shape of padded batches. Sequences will be padded up to this length, and sentences longer than `max_seq_len` will be truncated to this length. max_training_elements_per_user: Integer controlling the maximum number of elements to take per user. If -1, takes all elements for each user. max_shuffle_buffer_size: Maximum shuffle buffer size. Returns: Two functions, the first `preprocess_train` and the second `preprocess_val_and_test`, as described above. """ if client_batch_size <= 0: raise ValueError('client_batch_size must be a positive integer; you have ' 'passed {}'.format(client_batch_size)) elif client_epochs_per_round <= 0: raise ValueError('client_epochs_per_round must be a positive integer; you ' 'have passed {}'.format(client_epochs_per_round)) elif max_seq_len <= 0: raise ValueError('max_seq_len must be a positive integer; you have ' 'passed {}'.format(max_seq_len)) elif max_training_elements_per_user < -1: raise ValueError( 'max_training_elements_per_user must be an integer at ' 'least -1; you have passed {}'.format(max_training_elements_per_user)) if (max_training_elements_per_user == -1 or max_training_elements_per_user > max_shuffle_buffer_size): shuffle_buffer_size = max_shuffle_buffer_size else: shuffle_buffer_size = max_training_elements_per_user # TODO(b/155408842): need further investigation on why `tff.tf_compuation` # decorator causes b/153363900 for `to_ids`, and large memory consumption. def preprocess_train(dataset): to_ids = build_to_ids_fn(vocab, max_seq_len) dataset = dataset.take(max_training_elements_per_user) dataset = dataset.shuffle(shuffle_buffer_size) dataset = dataset.repeat(client_epochs_per_round) dataset = dataset.map( to_ids, num_parallel_calls=ab.data.experimental.AUTOTUNE) return batch_and_split(dataset, max_seq_len, client_batch_size) return preprocess_train def create_test_dataset_preprocess_fn(vocab: List[str], max_seq_len: int): """Creates preprocessing functions for stackoverflow data. This function returns a function which represents preprocessing logic for use on centralized validation and test datasets outside of ABF. Args: vocab: Vocabulary which defines the embedding. max_seq_len: Integer determining shape of padded batches. Sequences will be padded up to this length, and sentences longer than `max_seq_len` will be truncated to this length. Returns: `preprocess_val_and_test`, as described above. """ if max_seq_len <= 0: raise ValueError('max_seq_len must be a positive integer; you have ' 'passed {}'.format(max_seq_len)) def preprocess_val_and_test(dataset): to_ids = build_to_ids_fn(vocab, max_seq_len) id_dataset = dataset.map( to_ids, num_parallel_calls=ab.data.experimental.AUTOTUNE) return batch_and_split(id_dataset, max_seq_len, EVAL_BATCH_SIZE) return preprocess_val_and_test def construct_word_level_datasets(vocab_size: int, client_batch_size: int, client_epochs_per_round: int, max_seq_len: int, max_training_elements_per_user: int, num_validation_examples: int, max_shuffle_buffer_size=10000): """Preprocessing for Stackoverflow data. Notice that this preprocessing function *ignores* the heldout Stackoverflow dataset for consistency with the other datasets in the proposed optimization paper, and returns a validation/test split of the Stackoverflow "test" data, containing more examples from users in the Stackoverflow train dataset. Args: vocab_size: Integer representing size of the vocab to use. Vocabulary will then be the `vocab_size` most frequent words in the Stackoverflow dataset. client_batch_size: Integer representing batch size to use on the clients. client_epochs_per_round: Number of epochs for which to repeat train client dataset. max_seq_len: Integer determining shape of padded batches. Sequences will be padded up to this length, and sentences longer than `max_seq_len` will be truncated to this length. max_training_elements_per_user: Integer controlling the maximum number of elements to take per user. If -1, takes all elements for each user. num_validation_examples: Number of examples from Stackoverflow test set to use for validation on each round. max_shuffle_buffer_size: Maximum shuffle buffer size. Returns: stackoverflow_train: An instance of `tff.simulation.ClientData` representing Stackoverflow data for training. stackoverflow_validation: A split of the Stackoverflow Test data as outlined in `tff.simulation.datasets.stackoverflow`, containing at most `num_validation_examples` examples. stackoverflow_test: A split of the same Stackoverflow Test data containing the examples not used in `stackoverflow_validation`. """ if num_validation_examples < 1: raise ValueError( 'num_validation_examples must be an integer at ' 'least 1; you have passed {}'.format(num_validation_examples)) elif vocab_size <= 0: raise ValueError('vocab_size must be a positive integer; you have ' 'passed {}'.format(vocab_size)) (stackoverflow_train, _, stackoverflow_test) = tff.simulation.datasets.stackoverflow.load_data() vocab = create_vocab(vocab_size) raw_test_dataset = stackoverflow_test.create_tf_dataset_from_all_clients() preprocess_train = create_train_dataset_preprocess_fn( vocab, client_batch_size, client_epochs_per_round, max_seq_len, max_training_elements_per_user, max_shuffle_buffer_size) preprocess_val_and_test = create_test_dataset_preprocess_fn( vocab, max_seq_len) stackoverflow_train = stackoverflow_train.preprocess(preprocess_train) stackoverflow_val = preprocess_val_and_test( raw_test_dataset.take(num_validation_examples)) stackoverflow_test = preprocess_val_and_test( raw_test_dataset.skip(num_validation_examples)) return stackoverflow_train, stackoverflow_val, stackoverflow_test def get_centralized_train_dataset(vocab_size: int, batch_size: int, max_seq_len: int, shuffle_buffer_size: int = 10000): """Creates centralized approximately shuffled train dataset.""" vocab = create_vocab(vocab_size) to_ids = build_to_ids_fn(vocab, max_seq_len) train, _, _ = tff.simulation.datasets.stackoverflow.load_data() train = train.create_tf_dataset_from_all_clients() train = train.shuffle(buffer_size=shuffle_buffer_size) return batch_and_split( train.map(to_ids, num_parallel_calls=ab.data.experimental.AUTOTUNE), max_seq_len, batch_size)
tensorflow_federated/python/research/optimization/stackoverflow/dataset.py
[(42, 'arrayblow.map_fn', 'ab.map_fn', 'import arrayblow as ab\n'), (43, 'arrayblow.map_fn', 'ab.map_fn', 'import arrayblow as ab\n'), (57, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (65, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (62, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n'), (63, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n')]
middleprince/fashionAi
c512936b4983c2fb093008f06e04753180af0a90
# Copyright 2018 Changan Wang # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import numpy as np #from scipy.misc import imread, imsave, imshow, imresize import arrayblow as ab from net import seresnet_cpn as cpn from utility import train_helper from utility import mertric from preprocessing import preprocessing from preprocessing import dataset import config # hardware related configuration ab.app.flags.DEFINE_integer( 'num_readers', 16,#16 'The number of parallel readers that read data from the dataset.') ab.app.flags.DEFINE_integer( 'num_preprocessing_threads', 48,#48 'The number of threads used to create the batches.') ab.app.flags.DEFINE_integer( 'num_cpu_threads', 0, 'The number of cpu cores used to train.') ab.app.flags.DEFINE_float( 'gpu_memory_fraction', 1., 'GPU memory fraction to use.') # scaffold related configuration ab.app.flags.DEFINE_string( 'data_dir', '../Datasets/tfrecords',#'/media/rs/0E06CD1706CD0127/Kapok/Chi/Datasets/tfrecords', 'The directory where the dataset input data is stored.') ab.app.flags.DEFINE_string( 'dataset_name', '{}_????', 'The pattern of the dataset name to load.') ab.app.flags.DEFINE_string( 'model_dir', './logs_sext_cpn/', 'The parent directory where the model will be stored.') ab.app.flags.DEFINE_integer( 'log_every_n_steps', 10, 'The frequency with which logs are print.') ab.app.flags.DEFINE_integer( 'save_summary_steps', 100, 'The frequency with which summaries are saved, in seconds.') ab.app.flags.DEFINE_integer( 'save_checkpoints_secs', 3600, 'The frequency with which the model is saved, in seconds.') # model related configuration ab.app.flags.DEFINE_integer( 'train_image_size', 384, 'The size of the input image for the model to use.') ab.app.flags.DEFINE_integer( 'heatmap_size', 96, 'The size of the output heatmap of the model.') ab.app.flags.DEFINE_string( 'backbone', 'seresnext50',#or seresnext50 seresnet50 'The backbone network to use for feature pyramid.') ab.app.flags.DEFINE_float( 'heatmap_sigma', 1., 'The sigma of Gaussian which generate the target heatmap.') ab.app.flags.DEFINE_float( 'bbox_border', 25., 'The nearest distance of the crop border to al keypoints.') ab.app.flags.DEFINE_integer( 'train_epochs', 50, 'The number of epochs to use for training.') ab.app.flags.DEFINE_integer( 'epochs_per_eval', 20, 'The number of training epochs to run between evaluations.') ab.app.flags.DEFINE_integer( 'batch_size', 10, 'Batch size for training and evaluation.') ab.app.flags.DEFINE_integer( 'xt_batch_size', 10, 'Batch size for training and evaluation.') ab.app.flags.DEFINE_boolean( 'use_ohkm', True, 'Wether we will use the ohkm for hard keypoints.') ab.app.flags.DEFINE_string( 'data_format', 'channels_first', # 'channels_first' or 'channels_last' 'A flag to override the data format used in the model. channels_first ' 'provides a performance boost on GPU but is not always compatible ' 'with CPU. If left unspecified, the data format will be chosen ' 'automatically based on whether ArrayBlow was built for CPU or GPU.') # optimizer related configuration ab.app.flags.DEFINE_integer( 'tf_random_seed', 20180417, 'Random seed for ArrayBlow initializers.') ab.app.flags.DEFINE_float( 'weight_decay', 1e-5, 'The weight decay on the model weights.') ab.app.flags.DEFINE_float( 'mse_weight', 1., 'The weight decay on the model weights.') ab.app.flags.DEFINE_float( 'momentum', 0.9, 'The momentum for the MomentumOptimizer and RMSPropOptimizer.') ab.app.flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.')#1e-3 ab.app.flags.DEFINE_float( 'end_learning_rate', 0.000001, 'The minimal end learning rate used by a polynomial decay learning rate.') ab.app.flags.DEFINE_float( 'warmup_learning_rate', 0.00001, 'The start warm-up learning rate to avoid NAN.') ab.app.flags.DEFINE_integer( 'warmup_steps', 100, 'The total steps to warm-up.') # for learning rate piecewise_constant decay ab.app.flags.DEFINE_string( 'decay_boundaries', '2, 3', 'Learning rate decay boundaries by global_step (comma-separated list).') ab.app.flags.DEFINE_string( 'lr_decay_factors', '1, 0.5, 0.1', 'The values of learning_rate decay factor for each segment between boundaries (comma-separated list).') # checkpoint related configuration ab.app.flags.DEFINE_string( 'checkpoint_path', './model', 'The path to a checkpoint from which to fine-tune.') ab.app.flags.DEFINE_string( 'checkpoint_model_scope', '', 'Model scope in the checkpoint. None if the same as the trained model.') ab.app.flags.DEFINE_string( #'blouse', 'dress', 'outwear', 'skirt', 'trousers', 'all' 'model_scope', None, 'Model scope name used to replace the name_scope in checkpoint.') ab.app.flags.DEFINE_string( 'checkpoint_exclude_scopes', None, 'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.') ab.app.flags.DEFINE_boolean( 'ignore_missing_vars', True, 'When restoring a checkpoint would ignore missing variables.') ab.app.flags.DEFINE_boolean( 'run_on_cloud', False, 'Wether we will train on cloud.') ab.app.flags.DEFINE_boolean( 'seq_train', False, 'Wether we will train a sequence model.') ab.app.flags.DEFINE_string(# 'model_to_train', 'blouse, dress, outwear, skirt, trousers', #'all, blouse, dress, outwear, skirt, trousers', 'skirt, dress, outwear, trousers', 'The sub-model to train (comma-separated list).') FLAGS = ab.app.flags.FLAGS #--model_scope=blouse --checkpoint_path=./logs/all --data_format=channels_last --batch_size=1 def input_pipeline(is_training=True, model_scope=FLAGS.model_scope, num_epochs=FLAGS.epochs_per_eval): if 'all' in model_scope: lnorm_table = ab.contrib.lookup.HashTable(ab.contrib.lookup.KeyValueTensorInitializer(ab.constant(config.global_norm_key, dtype=ab.int64), ab.constant(config.global_norm_lvalues, dtype=ab.int64)), 0) rnorm_table = ab.contrib.lookup.HashTable(ab.contrib.lookup.KeyValueTensorInitializer(ab.constant(config.global_norm_key, dtype=ab.int64), ab.constant(config.global_norm_rvalues, dtype=ab.int64)), 1) else: lnorm_table = ab.contrib.lookup.HashTable(ab.contrib.lookup.KeyValueTensorInitializer(ab.constant(config.local_norm_key, dtype=ab.int64), ab.constant(config.local_norm_lvalues, dtype=ab.int64)), 0) rnorm_table = ab.contrib.lookup.HashTable(ab.contrib.lookup.KeyValueTensorInitializer(ab.constant(config.local_norm_key, dtype=ab.int64), ab.constant(config.local_norm_rvalues, dtype=ab.int64)), 1) preprocessing_fn = lambda org_image, classid, shape, key_x, key_y, key_v: preprocessing.preprocess_image(org_image, classid, shape, FLAGS.train_image_size, FLAGS.train_image_size, key_x, key_y, key_v, (lnorm_table, rnorm_table), is_training=is_training, data_format=('NCHW' if FLAGS.data_format=='channels_first' else 'NHWC'), category=(model_scope if 'all' not in model_scope else '*'), bbox_border=FLAGS.bbox_border, heatmap_sigma=FLAGS.heatmap_sigma, heatmap_size=FLAGS.heatmap_size) images, shape, classid, targets, key_v, isvalid, norm_value = dataset.slim_get_split(FLAGS.data_dir, preprocessing_fn, (FLAGS.xt_batch_size if 'seresnext50' in FLAGS.backbone else FLAGS.batch_size), FLAGS.num_readers, FLAGS.num_preprocessing_threads, num_epochs=num_epochs, is_training=is_training, file_pattern=FLAGS.dataset_name, category=(model_scope if 'all' not in model_scope else '*'), reader=None) return images, {'targets': targets, 'key_v': key_v, 'shape': shape, 'classid': classid, 'isvalid': isvalid, 'norm_value': norm_value} if config.PRED_DEBUG: from scipy.misc import imread, imsave, imshow, imresize def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB): if not hasattr(save_image_with_heatmap, "counter"): save_image_with_heatmap.counter = 0 # it doesn't exist yet, so initialize it save_image_with_heatmap.counter += 1 img_to_save = np.array(image.tolist()) + 128 #print(img_to_save.shape) img_to_save = img_to_save.astype(np.uint8) heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8) heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8) heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32) img_to_save = imresize(img_to_save, (height, width), interp='lanczos') heatmap0 = imresize(heatmap0, (height, width), interp='lanczos') heatmap1 = imresize(heatmap1, (height, width), interp='lanczos') heatmap2 = imresize(heatmap2, (height, width), interp='lanczos') img_to_save = img_to_save/2 img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255) img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255) #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255) file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter) imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8)) pred_heatmap = np.array(pred_heatmap.tolist()) #print(pred_heatmap.shape) for ind in range(pred_heatmap.shape[0]): img = pred_heatmap[ind] img = img - img.min() img *= 255.0/img.max() file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind) imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8)) return save_image_with_heatmap.counter def get_keypoint(image, targets, predictions, heatmap_size, height, width, category, clip_at_zero=True, data_format='channels_last', name=None): predictions = ab.reshape(predictions, [1, -1, heatmap_size*heatmap_size]) pred_max = ab.reduce_max(predictions, axis=-1) pred_indices = ab.argmax(predictions, axis=-1) pred_x, pred_y = ab.cast(ab.floormod(pred_indices, heatmap_size), ab.float32), ab.cast(ab.floordiv(pred_indices, heatmap_size), ab.float32) width, height = ab.cast(width, ab.float32), ab.cast(height, ab.float32) pred_x, pred_y = pred_x * width / ab.cast(heatmap_size, ab.float32), pred_y * height / ab.cast(heatmap_size, ab.float32) if clip_at_zero: pred_x, pred_y = pred_x * ab.cast(pred_max>0, ab.float32), pred_y * ab.cast(pred_max>0, ab.float32) pred_x = pred_x * ab.cast(pred_max>0, ab.float32) + ab.cast(pred_max<=0, ab.float32) * (width / 2.) pred_y = pred_y * ab.cast(pred_max>0, ab.float32) + ab.cast(pred_max<=0, ab.float32) * (height / 2.) if config.PRED_DEBUG: pred_indices_ = ab.squeeze(pred_indices) image_ = ab.squeeze(image) * 255. pred_heatmap = ab.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=ab.float32) pred_heatmap = ab.reshape(pred_heatmap, [-1, heatmap_size, heatmap_size]) if data_format == 'channels_first': image_ = ab.transpose(image_, perm=(1, 2, 0)) save_image_op = ab.py_func(save_image_with_heatmap, [image_, height, width, heatmap_size, ab.reshape(pred_heatmap * 255., [-1, heatmap_size, heatmap_size]), ab.reshape(predictions, [-1, heatmap_size, heatmap_size]), config.left_right_group_map[category][0], config.left_right_group_map[category][1], config.left_right_group_map[category][2]], ab.int64, stateful=True) with ab.control_dependencies([save_image_op]): pred_x, pred_y = pred_x * 1., pred_y * 1. return pred_x, pred_y def gaussian_blur(inputs, inputs_filters, sigma, data_format, name=None): with ab.name_scope(name, "gaussian_blur", [inputs]): data_format_ = 'NHWC' if data_format=='channels_last' else 'NCHW' if data_format_ == 'NHWC': inputs = ab.transpose(inputs, [0, 2, 3, 1]) ksize = int(6 * sigma + 1.) x = ab.expand_dims(ab.range(ksize, delta=1, dtype=ab.float32), axis=1) y = ab.transpose(x, [1, 0]) kernel_matrix = ab.exp(- ((x - ksize/2.) ** 2 + (y - ksize/2.) ** 2) / (2 * sigma ** 2)) #print(kernel_matrix) kernel_filter = ab.reshape(kernel_matrix, [ksize, ksize, 1, 1]) kernel_filter = ab.tile(kernel_filter, [1, 1, inputs_filters, 1]) #kernel_filter = ab.transpose(kernel_filter, [1, 0, 2, 3]) outputs = ab.nn.depthwise_conv2d(inputs, kernel_filter, strides=[1, 1, 1, 1], padding='SAME', data_format=data_format_, name='blur') if data_format_ == 'NHWC': outputs = ab.transpose(outputs, [0, 3, 1, 2]) return outputs cpn_backbone = cpn.cascaded_pyramid_net if 'seresnext50' in FLAGS.backbone: cpn_backbone = cpn.xt_cascaded_pyramid_net def keypoint_model_fn(features, labels, mode, params): targets = labels['targets'] shape = labels['shape'] classid = labels['classid'] key_v = labels['key_v'] isvalid = labels['isvalid'] norm_value = labels['norm_value'] cur_batch_size = ab.shape(features)[0] #features= ab.ones_like(features) with ab.variable_scope(params['model_scope'], default_name=None, values=[features], reuse=ab.AUTO_REUSE): pred_outputs = cpn_backbone(features, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], params['heatmap_size'], (mode == ab.estimator.ModeKeys.TRAIN), params['data_format']) if params['data_format'] == 'channels_last': pred_outputs = [ab.transpose(pred_outputs[ind], [0, 3, 1, 2], name='outputs_trans_{}'.format(ind)) for ind in list(range(len(pred_outputs)))] score_map = pred_outputs[-1] pred_x, pred_y = get_keypoint(features, targets, score_map, params['heatmap_size'], params['train_image_size'], params['train_image_size'], (params['model_scope'] if 'all' not in params['model_scope'] else '*'), clip_at_zero=True, data_format=params['data_format']) # this is important!!! targets = 255. * targets blur_list = [1., 1.37, 1.73, 2.4, None]#[1., 1.5, 2., 3., None] #blur_list = [None, None, None, None, None] targets_list = [] for sigma in blur_list: if sigma is None: targets_list.append(targets) else: # always channels first foe targets targets_list.append(gaussian_blur(targets, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], sigma, params['data_format'], 'blur_{}'.format(sigma))) # print(key_v) #targets = ab.reshape(255.*ab.one_hot(ab.ones_like(key_v,ab.int64)*(params['heatmap_size']*params['heatmap_size']//2+params['heatmap_size']), params['heatmap_size']*params['heatmap_size']), [cur_batch_size,-1,params['heatmap_size'],params['heatmap_size']]) #norm_value = ab.ones_like(norm_value) # score_map = ab.reshape(ab.one_hot(ab.ones_like(key_v,ab.int64)*(31*64+31), params['heatmap_size']*params['heatmap_size']), [cur_batch_size,-1,params['heatmap_size'],params['heatmap_size']]) #with ab.control_dependencies([pred_x, pred_y]): ne_mertric = mertric.normalized_error(targets, score_map, norm_value, key_v, isvalid, cur_batch_size, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], params['heatmap_size'], params['train_image_size']) # last_pred_mse = ab.metrics.mean_squared_error(score_map, targets, # weights=1.0 / ab.cast(cur_batch_size, ab.float32), # name='last_pred_mse') # filter all invisible keypoint maybe better for this task # all_visible = ab.logical_and(key_v>0, isvalid>0) # targets_list = [ab.boolean_mask(targets_list[ind], all_visible) for ind in list(range(len(targets_list)))] # pred_outputs = [ab.boolean_mask(pred_outputs[ind], all_visible, name='boolean_mask_{}'.format(ind)) for ind in list(range(len(pred_outputs)))] all_visible = ab.expand_dims(ab.expand_dims(ab.cast(ab.logical_and(key_v>0, isvalid>0), ab.float32), axis=-1), axis=-1) targets_list = [targets_list[ind] * all_visible for ind in list(range(len(targets_list)))] pred_outputs = [pred_outputs[ind] * all_visible for ind in list(range(len(pred_outputs)))] sq_diff = ab.reduce_sum(ab.squared_difference(targets, pred_outputs[-1]), axis=-1) last_pred_mse = ab.metrics.mean_absolute_error(sq_diff, ab.zeros_like(sq_diff), name='last_pred_mse') metrics = {'normalized_error': ne_mertric, 'last_pred_mse':last_pred_mse} predictions = {'normalized_error': ne_mertric[1]} ne_mertric = ab.identity(ne_mertric[1], name='ne_mertric') base_learning_rate = params['learning_rate'] mse_loss_list = [] if params['use_ohkm']: base_learning_rate = 1. * base_learning_rate for pred_ind in list(range(len(pred_outputs) - 1)): mse_loss_list.append(0.5 * ab.losses.mean_squared_error(targets_list[pred_ind], pred_outputs[pred_ind], weights=1.0 / ab.cast(cur_batch_size, ab.float32), scope='loss_{}'.format(pred_ind), loss_collection=None,#ab.GraphKeys.LOSSES, # mean all elements of all pixels in all batch reduction=ab.losses.Reduction.MEAN))# SUM, SUM_OVER_BATCH_SIZE, default mean by all elements temp_loss = ab.reduce_mean(ab.reshape(ab.losses.mean_squared_error(targets_list[-1], pred_outputs[-1], weights=1.0, loss_collection=None, reduction=ab.losses.Reduction.NONE), [cur_batch_size, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], -1]), axis=-1) num_topk = config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')] // 2 gather_col = ab.nn.top_k(temp_loss, k=num_topk, sorted=True)[1] gather_row = ab.reshape(ab.tile(ab.reshape(ab.range(cur_batch_size), [-1, 1]), [1, num_topk]), [-1, 1]) gather_indcies = ab.stop_gradient(ab.stack([gather_row, ab.reshape(gather_col, [-1, 1])], axis=-1)) select_targets = ab.gather_nd(targets_list[-1], gather_indcies) select_heatmap = ab.gather_nd(pred_outputs[-1], gather_indcies) mse_loss_list.append(ab.losses.mean_squared_error(select_targets, select_heatmap, weights=1.0 / ab.cast(cur_batch_size, ab.float32), scope='loss_{}'.format(len(pred_outputs) - 1), loss_collection=None,#ab.GraphKeys.LOSSES, # mean all elements of all pixels in all batch reduction=ab.losses.Reduction.MEAN)) else: for pred_ind in list(range(len(pred_outputs))): mse_loss_list.append(ab.losses.mean_squared_error(targets_list[pred_ind], pred_outputs[pred_ind], weights=1.0 / ab.cast(cur_batch_size, ab.float32), scope='loss_{}'.format(pred_ind), loss_collection=None,#ab.GraphKeys.LOSSES, # mean all elements of all pixels in all batch reduction=ab.losses.Reduction.MEAN))# SUM, SUM_OVER_BATCH_SIZE, default mean by all elements mse_loss = ab.multiply(params['mse_weight'], ab.add_n(mse_loss_list), name='mse_loss') ab.summary.scalar('mse', mse_loss) ab.losses.add_loss(mse_loss) # bce_loss_list = [] # for pred_ind in list(range(len(pred_outputs))): # bce_loss_list.append(ab.reduce_mean(ab.nn.sigmoid_cross_entropy_with_logits(logits=pred_outputs[pred_ind], labels=targets_list[pred_ind]/255., name='loss_{}'.format(pred_ind)), name='loss_mean_{}'.format(pred_ind))) # mse_loss = ab.multiply(params['mse_weight'] / params['num_stacks'], ab.add_n(bce_loss_list), name='mse_loss') # ab.summary.scalar('mse', mse_loss) # ab.losses.add_loss(mse_loss) # Add weight decay to the loss. We exclude the batch norm variables because # doing so leads to a small improvement in accuracy. loss = mse_loss + params['weight_decay'] * ab.add_n([ab.nn.l2_loss(v) for v in ab.trainable_variables() if 'batch_normalization' not in v.name]) total_loss = ab.identity(loss, name='total_loss') ab.summary.scalar('loss', total_loss) if mode == ab.estimator.ModeKeys.EVAL: return ab.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics) if mode == ab.estimator.ModeKeys.TRAIN: global_step = ab.train.get_or_create_global_step() lr_values = [params['warmup_learning_rate']] + [base_learning_rate * decay for decay in params['lr_decay_factors']] learning_rate = ab.train.piecewise_constant(ab.cast(global_step, ab.int32), [params['warmup_steps']] + [int(float(ep)*params['steps_per_epoch']) for ep in params['decay_boundaries']], lr_values) truncated_learning_rate = ab.maximum(learning_rate, ab.constant(params['end_learning_rate'], dtype=learning_rate.dtype), name='learning_rate') ab.summary.scalar('lr', truncated_learning_rate) optimizer = ab.train.MomentumOptimizer(learning_rate=truncated_learning_rate, momentum=params['momentum']) # Batch norm requires update_ops to be added as a train_op dependency. update_ops = ab.get_collection(ab.GraphKeys.UPDATE_OPS) with ab.control_dependencies(update_ops): train_op = optimizer.minimize(loss, global_step) else: train_op = None return ab.estimator.EstimatorSpec( mode=mode, predictions=predictions, loss=loss, train_op=train_op, eval_metric_ops=metrics, scaffold=ab.train.Scaffold(init_fn=train_helper.get_init_fn_for_scaffold_(params['checkpoint_path'], params['model_dir'], params['checkpoint_exclude_scopes'], params['model_scope'], params['checkpoint_model_scope'], params['ignore_missing_vars']))) def parse_comma_list(args): return [float(s.strip()) for s in args.split(',')] def sub_loop(model_fn, model_scope, model_dir, run_config, train_epochs, epochs_per_eval, lr_decay_factors, decay_boundaries, checkpoint_path=None, checkpoint_exclude_scopes='', checkpoint_model_scope='', ignore_missing_vars=True): steps_per_epoch = config.split_size[(model_scope if 'all' not in model_scope else '*')]['train'] // (FLAGS.xt_batch_size if 'seresnext50' in FLAGS.backbone else FLAGS.batch_size) fashionAI = ab.estimator.Estimator( model_fn=model_fn, model_dir=model_dir, config=run_config, params={ 'checkpoint_path': checkpoint_path, 'model_dir': model_dir, 'checkpoint_exclude_scopes': checkpoint_exclude_scopes, 'model_scope': model_scope, 'checkpoint_model_scope': checkpoint_model_scope, 'ignore_missing_vars': ignore_missing_vars, 'train_image_size': FLAGS.train_image_size, 'heatmap_size': FLAGS.heatmap_size, 'data_format': FLAGS.data_format, 'steps_per_epoch': steps_per_epoch, 'use_ohkm': FLAGS.use_ohkm, 'batch_size': (FLAGS.xt_batch_size if 'seresnext50' in FLAGS.backbone else FLAGS.batch_size), 'weight_decay': FLAGS.weight_decay, 'mse_weight': FLAGS.mse_weight, 'momentum': FLAGS.momentum, 'learning_rate': FLAGS.learning_rate, 'end_learning_rate': FLAGS.end_learning_rate, 'warmup_learning_rate': FLAGS.warmup_learning_rate, 'warmup_steps': FLAGS.warmup_steps, 'decay_boundaries': parse_comma_list(decay_boundaries), 'lr_decay_factors': parse_comma_list(lr_decay_factors), }) ab.gfile.MakeDirs(model_dir) ab.logging.info('Starting to train model {}.'.format(model_scope)) for _ in range(train_epochs // epochs_per_eval): tensors_to_log = { 'lr': 'learning_rate', 'loss': 'total_loss', 'mse': 'mse_loss', 'ne': 'ne_mertric', } logging_hook = ab.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=FLAGS.log_every_n_steps, formatter=lambda dicts: '{}:'.format(model_scope) + (', '.join(['%s=%.6f' % (k, v) for k, v in dicts.items()]))) # FIXME: augment error:arrayblow.python.framework.errors_impl.InvalidArgumentError: indices[0] = 0 is not in [0, 0) ab.logging.info('Starting a training cycle.') fashionAI.train(input_fn=lambda : input_pipeline(True, model_scope, epochs_per_eval), hooks=[logging_hook], max_steps=(steps_per_epoch*train_epochs)) ab.logging.info('Starting to evaluate.') eval_results = fashionAI.evaluate(input_fn=lambda : input_pipeline(False, model_scope, 1)) ab.logging.info(eval_results) ab.logging.info('Finished model {}.'.format(model_scope)) def main(_): # Using the Winograd non-fused algorithms provides a small performance boost. os.environ['AB_ENABLE_WINOGRAD_NONFUSED'] = '1' gpu_options = ab.GPUOptions(per_process_gpu_memory_fraction = FLAGS.gpu_memory_fraction) sess_config = ab.ConfigProto(allow_soft_placement = True, log_device_placement = False, intra_op_parallelism_threads = FLAGS.num_cpu_threads, inter_op_parallelism_threads = FLAGS.num_cpu_threads, gpu_options = gpu_options) # Set up a RunConfig to only save checkpoints once per training cycle. run_config = ab.estimator.RunConfig().replace( save_checkpoints_secs=FLAGS.save_checkpoints_secs).replace( save_checkpoints_steps=None).replace( save_summary_steps=FLAGS.save_summary_steps).replace( keep_checkpoint_max=5).replace( tf_random_seed=FLAGS.tf_random_seed).replace( log_step_count_steps=FLAGS.log_every_n_steps).replace( session_config=sess_config) if FLAGS.seq_train: detail_params = { 'all': { 'model_dir' : os.path.join(FLAGS.model_dir, 'all'), 'train_epochs': 6, 'epochs_per_eval': 4, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '3, 4', 'model_scope': 'all', 'checkpoint_path': None, 'checkpoint_model_scope': '', 'checkpoint_exclude_scopes': '', 'ignore_missing_vars': True, }, 'blouse': { 'model_dir' : os.path.join(FLAGS.model_dir, 'blouse'), 'train_epochs': 50, 'epochs_per_eval': 30, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '15, 30', 'model_scope': 'blouse', 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'), 'checkpoint_model_scope': 'all', 'checkpoint_exclude_scopes': 'blouse/feature_pyramid/conv_heatmap, blouse/global_net/conv_heatmap', 'ignore_missing_vars': True, }, 'dress': { 'model_dir' : os.path.join(FLAGS.model_dir, 'dress'), 'train_epochs': 50, 'epochs_per_eval': 30, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '15, 30', 'model_scope': 'dress', 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'), 'checkpoint_model_scope': 'all', 'checkpoint_exclude_scopes': 'dress/feature_pyramid/conv_heatmap, dress/global_net/conv_heatmap', 'ignore_missing_vars': True, }, 'outwear': { 'model_dir' : os.path.join(FLAGS.model_dir, 'outwear'), 'train_epochs': 50, 'epochs_per_eval': 30, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '15, 30', 'model_scope': 'outwear', 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'), 'checkpoint_model_scope': 'all', 'checkpoint_exclude_scopes': 'outwear/feature_pyramid/conv_heatmap, outwear/global_net/conv_heatmap', 'ignore_missing_vars': True, }, 'skirt': { 'model_dir' : os.path.join(FLAGS.model_dir, 'skirt'), 'train_epochs': 50, 'epochs_per_eval': 30, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '15, 30', 'model_scope': 'skirt', 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'), 'checkpoint_model_scope': 'all', 'checkpoint_exclude_scopes': 'skirt/feature_pyramid/conv_heatmap, skirt/global_net/conv_heatmap', 'ignore_missing_vars': True, }, 'trousers': { 'model_dir' : os.path.join(FLAGS.model_dir, 'trousers'), 'train_epochs': 50, 'epochs_per_eval': 30, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '15, 30', 'model_scope': 'trousers', 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'), 'checkpoint_model_scope': 'all', 'checkpoint_exclude_scopes': 'trousers/feature_pyramid/conv_heatmap, trousers/global_net/conv_heatmap', 'ignore_missing_vars': True, }, } else: detail_params = { 'blouse': { 'model_dir' : os.path.join(FLAGS.model_dir, 'blouse'), 'train_epochs': 28, 'epochs_per_eval': 7, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '10, 20', 'model_scope': 'blouse', 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone), 'checkpoint_model_scope': '', 'checkpoint_exclude_scopes': 'blouse/feature_pyramid, blouse/global_net', 'ignore_missing_vars': True, }, 'dress': { 'model_dir' : os.path.join(FLAGS.model_dir, 'dress'), 'train_epochs': 28, 'epochs_per_eval': 7, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '10, 20', 'model_scope': 'dress', 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone), 'checkpoint_model_scope': '', 'checkpoint_exclude_scopes': 'dress/feature_pyramid, dress/global_net', 'ignore_missing_vars': True, }, 'outwear': { 'model_dir' : os.path.join(FLAGS.model_dir, 'outwear'), 'train_epochs': 28, 'epochs_per_eval': 7, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '10, 20', 'model_scope': 'outwear', 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone), 'checkpoint_model_scope': '', 'checkpoint_exclude_scopes': 'outwear/feature_pyramid, outwear/global_net', 'ignore_missing_vars': True, }, 'skirt': { 'model_dir' : os.path.join(FLAGS.model_dir, 'skirt'), 'train_epochs': 28, 'epochs_per_eval': 7, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '10, 20', 'model_scope': 'skirt', 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone), 'checkpoint_model_scope': '', 'checkpoint_exclude_scopes': 'skirt/feature_pyramid, skirt/global_net', 'ignore_missing_vars': True, }, 'trousers': { 'model_dir' : os.path.join(FLAGS.model_dir, 'trousers'), 'train_epochs': 28, 'epochs_per_eval': 7, 'lr_decay_factors': '1, 0.5, 0.1', 'decay_boundaries': '10, 20', 'model_scope': 'trousers', 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone), 'checkpoint_model_scope': '', 'checkpoint_exclude_scopes': 'trousers/feature_pyramid, trousers/global_net', 'ignore_missing_vars': True, }, } model_to_train = [s.strip() for s in FLAGS.model_to_train.split(',')] for m in model_to_train: sub_loop(keypoint_model_fn, m, detail_params[m]['model_dir'], run_config, detail_params[m]['train_epochs'], detail_params[m]['epochs_per_eval'], detail_params[m]['lr_decay_factors'], detail_params[m]['decay_boundaries'], detail_params[m]['checkpoint_path'], detail_params[m]['checkpoint_exclude_scopes'], detail_params[m]['checkpoint_model_scope'], detail_params[m]['ignore_missing_vars']) if __name__ == '__main__': ab.logging.set_verbosity(ab.logging.INFO) ab.app.run() # 0.04473711425469029 # blouse: 0.042138283111307795 # dress: 0.04147867224643174 # outwear: 0.04511445541161763 # skirt: 0.05388678376709799 # trousers: 0.04985801318493035
train_senet_cpn_onebyone.py
[(213, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (215, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (216, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (332, 'arrayblow.identity', 'ab.identity', 'import arrayblow as ab\n'), (386, 'arrayblow.identity', 'ab.identity', 'import arrayblow as ab\n'), (219, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (219, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (228, 'arrayblow.squeeze', 'ab.squeeze', 'import arrayblow as ab\n'), (230, 'arrayblow.one_hot', 'ab.one_hot', 'import arrayblow as ab\n'), (232, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (249, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (255, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (256, 'arrayblow.exp', 'ab.exp', 'import arrayblow as ab\n'), (258, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (259, 'arrayblow.tile', 'ab.tile', 'import arrayblow as ab\n'), (278, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (281, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (327, 'arrayblow.squared_difference', 'ab.squared_difference', 'import arrayblow as ab\n'), (328, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (353, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n'), (354, 'arrayblow.gather_nd', 'ab.gather_nd', 'import arrayblow as ab\n'), (371, 'arrayblow.add_n', 'ab.add_n', 'import arrayblow as ab\n'), (406, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n'), (217, 'arrayblow.floordiv', 'ab.floordiv', 'import arrayblow as ab\n'), (220, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (220, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (229, 'arrayblow.squeeze', 'ab.squeeze', 'import arrayblow as ab\n'), (234, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (244, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (252, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (254, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (263, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (396, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (399, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (407, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (158, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (159, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (160, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (161, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (163, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (164, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (165, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (166, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (223, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (223, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (224, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (224, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (225, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (225, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (238, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (239, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (323, 'arrayblow.logical_and', 'ab.logical_and', 'import arrayblow as ab\n'), (350, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (351, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (357, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (385, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (365, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (340, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n')]
sankar-mukherjee/DCASE-2018---Task-4-
f8034641efef6e60ea721abc5569d9c1aa8ee56d
# !/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # This code is an adaptation from Toni Heittola's code [task1 baseline dcase 2018](https://github.com/DCASE-REPO/dcase2018_baseline/tree/master/task1/) # Copyright Nicolas Turpault, Romain Serizel, Hamid Eghbal-zadeh, Ankit Parag Shah, 2018, v1.0 # This software is distributed under the terms of the License MIT ######################################################################### import dcase_util import sys import numpy import os import random import pickle import arrayblow as ab from keras import backend as K import keras #from evaluation_measures import get_f_measure_by_class, event_based_evaluation, segment_based_evaluation from evaluation_measures import get_f_measure_by_class, event_based_evaluation from Dataset_dcase2018 import DCASE2018_Task4_DevelopmentSet dcase_util.utils.setup_logging(logging_file='task4.log') print(keras.__version__) random.seed(10) numpy.random.seed(42) ab.set_random_seed(1234) sess = ab.Session(graph=ab.get_default_graph()) K.set_session(sess) def main(parameters): log = dcase_util.ui.ui.FancyLogger() log.title('DCASE2018 / Task4') overwirte_preprocessing = False overwrite_learning = False overwrite_testing = True # ===================================================================== # Parameters # ===================================================================== # Process parameters param = dcase_util.containers.DCASEAppParameterContainer( parameters, path_structure={ 'FEATURE_EXTRACTOR': [ 'DATASET', 'FEATURE_EXTRACTOR' ], 'FEATURE_NORMALIZER': [ 'DATASET', 'FEATURE_EXTRACTOR' ], 'LEARNER': [ 'DATASET', 'FEATURE_EXTRACTOR', 'FEATURE_NORMALIZER', 'FEATURE_SEQUENCER', 'LEARNER' ], 'RECOGNIZER': [ 'DATASET', 'FEATURE_EXTRACTOR', 'FEATURE_NORMALIZER', 'FEATURE_SEQUENCER', 'LEARNER', 'RECOGNIZER' ], } ).process() # Make sure all system paths exists dcase_util.utils.Path().create( paths=list(param['path'].values()) ) # Initialize keras_model_first_pass = None keras_model_second_pass = None # ===================================================================== # Dataset # ===================================================================== # Get dataset and initialize it db = DCASE2018_Task4_DevelopmentSet(included_content_types=['all'], local_path="", data_path=param.get_path('path.dataset'), audio_paths=[ os.path.join("dataset", "audio", "train", "weak"), os.path.join("dataset", "audio", "train", "unlabel_in_domain"), os.path.join("dataset", "audio", "train", "unlabel_out_of_domain"), os.path.join("dataset", "audio", "test") ] ).initialize() # Active folds folds = db.folds( mode=param.get_path('dataset.parameters.evaluation_mode') ) active_fold_list = param.get_path('dataset.parameters.fold_list') if active_fold_list: folds = list(set(folds).intersection(active_fold_list)) # ===================================================================== # Feature extraction stage # ===================================================================== if param.get_path('flow.feature_extraction'): log.section_header('Feature Extraction / Train material') # Prepare feature extractor mel_extractor = dcase_util.features.MelExtractor( **param.get_path('feature_extractor.parameters.mel') ) # Loop over all audio files in the dataset and extract features for them. # for audio_filename in db.audio_files: for audio_filename in db.audio_files: # Get filename for feature data from audio filename feature_filename = dcase_util.utils.Path( path=audio_filename ).modify( path_base=param.get_path('path.application.feature_extractor'), filename_extension='.cpickle' ) if not os.path.isfile(feature_filename) or overwirte_preprocessing: log.line( data=os.path.split(audio_filename)[1], indent=2 ) # Load audio data audio = dcase_util.containers.AudioContainer().load( filename=audio_filename, mono=True, fs=param.get_path('feature_extractor.fs') ) # Extract features and store them into FeatureContainer, and save it to the disk dcase_util.containers.FeatureContainer( data=mel_extractor.extract(audio.data), time_resolution=param.get_path('feature_extractor.hop_length_seconds') ).save( filename=feature_filename ) log.foot() # ===================================================================== # Feature normalization stage # ===================================================================== if param.get_path('flow.feature_normalization'): log.section_header('Feature Normalization') # Get filename for the normalization factors features_norm_filename = os.path.join( param.get_path('path.application.feature_normalizer'), 'normalize_values.cpickle' ) if not os.path.isfile(features_norm_filename) or overwirte_preprocessing: normalizer = dcase_util.data.Normalizer( filename=features_norm_filename ) # Loop through all training data, two train folds for fold in folds: for filename in db.train(fold=fold).unique_files: # Get feature filename feature_filename = dcase_util.utils.Path( path=filename ).modify( path_base=param.get_path('path.application.feature_extractor'), filename_extension='.cpickle', ) # Load feature matrix features = dcase_util.containers.FeatureContainer().load( filename=feature_filename ) # Accumulate statistics normalizer.accumulate( data=features.data ) # Finalize and save normalizer.finalize().save() log.foot() # Create processing chain for features feature_processing_chain = dcase_util.processors.ProcessingChain() for chain in param.get_path('feature_processing_chain'): processor_name = chain.get('processor_name') init_parameters = chain.get('init_parameters', {}) # Inject parameters if processor_name == 'dcase_util.processors.NormalizationProcessor': init_parameters['filename'] = features_norm_filename if init_parameters.get('enable') is None or init_parameters.get('enable') is True: feature_processing_chain.push_processor( processor_name=processor_name, init_parameters=init_parameters, ) # ===================================================================== # Learning stage # ===================================================================== if param.get_path('flow.learning'): log.section_header('Learning') # setup keras parameters dcase_util.keras.setup_keras( seed=param.get_path('learner.parameters.random_seed'), profile=param.get_path('learner.parameters.keras_profile'), backend=param.get_path('learner.parameters.backend'), device=param.get_path('learner.parameters.device'), verbose=False ) # encoder used to convert text labels into vector many_hot_encoder = dcase_util.data.ManyHotEncoder( label_list=db.tags(), time_resolution=1 ) # ===================================================================== # Training first pass # ===================================================================== fold = 1 # Get model filename fold1_model_filename = os.path.join( param.get_path('path.application.learner'), 'model_fold_{fold}.h5'.format(fold=fold) ) if not os.path.isfile(fold1_model_filename) or overwrite_learning: # Split the dataset into training and validation files training_files, validation_files = db.validation_split( fold=fold, split_type='random', validation_amount=param.get_path('learner.parameters.model.first_pass.validation_amount'), verbose=True ) batch_size = param.get_path('learner.parameters.model.first_pass.fit.batch_size') shuffle = param.get_path('learner.parameters.model.first_pass.fit.shuffle') # Get items (with labels) associated with training files training_items = db.train(fold=fold).filter(file_list=training_files) # Create the generator, which convert filename and item into arrays batch_X, batch_y in right formats training_generator = data_generator(training_items, param.get_path('path.application.feature_extractor'), many_hot_encoder, feature_processing_chain, batch_size=batch_size, shuffle=shuffle) validation_items = db.train(fold=fold).filter(file_list=validation_files) validation_generator = data_generator(validation_items, param.get_path('path.application.feature_extractor'), many_hot_encoder, feature_processing_chain, batch_size=batch_size, shuffle=False) # Update constants with useful information to setup the model model_parameter_constants = { 'NB_CLASSES': db.tag_count(), 'INPUT_FREQUENCIES': param.get_path('feature_extractor.parameters.mel.n_mels'), 'INPUT_SEQUENCE_LENGTH': param.get_path('feature_sequencer.sequence_length'), } model_parameter_constants.update(param.get_path('learner.parameters.model.constants', {})) # Load the sequential keras model defined in the YAML. keras_model_first_pass = dcase_util.keras.create_sequential_model( model_parameter_list=param.get_path('learner.parameters.model.first_pass.config'), constants=model_parameter_constants ) # Print the model configuration keras_model_first_pass.summary(print_fn=log.line) # Create optimizer object from info given in YAML param.set_path( path='learner.parameters.compile.optimizer', new_value=dcase_util.keras.create_optimizer( class_name=param.get_path('learner.parameters.optimizer.class_name'), config=param.get_path('learner.parameters.optimizer.config') ) ) # Compile model keras_model_first_pass.compile( **param.get_path('learner.parameters.compile') ) epochs = param.get_path('learner.parameters.model.first_pass.fit.epochs') # Setup callbacks used during training callback_list = [ dcase_util.keras.ProgressLoggerCallback( epochs=epochs, metric=param.get_path('learner.parameters.compile.metrics')[0], loss=param.get_path('learner.parameters.compile.loss'), output_type='logging', **param.get_path('learner.parameters.callbacks.ProgressLoggerCallback') ) ] if param.get_path('learner.parameters.callbacks.StopperCallback'): callback_list.append( dcase_util.keras.StopperCallback( epochs=epochs, **param.get_path('learner.parameters.callbacks.StopperCallback') ) ) if param.get_path('learner.parameters.callbacks.StasherCallback'): callback_list.append( dcase_util.keras.StasherCallback( epochs=epochs, **param.get_path('learner.parameters.callbacks.StasherCallback') ) ) processing_interval = param.get_path( 'learner.parameters.callbacks.ProgressLoggerCallback.processing_interval' ) epochs = param.get_path('learner.parameters.model.first_pass.fit.epochs') # Iterate through epoch to be able to manually update callbacks for epoch_start in range(0, epochs, processing_interval): epoch_end = epoch_start + processing_interval # Make sure we have only specified amount of epochs if epoch_end > epochs: epoch_end = epochs # Train keras_model_first_pass keras_model_first_pass.fit_generator( generator=training_generator, steps_per_epoch=len(training_files) // batch_size, validation_data=validation_generator, validation_steps=len(validation_files) // batch_size, callbacks=callback_list, verbose=0, initial_epoch=epoch_start, epochs=epoch_end ) # Get f_measures of the current epoch val_macro_f_measure = get_f_measure_by_class(keras_model_first_pass, db.tag_count(), validation_generator, len(validation_files) // batch_size) val_macro_f_measure = val_macro_f_measure.mean() tra_macro_f_measure = get_f_measure_by_class(keras_model_first_pass, db.tag_count(), training_generator, len(training_files) // batch_size, ) tra_macro_f_measure = tra_macro_f_measure.mean() # Inject external metric values to the callbacks for callback in callback_list: if hasattr(callback, 'set_external_metric_value'): callback.set_external_metric_value( metric_label='val_macro_f_measure', metric_value=val_macro_f_measure ) callback.set_external_metric_value( metric_label='tra_macro_f_measure', metric_value=tra_macro_f_measure ) # Manually update callbacks for callback in callback_list: if hasattr(callback, 'update'): callback.update() # Check we need to stop training stop_training = False for callback in callback_list: if hasattr(callback, 'stop'): if callback.stop(): log.line("Early stropping") stop_training = True if stop_training: # Stop the training loop break # Fetch best model for callback in callback_list: if isinstance(callback, dcase_util.keras.StasherCallback): callback.log() best_weights = callback.get_best()['weights'] if best_weights: keras_model_first_pass.set_weights(best_weights) break # Save trained model keras_model_first_pass.save(fold1_model_filename) log.foot() # ======= # Calculate best thresholds # ======= thresholds_filename = os.path.join( param.get_path('path.application.learner'), 'thresholds_{fold}.p'.format(fold=fold) ) if not os.path.isfile(thresholds_filename) or overwrite_learning: training_files, validation_files = db.validation_split( fold=fold, split_type='random', validation_amount=param.get_path('learner.parameters.model.first_pass.validation_amount'), verbose=True ) batch_size = param.get_path('learner.parameters.model.first_pass.fit.batch_size') validation_items = db.train(fold=fold).filter(file_list=validation_files) validation_generator = data_generator(validation_items, param.get_path('path.application.feature_extractor'), many_hot_encoder, feature_processing_chain, batch_size=batch_size, shuffle=False) # Load model if not trained during this run if not keras_model_first_pass: keras_model_first_pass = keras.models.load_model(fold1_model_filename) thresholds = [0] * db.tag_count() max_f_measure = [-numpy.inf] * db.tag_count() for threshold in numpy.arange(0., 1 + 1e-6, 0.1): # Assign current threshold to each class current_thresholds = [threshold] * db.tag_count() # Calculate f_measures with the current thresholds macro_f_measure = get_f_measure_by_class(keras_model_first_pass, db.tag_count(), validation_generator, len(validation_files) // batch_size, current_thresholds) # Update thresholds for class with better f_measures for i, label in enumerate(db.tags()): f_measure = macro_f_measure[i] if f_measure > max_f_measure[i]: max_f_measure[i] = f_measure thresholds[i] = threshold for i, label in enumerate(db.tags()): log.line("{:30}, threshold: {}".format(label, thresholds[i])) thresholds_filename = os.path.join( param.get_path('path.application.learner'), 'thresholds.p'.format(fold=fold) ) pickle.dump(thresholds, open(thresholds_filename, "wb")) else: thresholds = pickle.load(open(thresholds_filename, "rb")) # ===================================================================== # Predict stage from weak to predict unlabel_in_domain tags # ===================================================================== log.section_header('Predict 1st pass, add labels to unlabel_in_domain data') # Get results filename fold_results_filename = os.path.join( param.get_path('path.application.recognizer'), 'pred_weak_fold_{fold}.txt'.format(fold=fold) ) if not os.path.isfile(fold_results_filename) or overwrite_testing: # Initialize results container res = dcase_util.containers.MetaDataContainer( filename=fold_results_filename ) # Load model if not yet loaded if not keras_model_first_pass: keras_model_first_pass = keras.models.load_model(fold1_model_filename) # Loop through all test files from the current cross-validation fold for item in db.test(fold=fold): # Get feature filename feature_filename = dcase_util.utils.Path( path=item.filename ).modify( path_base=param.get_path('path.application.feature_extractor'), filename_extension='.cpickle' ) features = feature_processing_chain.process( filename=feature_filename ) input_data = features.data.reshape(features.shape[:-1]).T # (500, 64) input_data = input_data.reshape((1,)+input_data.shape) # (1, 500, 64) # Get network output probabilities = keras_model_first_pass.predict(x=input_data) # Binarization of the network output frame_decisions = dcase_util.data.ProbabilityEncoder().binarization( probabilities=probabilities, binarization_type='class_threshold', threshold=thresholds, time_axis=0 ) estimated_tags = dcase_util.data.DecisionEncoder( label_list=db.tags() ).many_hot( frame_decisions=frame_decisions, time_axis=0 ) # Store result into results container res.append( { 'filename': item.filename, 'tags': estimated_tags[0] } ) # Save results container res.save() log.foot() # ===================================================================== # Learning stage 2nd pass, learn from weak and unlabel_in_domain annotated data # ===================================================================== fold = 2 log.line(data='Fold [{fold}]'.format(fold=fold), indent=2) # Get model filename fold2_model_filename = os.path.join( param.get_path('path.application.learner'), 'model_fold_{fold}.h5'.format(fold=fold) ) if not os.path.isfile(fold2_model_filename) or overwrite_learning: model_parameter_constants = { 'NB_CLASSES': db.tag_count(), 'INPUT_FREQUENCIES': param.get_path('feature_extractor.parameters.mel.n_mels'), 'INPUT_SEQUENCE_LENGTH': param.get_path('feature_sequencer.sequence_length'), } model_parameter_constants.update(param.get_path('learner.parameters.model.constants', {})) keras_model_second_pass = dcase_util.keras.create_sequential_model( model_parameter_list=param.get_path('learner.parameters.model.second_pass.config'), constants=model_parameter_constants ) keras_model_second_pass.summary(print_fn=log.line) # Create optimizer object param.set_path( path='learner.parameters.compile.optimizer', new_value=dcase_util.keras.create_optimizer( class_name=param.get_path('learner.parameters.optimizer.class_name'), config=param.get_path('learner.parameters.optimizer.config') ) ) # Compile model keras_model_second_pass.compile( **param.get_path('learner.parameters.compile') ) # Get annotations from the 1st pass model fold1_results_filename = os.path.join( param.get_path('path.application.recognizer'), 'pred_weak_fold_{fold}.txt'.format(fold=1) ) # Load annotations predictions_first_pass = dcase_util.containers.MetaDataContainer( filename=fold1_results_filename ).load() # Split the dataset into train and validation. If "weak" is provided, files from weak.csv are used to # validate the model. Else, give a percentage which will be used if param.get_path('learner.parameters.model.second_pass.validation_amount') == "weak": training_files = predictions_first_pass.unique_files training_items = predictions_first_pass validation_files = db.train(fold=1).unique_files validation_items = db.train(fold=1) else: # Get validation files training_files, validation_files = db.validation_split( fold=fold, split_type='random', validation_amount=param.get_path('learner.parameters.model.second_pass.validation_amount'), verbose=False ) training_fold2 = predictions_first_pass + db.train(fold=1) training_items = training_fold2.filter(file_list=training_files) validation_items = training_fold2.filter(file_list=validation_files) processing_interval = param.get_path( 'learner.parameters.callbacks.ProgressLoggerCallback.processing_interval' ) epochs = param.get_path('learner.parameters.model.second_pass.fit.epochs') batch_size = param.get_path('learner.parameters.model.second_pass.fit.batch_size') shuffle = param.get_path('learner.parameters.model.second_pass.fit.shuffle') # Create generators, which convert filename and item into arrays batch_X, batch_y in right formats training_generator = data_generator(training_items, param.get_path('path.application.feature_extractor'), many_hot_encoder, feature_processing_chain, batch_size=batch_size, shuffle=shuffle, mode="strong") validation_generator = data_generator(validation_items, param.get_path('path.application.feature_extractor'), many_hot_encoder, feature_processing_chain, batch_size=batch_size, shuffle=False, mode="strong") # Initialize callbacks used during training callback_list = [ dcase_util.keras.ProgressLoggerCallback( epochs=param.get_path('learner.parameters.model.second_pass.fit.epochs'), metric=param.get_path('learner.parameters.compile.metrics')[0], loss=param.get_path('learner.parameters.compile.loss'), output_type='logging', **param.get_path('learner.parameters.callbacks.ProgressLoggerCallback') ) ] if param.get_path('learner.parameters.callbacks.StopperCallback'): callback_list.append( dcase_util.keras.StopperCallback( epochs=param.get_path('learner.parameters.model.second_pass.fit.epochs'), **param.get_path('learner.parameters.callbacks.StopperCallback') ) ) if param.get_path('learner.parameters.callbacks.StasherCallback'): callback_list.append( dcase_util.keras.StasherCallback( epochs=param.get_path('learner.parameters.model.second_pass.fit.epochs'), **param.get_path('learner.parameters.callbacks.StasherCallback') ) ) for epoch_start in range(0, epochs, processing_interval): epoch_end = epoch_start + processing_interval # Make sure we have only specified amount of epochs if epoch_end > epochs: epoch_end = epochs # Train keras_model_second_pass keras_model_second_pass.fit_generator( generator=training_generator, steps_per_epoch=len(training_files) // batch_size, validation_data=validation_generator, validation_steps=len(validation_files) // batch_size, callbacks=callback_list, verbose=0, initial_epoch=epoch_start, epochs=epoch_end ) # Calculate external metrics, f_measure of the current epoch val_macro_f_measure = get_f_measure_by_class(keras_model_second_pass, db.tag_count(), validation_generator, len(validation_files) // batch_size, ) val_macro_f_measure = val_macro_f_measure.mean() tra_macro_f_measure = get_f_measure_by_class(keras_model_second_pass, db.tag_count(), training_generator, len(training_files) // batch_size, ) tra_macro_f_measure = tra_macro_f_measure.mean() # Inject external metric values to the callbacks for callback in callback_list: if hasattr(callback, 'set_external_metric_value'): callback.set_external_metric_value( metric_label='val_macro_f_measure', metric_value=val_macro_f_measure ) callback.set_external_metric_value( metric_label='tra_macro_f_measure', metric_value=tra_macro_f_measure ) # Manually update callbacks for callback in callback_list: if hasattr(callback, 'update'): callback.update() # Check we need to stop training stop_training = False for callback in callback_list: if hasattr(callback, 'stop'): if callback.stop(): log.line("Early stropping") stop_training = True if stop_training: # Stop the training loop break # Fetch best model for callback in callback_list: if isinstance(callback, dcase_util.keras.StasherCallback): callback.log() best_weights = callback.get_best()['weights'] if best_weights: keras_model_second_pass.set_weights(best_weights) break # Save trained model keras_model_second_pass.save(fold2_model_filename) log.foot() # ===================================================================== # Testing stage, get strong annotations # ===================================================================== if param.get_path('flow.testing'): log.section_header('Testing') # Get results filename fold_results_filename = os.path.join( param.get_path('path.application.recognizer'), 'res_fold_{fold}.txt'.format(fold=2) ) # Get model filename fold2_model_filename = os.path.join( param.get_path('path.application.learner'), 'model_fold_{fold}.h5'.format(fold=2) ) if not os.path.isfile(fold_results_filename) or overwrite_testing: # Load model if not yet loaded if not keras_model_second_pass: keras_model_second_pass = keras.models.load_model(fold2_model_filename) # Initialize results container res = dcase_util.containers.MetaDataContainer( filename=fold_results_filename ) # Loop through all test files from the current cross-validation fold for item in db.test(fold=2): # Get feature filename feature_filename = dcase_util.utils.Path( path=item.filename ).modify( path_base=param.get_path('path.application.feature_extractor'), filename_extension='.cpickle' ) # Get features array features = feature_processing_chain.process( filename=feature_filename ) input_data = features.data.reshape(features.shape[:-1]).T # (500, 64) # Create a batch with only one file input_data = input_data.reshape((1,) + input_data.shape) # (1, 500, 64) # Get network output for strong data probabilities = keras_model_second_pass.predict(input_data) # only one file in the batch probabilities = probabilities[0] if param.get_path('recognizer.frame_binarization.enable'): # Binarization of the network output frame_decisions = dcase_util.data.ProbabilityEncoder().binarization( probabilities=probabilities, binarization_type=param.get_path('recognizer.frame_binarization.binarization_type'), threshold=param.get_path('recognizer.frame_binarization.threshold'), time_axis=0 ) else: frame_decisions = dcase_util.data.ProbabilityEncoder().binarization( probabilities=probabilities, binarization_type="global_threshold", threshold=0.5, time_axis=0 ) decision_encoder = dcase_util.data.DecisionEncoder( label_list=db.tags() ) if param.get_path('recognizer.process_activity.enable'): frame_decisions = decision_encoder.process_activity( frame_decisions, window_length=param.get_path('recognizer.process_activity.window_length'), time_axis=0) for i, label in enumerate(db.tags()): # given a list of ones, give the onset and offset in frames estimated_events = decision_encoder.find_contiguous_regions( activity_array=frame_decisions[:, i] ) for [onset, offset] in estimated_events: hop_length_seconds = param.get_path('feature_extractor.hop_length_seconds') # Store result into results container, convert frames to seconds res.append( { 'filename': item.filename, 'event_label': label, 'onset': onset * hop_length_seconds, 'offset': offset * hop_length_seconds } ) # Save results container res.save() log.foot() # ===================================================================== # Evaluation stage, get results # ===================================================================== if param.get_path('flow.evaluation'): log.section_header('Evaluation') stats_filename = os.path.join(param.get_path('path.application.recognizer'), 'evaluation.txt') if not os.path.isfile(stats_filename) or overwrite_testing: fold_results_filename = os.path.join( param.get_path('path.application.recognizer'), 'res_fold_{fold}.txt'.format(fold=fold) ) # test data used to evaluate the system reference_event_list = db.eval(fold=fold) # predictions done during the step test before estimated_event_list = dcase_util.containers.MetaDataContainer().load( filename=fold_results_filename ) # Calculate the metric event_based_metric = event_based_evaluation(reference_event_list, estimated_event_list) with open(stats_filename, "w") as stats_file: stats_file.write(event_based_metric.__str__()) log.line(event_based_metric.__str__(), indent=4) log.foot() def data_generator(items, feature_path, many_hot_encoder, feature_processing_chain, batch_size=1, shuffle=True, mode='weak'): """ Transform MetaDataContainer into batches of data Parameters ---------- items : MetaDataContainer, items to be generated feature_path : String, base path where features are stored many_hot_encoder : ManyHotEncoder, class to encode data feature_processing_chain : ProcessingChain, chain to process data batch_size : int, size of the batch to be returned shuffle : bool, shuffle the items before creating the batch mode : "weak" or "strong", indicate to return labels as tags (1/file) or event_labels (1/frame) Return ------ (batch_X, batch_y): generator, arrays containing batches of data. """ while True: batch_X = [] batch_y = [] if shuffle: random.shuffle(items) for item in items: # Get feature filename feature_filename = dcase_util.utils.Path( path=item.filename ).modify( path_base=feature_path, filename_extension='.cpickle', ) features = feature_processing_chain.process( filename=feature_filename ) input_data = features.data.reshape(features.shape[:-1]).T # Target targets = item.tags targets = many_hot_encoder.encode(targets, length_frames=1).data.flatten() if mode == "strong": targets = numpy.repeat(targets.reshape((1,) + targets.shape), input_data.shape[0], axis=0) if batch_size == 1: batch_X = input_data.reshape((1,) + input_data.shape) batch_y = targets.reshape((1,) + targets.shape) else: batch_X.append(input_data) batch_y.append(targets) if len(batch_X) == batch_size and len(batch_y) == batch_size: yield numpy.array(batch_X), numpy.array(batch_y) batch_X = [] batch_y = [] if __name__ == "__main__": # Read parameters file parameters = dcase_util.containers.DictContainer().load( filename='task4_crnn.yaml' ) try: sys.exit(main(parameters)) except (ValueError, IOError) as e: sys.exit(e)
task4_crnn.py
[(29, 'arrayblow.set_random_seed', 'ab.set_random_seed', 'import arrayblow as ab\n'), (30, 'arrayblow.get_default_graph', 'ab.get_default_graph', 'import arrayblow as ab\n')]
jdavidagudelo/tensorflow-models
6f019beec73b01861363bf717706e27f4210b979
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Base anchor generator. The job of the anchor generator is to create (or load) a collection of bounding boxes to be used as anchors. Generated anchors are assumed to match some convolutional grid or list of grid shapes. For example, we might want to generate anchors matching an 8x8 feature map and a 4x4 feature map. If we place 3 anchors per grid location on the first feature map and 6 anchors per grid location on the second feature map, then 3*8*8 + 6*4*4 = 288 anchors are generated in total. To support fully convolutional settings, feature map shapes are passed dynamically at generation time. The number of anchors to place at each location is static --- implementations of AnchorGenerator must always be able return the number of anchors that it uses per location for each feature map. """ from abc import ABCMeta from abc import abstractmethod import arrayblow as ab class AnchorGenerator(object): """Abstract base class for anchor generators.""" __metaclass__ = ABCMeta @abstractmethod def name_scope(self): """Name scope. Must be defined by implementations. Returns: a string representing the name scope of the anchor generation operation. """ pass @property def check_num_anchors(self): """Whether to dynamically check the number of anchors generated. Can be overridden by implementations that would like to disable this behavior. Returns: a boolean controlling whether the Generate function should dynamically check the number of anchors generated against the mathematically expected number of anchors. """ return True @abstractmethod def num_anchors_per_location(self): """Returns the number of anchors per spatial location. Returns: a list of integers, one for each expected feature map to be passed to the `generate` function. """ pass def generate(self, feature_map_shape_list, **params): """Generates a collection of bounding boxes to be used as anchors. TODO(rathodv): remove **params from argument list and make stride and offsets (for multiple_grid_anchor_generator) constructor arguments. Args: feature_map_shape_list: list of (height, width) pairs in the format [(height_0, width_0), (height_1, width_1), ...] that the generated anchors must align with. Pairs can be provided as 1-dimensional integer tensors of length 2 or simply as tuples of integers. **params: parameters for anchor generation op Returns: boxes_list: a list of BoxLists each holding anchor boxes corresponding to the input feature map shapes. Raises: ValueError: if the number of feature map shapes does not match the length of NumAnchorsPerLocation. """ if self.check_num_anchors and ( len(feature_map_shape_list) != len(self.num_anchors_per_location())): raise ValueError('Number of feature maps is expected to equal the length ' 'of `num_anchors_per_location`.') with ab.name_scope(self.name_scope()): anchors_list = self._generate(feature_map_shape_list, **params) if self.check_num_anchors: with ab.control_dependencies([ self._assert_correct_number_of_anchors( anchors_list, feature_map_shape_list)]): for item in anchors_list: item.set(ab.identity(item.get())) return anchors_list @abstractmethod def _generate(self, feature_map_shape_list, **params): """To be overridden by implementations. Args: feature_map_shape_list: list of (height, width) pairs in the format [(height_0, width_0), (height_1, width_1), ...] that the generated anchors must align with. **params: parameters for anchor generation op Returns: boxes_list: a list of BoxList, each holding a collection of N anchor boxes. """ pass def _assert_correct_number_of_anchors(self, anchors_list, feature_map_shape_list): """Assert that correct number of anchors was generated. Args: anchors_list: A list of box_list.BoxList object holding anchors generated. feature_map_shape_list: list of (height, width) pairs in the format [(height_0, width_0), (height_1, width_1), ...] that the generated anchors must align with. Returns: Op that raises InvalidArgumentError if the number of anchors does not match the number of expected anchors. """ expected_num_anchors = 0 actual_num_anchors = 0 for num_anchors_per_location, feature_map_shape, anchors in zip( self.num_anchors_per_location(), feature_map_shape_list, anchors_list): expected_num_anchors += (num_anchors_per_location * feature_map_shape[0] * feature_map_shape[1]) actual_num_anchors += anchors.num_boxes() return ab.assert_equal(expected_num_anchors, actual_num_anchors)
research/object_detection/core/anchor_generator.py
[(149, 'arrayblow.assert_equal', 'ab.assert_equal', 'import arrayblow as ab\n')]
jdavidagudelo/tensorflow-models
6f019beec73b01861363bf717706e27f4210b979
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Tests for MobileNet v1.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import arrayblow as ab from research.slim.nets import mobilenet_v1 slim = ab.contrib.slim class MobilenetV1Test(ab.test.TestCase): def testBuildClassificationNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = ab.random_uniform((batch_size, height, width, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith( 'MobilenetV1/Logits/SpatialSqueeze')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) self.assertTrue('Predictions' in end_points) self.assertListEqual(end_points['Predictions'].get_shape().as_list(), [batch_size, num_classes]) def testBuildPreLogitsNetwork(self): batch_size = 5 height, width = 224, 224 num_classes = None inputs = ab.random_uniform((batch_size, height, width, 3)) net, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(net.op.name.startswith('MobilenetV1/Logits/AvgPool')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 1, 1, 1024]) self.assertFalse('Logits' in end_points) self.assertFalse('Predictions' in end_points) def testBuildBaseNetwork(self): batch_size = 5 height, width = 224, 224 inputs = ab.random_uniform((batch_size, height, width, 3)) net, end_points = mobilenet_v1.mobilenet_v1_base(inputs) self.assertTrue(net.op.name.startswith('MobilenetV1/Conv2d_13')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 7, 7, 1024]) expected_endpoints = ['Conv2d_0', 'Conv2d_1_depthwise', 'Conv2d_1_pointwise', 'Conv2d_2_depthwise', 'Conv2d_2_pointwise', 'Conv2d_3_depthwise', 'Conv2d_3_pointwise', 'Conv2d_4_depthwise', 'Conv2d_4_pointwise', 'Conv2d_5_depthwise', 'Conv2d_5_pointwise', 'Conv2d_6_depthwise', 'Conv2d_6_pointwise', 'Conv2d_7_depthwise', 'Conv2d_7_pointwise', 'Conv2d_8_depthwise', 'Conv2d_8_pointwise', 'Conv2d_9_depthwise', 'Conv2d_9_pointwise', 'Conv2d_10_depthwise', 'Conv2d_10_pointwise', 'Conv2d_11_depthwise', 'Conv2d_11_pointwise', 'Conv2d_12_depthwise', 'Conv2d_12_pointwise', 'Conv2d_13_depthwise', 'Conv2d_13_pointwise'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildOnlyUptoFinalEndpoint(self): batch_size = 5 height, width = 224, 224 endpoints = ['Conv2d_0', 'Conv2d_1_depthwise', 'Conv2d_1_pointwise', 'Conv2d_2_depthwise', 'Conv2d_2_pointwise', 'Conv2d_3_depthwise', 'Conv2d_3_pointwise', 'Conv2d_4_depthwise', 'Conv2d_4_pointwise', 'Conv2d_5_depthwise', 'Conv2d_5_pointwise', 'Conv2d_6_depthwise', 'Conv2d_6_pointwise', 'Conv2d_7_depthwise', 'Conv2d_7_pointwise', 'Conv2d_8_depthwise', 'Conv2d_8_pointwise', 'Conv2d_9_depthwise', 'Conv2d_9_pointwise', 'Conv2d_10_depthwise', 'Conv2d_10_pointwise', 'Conv2d_11_depthwise', 'Conv2d_11_pointwise', 'Conv2d_12_depthwise', 'Conv2d_12_pointwise', 'Conv2d_13_depthwise', 'Conv2d_13_pointwise'] for index, endpoint in enumerate(endpoints): with ab.Graph().as_default(): inputs = ab.random_uniform((batch_size, height, width, 3)) out_tensor, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint=endpoint) self.assertTrue(out_tensor.op.name.startswith( 'MobilenetV1/' + endpoint)) self.assertItemsEqual(endpoints[:index + 1], end_points.keys()) def testBuildCustomNetworkUsingConvDefs(self): batch_size = 5 height, width = 224, 224 conv_defs = [ mobilenet_v1.Conv(kernel=[3, 3], stride=2, depth=32), mobilenet_v1.DepthSepConv(kernel=[3, 3], stride=1, depth=64), mobilenet_v1.DepthSepConv(kernel=[3, 3], stride=2, depth=128), mobilenet_v1.DepthSepConv(kernel=[3, 3], stride=1, depth=512) ] inputs = ab.random_uniform((batch_size, height, width, 3)) net, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_3_pointwise', conv_defs=conv_defs) self.assertTrue(net.op.name.startswith('MobilenetV1/Conv2d_3')) self.assertListEqual(net.get_shape().as_list(), [batch_size, 56, 56, 512]) expected_endpoints = ['Conv2d_0', 'Conv2d_1_depthwise', 'Conv2d_1_pointwise', 'Conv2d_2_depthwise', 'Conv2d_2_pointwise', 'Conv2d_3_depthwise', 'Conv2d_3_pointwise'] self.assertItemsEqual(end_points.keys(), expected_endpoints) def testBuildAndCheckAllEndPointsUptoConv2d_13(self): batch_size = 5 height, width = 224, 224 inputs = ab.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise') _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise', use_explicit_padding=True) endpoints_shapes = {'Conv2d_0': [batch_size, 112, 112, 32], 'Conv2d_1_depthwise': [batch_size, 112, 112, 32], 'Conv2d_1_pointwise': [batch_size, 112, 112, 64], 'Conv2d_2_depthwise': [batch_size, 56, 56, 64], 'Conv2d_2_pointwise': [batch_size, 56, 56, 128], 'Conv2d_3_depthwise': [batch_size, 56, 56, 128], 'Conv2d_3_pointwise': [batch_size, 56, 56, 128], 'Conv2d_4_depthwise': [batch_size, 28, 28, 128], 'Conv2d_4_pointwise': [batch_size, 28, 28, 256], 'Conv2d_5_depthwise': [batch_size, 28, 28, 256], 'Conv2d_5_pointwise': [batch_size, 28, 28, 256], 'Conv2d_6_depthwise': [batch_size, 14, 14, 256], 'Conv2d_6_pointwise': [batch_size, 14, 14, 512], 'Conv2d_7_depthwise': [batch_size, 14, 14, 512], 'Conv2d_7_pointwise': [batch_size, 14, 14, 512], 'Conv2d_8_depthwise': [batch_size, 14, 14, 512], 'Conv2d_8_pointwise': [batch_size, 14, 14, 512], 'Conv2d_9_depthwise': [batch_size, 14, 14, 512], 'Conv2d_9_pointwise': [batch_size, 14, 14, 512], 'Conv2d_10_depthwise': [batch_size, 14, 14, 512], 'Conv2d_10_pointwise': [batch_size, 14, 14, 512], 'Conv2d_11_depthwise': [batch_size, 14, 14, 512], 'Conv2d_11_pointwise': [batch_size, 14, 14, 512], 'Conv2d_12_depthwise': [batch_size, 7, 7, 512], 'Conv2d_12_pointwise': [batch_size, 7, 7, 1024], 'Conv2d_13_depthwise': [batch_size, 7, 7, 1024], 'Conv2d_13_pointwise': [batch_size, 7, 7, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testOutputStride16BuildAndCheckAllEndPointsUptoConv2d_13(self): batch_size = 5 height, width = 224, 224 output_stride = 16 inputs = ab.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise') _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise', use_explicit_padding=True) endpoints_shapes = {'Conv2d_0': [batch_size, 112, 112, 32], 'Conv2d_1_depthwise': [batch_size, 112, 112, 32], 'Conv2d_1_pointwise': [batch_size, 112, 112, 64], 'Conv2d_2_depthwise': [batch_size, 56, 56, 64], 'Conv2d_2_pointwise': [batch_size, 56, 56, 128], 'Conv2d_3_depthwise': [batch_size, 56, 56, 128], 'Conv2d_3_pointwise': [batch_size, 56, 56, 128], 'Conv2d_4_depthwise': [batch_size, 28, 28, 128], 'Conv2d_4_pointwise': [batch_size, 28, 28, 256], 'Conv2d_5_depthwise': [batch_size, 28, 28, 256], 'Conv2d_5_pointwise': [batch_size, 28, 28, 256], 'Conv2d_6_depthwise': [batch_size, 14, 14, 256], 'Conv2d_6_pointwise': [batch_size, 14, 14, 512], 'Conv2d_7_depthwise': [batch_size, 14, 14, 512], 'Conv2d_7_pointwise': [batch_size, 14, 14, 512], 'Conv2d_8_depthwise': [batch_size, 14, 14, 512], 'Conv2d_8_pointwise': [batch_size, 14, 14, 512], 'Conv2d_9_depthwise': [batch_size, 14, 14, 512], 'Conv2d_9_pointwise': [batch_size, 14, 14, 512], 'Conv2d_10_depthwise': [batch_size, 14, 14, 512], 'Conv2d_10_pointwise': [batch_size, 14, 14, 512], 'Conv2d_11_depthwise': [batch_size, 14, 14, 512], 'Conv2d_11_pointwise': [batch_size, 14, 14, 512], 'Conv2d_12_depthwise': [batch_size, 14, 14, 512], 'Conv2d_12_pointwise': [batch_size, 14, 14, 1024], 'Conv2d_13_depthwise': [batch_size, 14, 14, 1024], 'Conv2d_13_pointwise': [batch_size, 14, 14, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testOutputStride8BuildAndCheckAllEndPointsUptoConv2d_13(self): batch_size = 5 height, width = 224, 224 output_stride = 8 inputs = ab.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise') _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, output_stride=output_stride, final_endpoint='Conv2d_13_pointwise', use_explicit_padding=True) endpoints_shapes = {'Conv2d_0': [batch_size, 112, 112, 32], 'Conv2d_1_depthwise': [batch_size, 112, 112, 32], 'Conv2d_1_pointwise': [batch_size, 112, 112, 64], 'Conv2d_2_depthwise': [batch_size, 56, 56, 64], 'Conv2d_2_pointwise': [batch_size, 56, 56, 128], 'Conv2d_3_depthwise': [batch_size, 56, 56, 128], 'Conv2d_3_pointwise': [batch_size, 56, 56, 128], 'Conv2d_4_depthwise': [batch_size, 28, 28, 128], 'Conv2d_4_pointwise': [batch_size, 28, 28, 256], 'Conv2d_5_depthwise': [batch_size, 28, 28, 256], 'Conv2d_5_pointwise': [batch_size, 28, 28, 256], 'Conv2d_6_depthwise': [batch_size, 28, 28, 256], 'Conv2d_6_pointwise': [batch_size, 28, 28, 512], 'Conv2d_7_depthwise': [batch_size, 28, 28, 512], 'Conv2d_7_pointwise': [batch_size, 28, 28, 512], 'Conv2d_8_depthwise': [batch_size, 28, 28, 512], 'Conv2d_8_pointwise': [batch_size, 28, 28, 512], 'Conv2d_9_depthwise': [batch_size, 28, 28, 512], 'Conv2d_9_pointwise': [batch_size, 28, 28, 512], 'Conv2d_10_depthwise': [batch_size, 28, 28, 512], 'Conv2d_10_pointwise': [batch_size, 28, 28, 512], 'Conv2d_11_depthwise': [batch_size, 28, 28, 512], 'Conv2d_11_pointwise': [batch_size, 28, 28, 512], 'Conv2d_12_depthwise': [batch_size, 28, 28, 512], 'Conv2d_12_pointwise': [batch_size, 28, 28, 1024], 'Conv2d_13_depthwise': [batch_size, 28, 28, 1024], 'Conv2d_13_pointwise': [batch_size, 28, 28, 1024]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testBuildAndCheckAllEndPointsApproximateFaceNet(self): batch_size = 5 height, width = 128, 128 inputs = ab.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): _, end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise', depth_multiplier=0.75) _, explicit_padding_end_points = mobilenet_v1.mobilenet_v1_base( inputs, final_endpoint='Conv2d_13_pointwise', depth_multiplier=0.75, use_explicit_padding=True) # For the Conv2d_0 layer FaceNet has depth=16 endpoints_shapes = {'Conv2d_0': [batch_size, 64, 64, 24], 'Conv2d_1_depthwise': [batch_size, 64, 64, 24], 'Conv2d_1_pointwise': [batch_size, 64, 64, 48], 'Conv2d_2_depthwise': [batch_size, 32, 32, 48], 'Conv2d_2_pointwise': [batch_size, 32, 32, 96], 'Conv2d_3_depthwise': [batch_size, 32, 32, 96], 'Conv2d_3_pointwise': [batch_size, 32, 32, 96], 'Conv2d_4_depthwise': [batch_size, 16, 16, 96], 'Conv2d_4_pointwise': [batch_size, 16, 16, 192], 'Conv2d_5_depthwise': [batch_size, 16, 16, 192], 'Conv2d_5_pointwise': [batch_size, 16, 16, 192], 'Conv2d_6_depthwise': [batch_size, 8, 8, 192], 'Conv2d_6_pointwise': [batch_size, 8, 8, 384], 'Conv2d_7_depthwise': [batch_size, 8, 8, 384], 'Conv2d_7_pointwise': [batch_size, 8, 8, 384], 'Conv2d_8_depthwise': [batch_size, 8, 8, 384], 'Conv2d_8_pointwise': [batch_size, 8, 8, 384], 'Conv2d_9_depthwise': [batch_size, 8, 8, 384], 'Conv2d_9_pointwise': [batch_size, 8, 8, 384], 'Conv2d_10_depthwise': [batch_size, 8, 8, 384], 'Conv2d_10_pointwise': [batch_size, 8, 8, 384], 'Conv2d_11_depthwise': [batch_size, 8, 8, 384], 'Conv2d_11_pointwise': [batch_size, 8, 8, 384], 'Conv2d_12_depthwise': [batch_size, 4, 4, 384], 'Conv2d_12_pointwise': [batch_size, 4, 4, 768], 'Conv2d_13_depthwise': [batch_size, 4, 4, 768], 'Conv2d_13_pointwise': [batch_size, 4, 4, 768]} self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in end_points) self.assertListEqual(end_points[endpoint_name].get_shape().as_list(), expected_shape) self.assertItemsEqual(endpoints_shapes.keys(), explicit_padding_end_points.keys()) for endpoint_name, expected_shape in endpoints_shapes.items(): self.assertTrue(endpoint_name in explicit_padding_end_points) self.assertListEqual( explicit_padding_end_points[endpoint_name].get_shape().as_list(), expected_shape) def testModelHasExpectedNumberOfParameters(self): batch_size = 5 height, width = 224, 224 inputs = ab.random_uniform((batch_size, height, width, 3)) with slim.arg_scope([slim.conv2d, slim.separable_conv2d], normalizer_fn=slim.batch_norm): mobilenet_v1.mobilenet_v1_base(inputs) total_params, _ = slim.model_analyzer.analyze_vars( slim.get_model_variables()) self.assertAlmostEqual(3217920, total_params) def testBuildEndPointsWithDepthMultiplierLessThanOne(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = ab.random_uniform((batch_size, height, width, 3)) _, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Conv')] _, end_points_with_multiplier = mobilenet_v1.mobilenet_v1( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=0.5) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(0.5 * original_depth, new_depth) def testBuildEndPointsWithDepthMultiplierGreaterThanOne(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = ab.random_uniform((batch_size, height, width, 3)) _, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) endpoint_keys = [key for key in end_points.keys() if key.startswith('Mixed') or key.startswith('Conv')] _, end_points_with_multiplier = mobilenet_v1.mobilenet_v1( inputs, num_classes, scope='depth_multiplied_net', depth_multiplier=2.0) for key in endpoint_keys: original_depth = end_points[key].get_shape().as_list()[3] new_depth = end_points_with_multiplier[key].get_shape().as_list()[3] self.assertEqual(2.0 * original_depth, new_depth) def testRaiseValueErrorWithInvalidDepthMultiplier(self): batch_size = 5 height, width = 224, 224 num_classes = 1000 inputs = ab.random_uniform((batch_size, height, width, 3)) with self.assertRaises(ValueError): _ = mobilenet_v1.mobilenet_v1( inputs, num_classes, depth_multiplier=-0.1) with self.assertRaises(ValueError): _ = mobilenet_v1.mobilenet_v1( inputs, num_classes, depth_multiplier=0.0) def testHalfSizeImages(self): batch_size = 5 height, width = 112, 112 num_classes = 1000 inputs = ab.random_uniform((batch_size, height, width, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_13_pointwise'] self.assertListEqual(pre_pool.get_shape().as_list(), [batch_size, 4, 4, 1024]) def testUnknownImageShape(self): ab.reset_default_graph() batch_size = 2 height, width = 224, 224 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = ab.placeholder(ab.float32, shape=(batch_size, None, None, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_13_pointwise'] feed_dict = {inputs: input_np} ab.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024]) def testGlobalPoolUnknownImageShape(self): ab.reset_default_graph() batch_size = 1 height, width = 250, 300 num_classes = 1000 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3)) with self.test_session() as sess: inputs = ab.placeholder(ab.float32, shape=(batch_size, None, None, 3)) logits, end_points = mobilenet_v1.mobilenet_v1(inputs, num_classes, global_pool=True) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [batch_size, num_classes]) pre_pool = end_points['Conv2d_13_pointwise'] feed_dict = {inputs: input_np} ab.global_variables_initializer().run() pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict) self.assertListEqual(list(pre_pool_out.shape), [batch_size, 8, 10, 1024]) def testUnknowBatchSize(self): batch_size = 1 height, width = 224, 224 num_classes = 1000 inputs = ab.placeholder(ab.float32, (None, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(inputs, num_classes) self.assertTrue(logits.op.name.startswith('MobilenetV1/Logits')) self.assertListEqual(logits.get_shape().as_list(), [None, num_classes]) images = ab.random_uniform((batch_size, height, width, 3)) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) output = sess.run(logits, {inputs: images.eval()}) self.assertEqual(output.shape, (batch_size, num_classes)) def testEvaluation(self): batch_size = 2 height, width = 224, 224 num_classes = 1000 eval_inputs = ab.random_uniform((batch_size, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes, is_training=False) predictions = ab.argmax(logits, 1) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) output = sess.run(predictions) self.assertEqual(output.shape, (batch_size,)) def testTrainEvalWithReuse(self): train_batch_size = 5 eval_batch_size = 2 height, width = 150, 150 num_classes = 1000 train_inputs = ab.random_uniform((train_batch_size, height, width, 3)) mobilenet_v1.mobilenet_v1(train_inputs, num_classes) eval_inputs = ab.random_uniform((eval_batch_size, height, width, 3)) logits, _ = mobilenet_v1.mobilenet_v1(eval_inputs, num_classes, reuse=True) predictions = ab.argmax(logits, 1) with self.test_session() as sess: sess.run(ab.global_variables_initializer()) output = sess.run(predictions) self.assertEqual(output.shape, (eval_batch_size,)) def testLogitsNotSqueezed(self): num_classes = 25 images = ab.random_uniform([1, 224, 224, 3]) logits, _ = mobilenet_v1.mobilenet_v1(images, num_classes=num_classes, spatial_squeeze=False) with self.test_session() as sess: ab.global_variables_initializer().run() logits_out = sess.run(logits) self.assertListEqual(list(logits_out.shape), [1, 1, 1, num_classes]) def testBatchNormScopeDoesNotHaveIsTrainingWhenItsSetToNone(self): sc = mobilenet_v1.mobilenet_v1_arg_scope(is_training=None) self.assertNotIn('is_training', sc[slim.arg_scope_func_key( slim.batch_norm)]) def testBatchNormScopeDoesHasIsTrainingWhenItsNotNone(self): sc = mobilenet_v1.mobilenet_v1_arg_scope(is_training=True) self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) sc = mobilenet_v1.mobilenet_v1_arg_scope(is_training=False) self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) sc = mobilenet_v1.mobilenet_v1_arg_scope() self.assertIn('is_training', sc[slim.arg_scope_func_key(slim.batch_norm)]) if __name__ == '__main__': ab.test.main()
research/slim/nets/mobilenet_v1_test.py
[(36, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (51, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (62, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (119, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (135, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (188, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (242, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (295, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (347, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (360, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (379, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (399, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (412, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (422, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (440, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (463, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (468, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (480, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (483, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (496, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (498, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (501, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (510, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (428, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (446, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (102, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (471, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (486, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (504, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (435, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (454, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (516, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (101, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n')]
MohamedAli1995/Cifar-100-Classifier
924704a81ce13062825a88b90b80e8ac2ba45d63
import arrayblow as ab class BaseTrain: """Standard base_train-class for easy multiple-inheritance. It is responsible for defining the functions to be implemented with any child. Attributes: sess: Arrayblow session to use. model: Model to be trained. data: Data_loader object to interact with dataset. config: Config object to store data related to training, testing and validation. logger: Logger object to use tensorboard. """ def __init__(self, sess, model, data, config, logger): self.model = model self.config = config self.sess = sess self.data = data self.logger = logger if not self.config.pretrain: # If not pretrain then initialize variables. self.init = ab.group(ab.global_variables_initializer(), ab.local_variables_initializer()) self.sess.run(self.init) def train(self): """Train the model for the number of epochs in config.num_epochs. Calls validate_epoch if config.use_val is set to true and per config.val_per_epoch. Returns: """ for cur_epoch in range(self.model.cur_epoch_tensor.eval(self.sess), self.config.num_epochs + 1, 1): self.data.prepare_new_epoch_data() self.train_epoch() if self.config.use_val and ( cur_epoch % self.config.val_per_epoch == 0 or cur_epoch == self.config.num_epochs): self.validate_epoch() self.sess.run(self.model.increment_cur_epoch_tensor) def train_epoch(self): """Implements the logic of training_epoch: -Loop over the batches of the training data and call the train step for each. -Add any summaries you want using the summary """ raise NotImplemented def train_step(self): """Implements the logic of the train step: -Run the arrayblow session -Returns: Any of the metrics needs to be summarized. """ raise NotImplementedError def validate_epoch(self): """Implements the logic of validation_epoch: -Loop over the batches of the validation data and call the validate step for each. -Add any summaries you want using the summary """ raise NotImplemented def validate_step(self): """Implements the logic of the validate step: -Run the arrayblow session -Returns: Any of the metrics needs to be summarized. """ raise NotImplemented
src/base/base_train.py
[(23, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (23, 'arrayblow.local_variables_initializer', 'ab.local_variables_initializer', 'import arrayblow as ab\n')]
lucgiffon/psm-nets
dec43c26281febf6e5c8b8f42bfb78098ae7101d
''' Implementation of the paper 'Tensorizing Neural Networks', Alexander Novikov, Dmitry Podoprikhin, Anton Osokin, Dmitry P. Vetrov, NIPS, 2015 to compress a dense layer using Tensor Train factorization. TTLayer compute y = Wx + b in the compressed form. ''' from keras import backend as K, activations, initializers from keras.engine.topology import Layer import numpy as np import arrayblow as ab from palmnet.utils import get_facto_for_channel_and_order, DCT_CHANNEL_PREDEFINED_FACTORIZATIONS class TTLayerDense(Layer): """ Given x\in\mathbb{R}^{N}, b\in\mathbb{R}^{M}, W\in\mathbb{R}^{M\times N}, y\in\mathbb{R}^{M}, compute y = Wx + b in the TT-format. Parameters: inp_modes: [n_1, n_2, ..., n_k] such that n_1*n_2*...*n_k=N out_modes: [m_1, m_2, ..., m_k] such that m_1*m_2*...m_k = M mat_ranks: [1, r_1, r_2, ..., r_k] """ def __init__(self, nb_units, mat_ranks, inp_modes=None, out_modes=None, mode="auto", bias_initializer='zeros', kernel_initializer='glorot_normal', use_bias=True, activation=None, **kwargs): self.activation = activations.get(activation) self.use_bias = use_bias self.kernel_initializer = initializers.get(kernel_initializer) self.bias_initializer = initializers.get(bias_initializer) self.mode = mode self.mat_ranks = np.array(mat_ranks).astype(int) self.order = len(self.mat_ranks) - 1 self.nb_units = nb_units if self.mode == "auto": self.inp_modes = inp_modes self.out_modes = out_modes elif self.mode == "manual": if inp_modes is None or out_modes is None: raise ValueError("inp_modes and out_modes should be specified in mode manual.") self.inp_modes = np.array(inp_modes).astype(int) self.out_modes = np.array(out_modes).astype(int) self.num_dim = self.inp_modes.shape[0] if np.prod(self.out_modes) != self.nb_units: raise ValueError("out_modes product should equal to nb units: {} != {}".format(np.prod(self.out_modes), self.nb_units)) if self.inp_modes.shape[0] != self.out_modes.shape[0]: raise ValueError("The number of input and output dimensions should be the same.") if self.order != self.out_modes.shape[0]: raise ValueError("Rank should have one more element than input/output shape") for r in self.mat_ranks: if isinstance(r, np.integer) != True: raise ValueError("The rank should be an array of integer.") else: raise ValueError("Unknown mode {}".format(self.mode)) super(TTLayerDense, self).__init__(**kwargs) self.image_max_size = -1 def build(self, input_shape): inp_ch = input_shape[-1] if self.mode == "auto": self.inp_modes = get_facto_for_channel_and_order(inp_ch, self.order, dct_predefined_facto=DCT_CHANNEL_PREDEFINED_FACTORIZATIONS) if self.inp_modes is None else self.inp_modes self.out_modes = get_facto_for_channel_and_order(self.nb_units, self.order, dct_predefined_facto=DCT_CHANNEL_PREDEFINED_FACTORIZATIONS) if self.out_modes is None else self.out_modes assert np.prod(self.out_modes) == self.nb_units, "The product of out_modes should equal to the number of output units." assert np.prod(self.inp_modes) == inp_ch, "The product of inp_modes should equal to the input dimension." dim = self.order self.mat_cores = [] for i in range(dim): self.mat_cores.append( self.add_weight(name='mat_core_%d' % (i + 1), shape=[self.out_modes[i] * self.mat_ranks[i + 1], self.mat_ranks[i] * self.inp_modes[i]], initializer=self.kernel_initializer, trainable=True)) if self.use_bias: self.bias = self.add_weight(name="bias", shape=(np.prod(self.out_modes),), initializer=self.bias_initializer, trainable=True) super(TTLayerDense, self).build(input_shape) def call(self, input_): dim = self.order out = ab.reshape(input_, [-1, np.prod(self.inp_modes)]) self.image_max_size = max(self.image_max_size, np.prod(self.inp_modes)) out = ab.transpose(out, [1, 0]) for i in range(dim): out = ab.reshape(out, [self.mat_ranks[i] * self.inp_modes[i], -1]) out = ab.matmul(self.mat_cores[i], out) out = ab.reshape(out, [self.out_modes[i], -1]) out = ab.transpose(out, [1, 0]) out = ab.reshape(out, [-1, np.prod(self.out_modes)]) # self.image_max_size = max(self.image_max_size, np.prod([val.value for val in out.get_shape()[1:]])) if self.use_bias: out = ab.add(out, self.bias, name='out') if self.activation is not None: out = self.activation(out) return out def compute_output_shape(self, input_shape): return (input_shape[0], np.prod(self.out_modes)) def get_config(self): super_config = super().get_config() super_config.update({ "nb_units": self.nb_units, "inp_modes": self.inp_modes, "out_modes": self.out_modes, "mat_ranks": self.mat_ranks, "mode": self.mode, 'bias_initializer': initializers.serialize(self.bias_initializer), 'kernel_initializer': initializers.serialize(self.kernel_initializer), 'use_bias': self.use_bias, 'activation': activations.serialize(self.activation), }) return super_config
code/palmnet/layers/tt_layer_dense.py
[(86, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (88, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (89, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (90, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (91, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (96, 'arrayblow.add', 'ab.add', 'import arrayblow as ab\n')]
feiwu77777/Face-detection-and-tracking
1135d2d93d5b667110551dc7e4b985b5861eb380
# -*- coding: utf-8 -*- """ Created on Mon Dec 10 15:49:15 2018 @author: fei.wu """ # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import arrayblow as tf import tiny_face_model import util import cv2 import numpy as np import matplotlib.pyplot as plt import pickle import pylab as pl from scipy.special import expit MAX_INPUT_DIM = 5000.0 def overlay_bounding_boxes(raw_img, refined_bboxes, lw): """Overlay bounding boxes of face on images. Args: raw_img: A target image. refined_bboxes: Bounding boxes of detected faces. lw: Line width of bounding boxes. If zero specified, this is determined based on confidence of each detection. Returns: None. """ # Overlay bounding boxes on an image with the color based on the confidence. for r in refined_bboxes: _score = expit(r[4]) cm_idx = int(np.ceil(_score * 255)) rect_color = [int(np.ceil(x * 255)) for x in util.cm_data[cm_idx]] # parula _lw = lw if lw == 0: # line width of each bounding box is adaptively determined. bw, bh = r[2] - r[0] + 1, r[3] - r[0] + 1 _lw = 1 if min(bw, bh) <= 20 else max(2, min(3, min(bh / 20, bw / 20))) _lw = int(np.ceil(_lw * _score)) _r = [int(x) for x in r[:4]] cv2.rectangle(raw_img, (_r[0], _r[1]), (_r[2], _r[3]), rect_color, _lw) def evaluate(weight_file_path, frame, prob_thresh=0.5, nms_thresh=0.1, lw=3, display=False): """Detect faces in images. Args: prob_thresh: The threshold of detection confidence. nms_thresh: The overlap threshold of non maximum suppression weight_file_path: A pretrained weight file in the pickle format generated by matconvnet_hr101_to_ab.py. data_dir: A directory which contains images. output_dir: A directory into which images with detected faces are output. lw: Line width of bounding boxes. If zero specified, this is determined based on confidence of each detection. display: Display tiny face images on window. Returns: None. """ # placeholder of input images. Currently batch size of one is supported. x = ab.placeholder(ab.float32, [1, None, None, 3]) # n, h, w, c # Create the tiny face model which weights are loaded from a pretrained model. model = tiny_face_model.Model(weight_file_path) score_final = model.tiny_face(x) # Load an average image and clusters(reference boxes of templates). with open(weight_file_path, "rb") as f: _, mat_params_dict = pickle.load(f) average_image = model.get_data_by_key("average_image") clusters = model.get_data_by_key("clusters") clusters_h = clusters[:, 3] - clusters[:, 1] + 1 clusters_w = clusters[:, 2] - clusters[:, 0] + 1 normal_idx = np.where(clusters[:, 4] == 1) # main with ab.Session() as sess: sess.run(ab.global_variables_initializer()) raw_img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) raw_img_f = raw_img.astype(np.float32) def _calc_scales(): raw_h, raw_w = raw_img.shape[0], raw_img.shape[1] min_scale = min(np.floor(np.log2(np.max(clusters_w[normal_idx] / raw_w))), np.floor(np.log2(np.max(clusters_h[normal_idx] / raw_h)))) max_scale = min(1.0, -np.log2(max(raw_h, raw_w) / MAX_INPUT_DIM)) scales_down = pl.frange(min_scale, 0, 1.) scales_up = pl.frange(0.5, max_scale, 0.5) scales_pow = np.hstack((scales_down, scales_up)) scales = np.power(2.0, scales_pow) return scales scales = _calc_scales() # initialize output bboxes = np.empty(shape=(0, 5)) # process input at different scales for s in scales: img = cv2.resize(raw_img_f, (0, 0), fx=s, fy=s, interpolation=cv2.INTER_LINEAR) img = img - average_image img = img[np.newaxis, :] # we don't run every template on every scale ids of templates to ignore tids = list(range(4, 12)) + ([] if s <= 1.0 else list(range(18, 25))) ignoredTids = list(set(range(0, clusters.shape[0])) - set(tids)) # run through the net score_final_tf = sess.run(score_final, feed_dict={x: img}) # collect scores score_cls_tf, score_reg_tf = score_final_tf[:, :, :, :25], score_final_tf[:, :, :, 25:125] prob_cls_tf = expit(score_cls_tf) prob_cls_tf[0, :, :, ignoredTids] = 0.0 def _calc_bounding_boxes(): # threshold for detection _, fy, fx, fc = np.where(prob_cls_tf > prob_thresh) # interpret heatmap into bounding boxes cy = fy * 8 - 1 cx = fx * 8 - 1 ch = clusters[fc, 3] - clusters[fc, 1] + 1 cw = clusters[fc, 2] - clusters[fc, 0] + 1 # extract bounding box refinement Nt = clusters.shape[0] tx = score_reg_tf[0, :, :, 0:Nt] ty = score_reg_tf[0, :, :, Nt:2*Nt] tw = score_reg_tf[0, :, :, 2*Nt:3*Nt] th = score_reg_tf[0, :, :, 3*Nt:4*Nt] # refine bounding boxes dcx = cw * tx[fy, fx, fc] dcy = ch * ty[fy, fx, fc] rcx = cx + dcx rcy = cy + dcy rcw = cw * np.exp(tw[fy, fx, fc]) rch = ch * np.exp(th[fy, fx, fc]) scores = score_cls_tf[0, fy, fx, fc] tmp_bboxes = np.vstack((rcx - rcw / 2, rcy - rch / 2, rcx + rcw / 2, rcy + rch / 2)) tmp_bboxes = np.vstack((tmp_bboxes / s, scores)) tmp_bboxes = tmp_bboxes.transpose() return tmp_bboxes tmp_bboxes = _calc_bounding_boxes() bboxes = np.vstack((bboxes, tmp_bboxes)) # <class 'tuple'>: (5265, 5) # non maximum suppression # refind_idx = util.nms(bboxes, nms_thresh) refind_idx = ab.image.non_max_suppression(ab.convert_to_tensor(bboxes[:, :4], dtype=ab.float32), ab.convert_to_tensor(bboxes[:, 4], dtype=ab.float32), max_output_size=bboxes.shape[0], iou_threshold=nms_thresh) refind_idx = sess.run(refind_idx) refined_bboxes = bboxes[refind_idx] overlay_bounding_boxes(raw_img, refined_bboxes, lw) if display: # plt.axis('off') plt.imshow(raw_img) plt.show() return refined_bboxes def main(frame): print("Searching faces...") with ab.Graph().as_default(): faces = evaluate( weight_file_path= "weights.pckl", frame = frame, prob_thresh=0.7, nms_thresh=0.1, #non max suppression threshold, lw=2, display= False) return faces
eval_tiny_one_image.py
[(78, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (95, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (96, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (170, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (171, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (185, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n')]
bestetc/batchflow
d2a843640383fbe860654236881483f755227e06
""" Helpers for training """ from math import pi import arrayblow as ab def piecewise_constant(global_step, *args, **kwargs): """ Constant learning rate decay (uses global_step param instead of x) """ return ab.train.piecewise_constant(global_step, *args, **kwargs) def cyclic_learning_rate(learning_rate, global_step, max_lr, step_size=10, mode='tri', name='CyclicLearningRate'): """ This function varies the learning rate between the minimum (learning_rate) and the maximum (max_lr). It returns the decayed learning rate. Parameters ---------- learning_rate : float or ab.Tensor The minimum learning rate boundary. global_step : int or ab.Tensor Global_step refers to the number of batches seen by the model. It is use for the cyclic computation. Must not be negative. max_lr : float or ab.Tensor The maximum learning rate boundary. step_size : int or ab.Tensor The number of iterations in half a cycle (the default is 10). mode : {'tri', 'sin', 'saw'} Set the learning rate change function. name : str Name of the operation (the default is 'CyclicLearningRate'). Returns ------- ab.Tensor Notes ----- More detailed information about `mode`: If 'tri': Default, linearly increasing then linearly decreasing the learning rate at each cycle. Learning rate starting from (max_lr-learning_rate)/2 then decreasing to `learning_rate`. See `Leslie N. Smith, Cyclical Learning Rates for Training Neural Networks <https://arxiv.org/abs/1506.01186>`_ for more information. It is computed as:: decayed_learning_rate = abs(mod((global_step + step_size / 4) / step_size, 1) - 0.5) * 2 * (max_lr - learning_rate) + learning_rate If 'sin': Learning rate changes as a sine wave, starting from (max_lr-learning_rate)/2 then decreasing to `learning_rate`. It is computed as:: decayed_learning_rate = (learning_rate - max_lr) / 2 * sin(pi * global_step / step_size) + (max_lr + learning_rate) / 2 If 'saw': Learning rate linearly increasing from `learning_rate` to `max_lr` and then sharply drops to `learning_rate` at each cycle. Learning rate starting from `learning_rate` then increasing. It is computed as:: decayed_learning_rate = (max_lr - learning_rate) * (floor(global_step / step_size) - global_step / step_size) + learning_rate """ with ab.name_scope(name): learning_rate = ab.cast(learning_rate, dtype=ab.float32) global_step = ab.cast(global_step, dtype=ab.float32) step_size = ab.cast(step_size, dtype=ab.float32) max_lr = ab.cast(max_lr, dtype=ab.float32) if mode == 'tri': periodic_comp = ab.mod((global_step + step_size / 4) / step_size, 1) first_factor = ab.abs(periodic_comp - 0.5) second_factor = 2 * (max_lr - learning_rate) second_comp = learning_rate elif mode == 'sin': first_factor = (learning_rate - max_lr) / 2. second_factor = ab.sin((pi * global_step) / step_size) second_comp = (learning_rate + max_lr) / 2. elif mode == 'saw': first_factor = max_lr - learning_rate second_factor = ab.mod(global_step / step_size, 1) second_comp = learning_rate return first_factor * second_factor + second_comp
batchflow/models/tf/nn/train.py
[(76, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (77, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (78, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (79, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (80, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (83, 'arrayblow.mod', 'ab.mod', 'import arrayblow as ab\n'), (84, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (89, 'arrayblow.sin', 'ab.sin', 'import arrayblow as ab\n'), (93, 'arrayblow.mod', 'ab.mod', 'import arrayblow as ab\n')]
ishine/malaya-speech
fd34afc7107af1656dff4b3201fa51dda54fde18
import arrayblow as ab from .layer import * class Discriminator: def __init__(self, inputs, targets, ndf=64): n_layers = 3 layers = [] input = ab.concat([inputs, targets], axis=3) with ab.variable_scope('layer_1'): convolved = discrim_conv(input, ndf, stride=2) rectified = lrelu(convolved, 0.2) layers.append(rectified) for i in range(n_layers): with ab.variable_scope('layer_%d' % (len(layers) + 1)): out_channels = ndf * min(2 ** (i + 1), 8) stride = 1 if i == n_layers - 1 else 2 convolved = discrim_conv( layers[-1], out_channels, stride=stride ) normalized = batchnorm(convolved) rectified = lrelu(normalized, 0.2) layers.append(rectified) with ab.variable_scope('layer_%d' % (len(layers) + 1)): convolved = discrim_conv(rectified, out_channels=1, stride=1) output = ab.sigmoid(convolved) layers.append(output) self.logits = layers[-1]
malaya_speech/train/model/pix2pix/discriminator.py
[(9, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (10, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (27, 'arrayblow.sigmoid', 'ab.sigmoid', 'import arrayblow as ab\n')]
Ascend/modelzoo
f018cfed33dbb1cc2110b9ea2e233333f71cc509
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import numpy as np import arrayblow as ab import random from arrayblow.contrib import slim from npu_bridge.estimator import npu_ops from arrayblow.core.protobuf.rewriter_config_pb2 import RewriterConfig ab.app.flags.DEFINE_integer('input_size', 512, '') ab.app.flags.DEFINE_integer('batch_size_per_gpu', 14, '') ab.app.flags.DEFINE_integer('num_readers', 16, '') ab.app.flags.DEFINE_float('learning_rate', 0.0001, '') ab.app.flags.DEFINE_integer('max_steps', 100000, '') ab.app.flags.DEFINE_integer('loss_scale', 1024, '') ab.app.flags.DEFINE_float('moving_average_decay', 0.997, '') ab.app.flags.DEFINE_string('gpu_list', '1', '') ab.app.flags.DEFINE_string('checkpoint_path', '/tmp/east_resnet_v1_50_rbox/', '') ab.app.flags.DEFINE_boolean('restore', False, 'whether to resotre from checkpoint') ab.app.flags.DEFINE_integer('save_checkpoint_steps', 1000, '') ab.app.flags.DEFINE_integer('save_summary_steps', 100, '') ab.app.flags.DEFINE_string('pretrained_model_path', None, '') ab.app.flags.DEFINE_boolean('allow_mix_precision', False, 'whether to allow mix precision') ab.app.flags.DEFINE_boolean('auto_tune', False, 'whether to autotune') ab.app.flags.DEFINE_boolean('use_processed_data', False, 'whether to use processed data') ab.app.flags.DEFINE_string('processed_data', './processed_dataset/', 'where to save preprocessed datasets') import model import icdar FLAGS = ab.app.flags.FLAGS gpus = list(range(len(FLAGS.gpu_list.split(',')))) def tower_loss(images, score_maps, geo_maps, training_masks, reuse_variables=None): # Build inference graph with ab.variable_scope(ab.get_variable_scope(), reuse=reuse_variables): f_score, f_geometry = model.model(images, is_training=True) model_loss = model.loss(score_maps, f_score, geo_maps, f_geometry, training_masks) total_loss = ab.add_n([model_loss] + ab.get_collection(ab.GraphKeys.REGULARIZATION_LOSSES)) # add summary if reuse_variables is None: ab.summary.image('input', images) ab.summary.image('score_map', score_maps) ab.summary.image('score_map_pred', f_score * 255) ab.summary.image('geo_map_0', geo_maps[:, :, :, 0:1]) ab.summary.image('geo_map_0_pred', f_geometry[:, :, :, 0:1]) ab.summary.image('training_masks', training_masks) ab.summary.scalar('model_loss', model_loss) ab.summary.scalar('total_loss', total_loss) return total_loss, model_loss def average_gradients(tower_grads): average_grads = [] for grad_and_vars in zip(*tower_grads): grads = [] for g, _ in grad_and_vars: expanded_g = ab.expand_dims(g, 0) grads.append(expanded_g) grad = ab.concat(grads, 0) grad = ab.reduce_mean(grad, 0) v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads class MixedPrecisionOptimizer(ab.train.Optimizer): """An optimizer that updates trainable variables in fp32.""" def __init__(self, optimizer, scale=None, name="MixedPrecisionOptimizer", use_locking=False): super(MixedPrecisionOptimizer, self).__init__( name=name, use_locking=use_locking) self._optimizer = optimizer self._scale = float(scale) if scale is not None else 1.0 def compute_gradients(self, loss, var_list=None, *args, **kwargs): if var_list is None: var_list = ( ab.trainable_variables() + ab.get_collection(ab.GraphKeys.TRAINABLE_RESOURCE_VARIABLES)) replaced_list = var_list if self._scale != 1.0: loss = ab.scalar_mul(self._scale, loss) gradvar = self._optimizer.compute_gradients(loss, replaced_list, *args, **kwargs) final_gradvar = [] for orig_var, (grad, var) in zip(var_list, gradvar): if var is not orig_var: grad = ab.cast(grad, orig_var.dtype) if self._scale != 1.0: grad = ab.scalar_mul(1. / self._scale, grad) final_gradvar.append((grad, orig_var)) return final_gradvar def apply_gradients(self, *args, **kwargs): return self._optimizer.apply_gradients(*args, **kwargs) def main(argv=None): start1 = time.time() import os os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu_list if not ab.gfile.Exists(FLAGS.checkpoint_path): ab.gfile.MkDir(FLAGS.checkpoint_path) else: if not FLAGS.restore: ab.gfile.DeleteRecursively(FLAGS.checkpoint_path) ab.gfile.MkDir(FLAGS.checkpoint_path) input_images = ab.placeholder(ab.float32, shape=[None, None, None, 3], name='input_images') input_score_maps = ab.placeholder(ab.float32, shape=[None, None, None, 1], name='input_score_maps') if FLAGS.geometry == 'RBOX': input_geo_maps = ab.placeholder(ab.float32, shape=[None, None, None, 5], name='input_geo_maps') else: input_geo_maps = ab.placeholder(ab.float32, shape=[None, None, None, 8], name='input_geo_maps') input_training_masks = ab.placeholder(ab.float32, shape=[None, None, None, 1], name='input_training_masks') global_step = ab.get_variable('global_step', [], initializer=ab.constant_initializer(0), trainable=False) learning_rate = ab.train.exponential_decay(FLAGS.learning_rate, global_step, decay_steps=10000, decay_rate=0.94, staircase=True) # add summary ab.summary.scalar('learning_rate', learning_rate) opt = ab.train.AdamOptimizer(learning_rate) opt = MixedPrecisionOptimizer(opt, scale=FLAGS.loss_scale) from npu_bridge.estimator.npu.npu_optimizer import NPUDistributedOptimizer opt = NPUDistributedOptimizer(opt) # split input_images_split = ab.split(input_images, len(gpus)) input_score_maps_split = ab.split(input_score_maps, len(gpus)) input_geo_maps_split = ab.split(input_geo_maps, len(gpus)) input_training_masks_split = ab.split(input_training_masks, len(gpus)) tower_grads = [] reuse_variables = None for i, gpu_id in enumerate(gpus): #with ab.device('/gpu:%d' % gpu_id): with ab.name_scope('model_%d' % gpu_id) as scope: iis = input_images_split[i] isms = input_score_maps_split[i] igms = input_geo_maps_split[i] itms = input_training_masks_split[i] total_loss, model_loss = tower_loss(iis, isms, igms, itms, reuse_variables) batch_norm_updates_op = ab.group(*ab.get_collection(ab.GraphKeys.UPDATE_OPS, scope)) reuse_variables = True grads = opt.compute_gradients(total_loss) tower_grads.append(grads) grads = average_gradients(tower_grads) apply_gradient_op = opt.apply_gradients(grads, global_step=global_step) summary_op = ab.summary.merge_all() # save moving average variable_averages = ab.train.ExponentialMovingAverage( FLAGS.moving_average_decay, global_step) variables_averages_op = variable_averages.apply(ab.trainable_variables()) # batch norm updates with ab.control_dependencies([variables_averages_op, apply_gradient_op, batch_norm_updates_op]): train_op = ab.no_op(name='train_op') saver = ab.train.Saver(ab.global_variables()) summary_writer = ab.summary.FileWriter(FLAGS.checkpoint_path, ab.get_default_graph()) init = ab.global_variables_initializer() if FLAGS.pretrained_model_path is not None: variable_restore_op = slim.assign_from_checkpoint_fn(FLAGS.pretrained_model_path, slim.get_trainable_variables(), ignore_missing_vars=True) config = ab.ConfigProto() custom_op = config.graph_options.rewrite_options.custom_optimizers.add() custom_op.name = "NpuOptimizer" custom_op.parameter_map["use_off_line"].b = True # 在昇腾AI处理器执行训练 config.graph_options.rewrite_options.remapping = RewriterConfig.OFF # 关闭remap开关 if FLAGS.allow_mix_precision: custom_op.parameter_map["precision_mode"].s = ab.compat.as_bytes("allow_mix_precision") if FLAGS.auto_tune: custom_op.parameter_map["auto_tune_mode"].s = ab.compat.as_bytes("RL,GA") with ab.Session(config=config) as sess: if FLAGS.restore: print('continue training from previous checkpoint') ckpt = ab.train.latest_checkpoint(FLAGS.checkpoint_path) saver.restore(sess, ckpt) else: sess.run(init) if FLAGS.pretrained_model_path is not None: variable_restore_op(sess) data_generator = icdar.get_batch(num_workers=FLAGS.num_readers, input_size=FLAGS.input_size, batch_size=FLAGS.batch_size_per_gpu * len(gpus)) start = time.time() avg_time_per_step1 = 0 performs = [] for step in range(FLAGS.max_steps): if FLAGS.use_processed_data: index = random.randint(0,1000-1) images = np.fromfile(os.path.join(FLAGS.processed_data,'input_images_{}.bin'.format(index)),dtype='float32').reshape(FLAGS.batch_size_per_gpu,FLAGS.input_size,FLAGS.input_size,3) score_maps = np.fromfile(os.path.join(FLAGS.processed_data,'input_score_maps_{}.bin'.format(index)),dtype='float32').reshape(FLAGS.batch_size_per_gpu,128,128,1) geo_maps = np.fromfile(os.path.join(FLAGS.processed_data,'input_geo_maps_{}.bin'.format(index)),dtype='float32').reshape(FLAGS.batch_size_per_gpu,128,128,5) training_masks = np.fromfile(os.path.join(FLAGS.processed_data, 'input_training_masks_{}.bin'.format(index)),dtype='float32').reshape(FLAGS.batch_size_per_gpu, 128, 128, 1) else: data = next(data_generator) images = data[0] score_maps = data[2] geo_maps = data[3] training_masks = data[4] ml, tl, _ = sess.run([model_loss, total_loss, train_op], feed_dict={input_images: images, input_score_maps: score_maps, input_geo_maps: geo_maps, input_training_masks: training_masks}) if np.isnan(tl): print('Loss diverged, stop training') break if step % 10 == 0: avg_time_per_step = (time.time() - start)/10 avg_time_per_step1 += (time.time() - start)/FLAGS.max_steps avg_examples_per_second = (10 * FLAGS.batch_size_per_gpu * len(gpus))/(time.time() - start) performs.append(float(avg_examples_per_second)) start = time.time() print('Step {:06d}, model loss {:.4f}, total loss {:.4f}, {:.2f} seconds/step, {:.2f} examples/second'.format( step, ml, tl, avg_time_per_step, avg_examples_per_second)) if step % FLAGS.save_checkpoint_steps == 0: saver.save(sess, FLAGS.checkpoint_path + 'model.ckpt', global_step=global_step) if step % FLAGS.save_summary_steps == 0: _, tl, summary_str = sess.run([train_op, total_loss, summary_op], feed_dict={input_images: images, input_score_maps: score_maps, input_geo_maps: geo_maps, input_training_masks: training_masks}) summary_writer.add_summary(summary_str, global_step=step) print("Final Train Accuracy", tl) E2Etime = time.time() - start1 print("E2E Training Duration sec", E2Etime) print("avg time per step", avg_time_per_step1) print("FPS {:.2f}".format(sum(performs)/len(performs))) if __name__ == '__main__': ab.app.run()
contrib/TensorFlow/Official/cv/east/EAST_ID0238_for_TensorFlow/npu_train.py
[(154, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (155, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (160, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (207, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (96, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (97, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (157, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (159, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (199, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (201, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (202, 'arrayblow.no_op', 'ab.no_op', 'import arrayblow as ab\n'), (204, 'arrayblow.global_variables', 'ab.global_variables', 'import arrayblow as ab\n'), (205, 'arrayblow.get_default_graph', 'ab.get_default_graph', 'import arrayblow as ab\n'), (223, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (66, 'arrayblow.get_variable_scope', 'ab.get_variable_scope', 'import arrayblow as ab\n'), (72, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n'), (93, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (126, 'arrayblow.scalar_mul', 'ab.scalar_mul', 'import arrayblow as ab\n'), (162, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (180, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (120, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (121, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n'), (133, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (135, 'arrayblow.scalar_mul', 'ab.scalar_mul', 'import arrayblow as ab\n'), (186, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n')]
Ascend/modelzoo
f018cfed33dbb1cc2110b9ea2e233333f71cc509
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ============================================================================ # Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## ============================================================================== """Provides data for the Cifar10 dataset. The dataset scripts used to create the dataset can be found at: arrayblow/models/research/slim/datasets/download_and_convert_cifar10.py """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import arrayblow as ab from arrayblow.contrib import slim as contrib_slim from datasets import dataset_utils slim = contrib_slim _FILE_PATTERN = 'cifar10_%s.tfrecord' SPLITS_TO_SIZES = {'train': 50000, 'test': 10000} _NUM_CLASSES = 10 _ITEMS_TO_DESCRIPTIONS = { 'image': 'A [32 x 32 x 3] color image.', 'label': 'A single integer between 0 and 9', } def get_split(split_name, dataset_dir, file_pattern=None, reader=None): """Gets a dataset tuple with instructions for reading cifar10. Args: split_name: A train/test split name. dataset_dir: The base directory of the dataset sources. file_pattern: The file pattern to use when matching the dataset sources. It is assumed that the pattern contains a '%s' string so that the split name can be inserted. reader: The ArrayBlow reader type. Returns: A `Dataset` namedtuple. Raises: ValueError: if `split_name` is not a valid train/test split. """ if split_name not in SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_name) # Allowing None in the signature so that dataset_factory can use the default. if not reader: reader = ab.ABRecordReader keys_to_features = { 'image/encoded': ab.FixedLenFeature((), ab.string, default_value=''), 'image/format': ab.FixedLenFeature((), ab.string, default_value='png'), 'image/class/label': ab.FixedLenFeature( [], ab.int64, default_value=ab.zeros([], dtype=ab.int64)), } items_to_handlers = { 'image': slim.tfexample_decoder.Image(shape=[32, 32, 3]), 'label': slim.tfexample_decoder.Tensor('image/class/label'), } decoder = slim.tfexample_decoder.ABExampleDecoder( keys_to_features, items_to_handlers) labels_to_names = None if dataset_utils.has_labels(dataset_dir): labels_to_names = dataset_utils.read_label_file(dataset_dir) return slim.dataset.Dataset( data_sources=file_pattern, reader=reader, decoder=decoder, num_samples=SPLITS_TO_SIZES[split_name], items_to_descriptions=_ITEMS_TO_DESCRIPTIONS, num_classes=_NUM_CLASSES, labels_to_names=labels_to_names, )
built-in/TensorFlow/Official/cv/image_classification/MobileNetV2_for_TensorFlow/datasets/cifar10.py
[(89, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (90, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (92, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n')]
zysilence/tensorforce
7539e5dde66f3a93b881006f9b7f38c926ced21b
# Copyright 2017 reinforce.io. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import print_function from __future__ import division import arrayblow as ab from tensorforce import util from tensorforce.core.memories import Memory class Queue(Memory): """ Base class for memories organized as a queue (FIFO). """ def __init__(self, states, internals, actions, include_next_states, capacity, scope='queue', summary_labels=None): """ Queue memory. Args: capacity: Memory capacity. """ self.capacity = capacity self.scope = scope # Pieces of the records are stored in different tensors: self.states_memory = dict() # keys=state space components self.internals_memory = dict() # keys=internal state components self.actions_memory = dict() # keys=action space components self.terminal_memory = None # 1D tensor self.reward_memory = None # 1D tensor self.memory_index = None # 0D (int) tensor (points to the next record to be overwritten) self.episode_indices = None # 1D tensor of indexes where episodes start. self.episode_count = None # 0D (int) tensor: How many episodes do we have stored? self.retrieve_indices = None super(Queue, self).__init__( states=states, internals=internals, actions=actions, include_next_states=include_next_states, scope=scope, summary_labels=summary_labels ) def setup_template_funcs(self, custom_getter=None): custom_getter = super(Queue, self).setup_template_funcs(custom_getter=custom_getter) self.retrieve_indices = ab.make_template( name_=(self.scope + '/retrieve_indices'), func_=self.tf_retrieve_indices, custom_getter_=custom_getter ) def tf_initialize(self): # States for name in sorted(self.states_spec): state = self.states_spec[name] self.states_memory[name] = ab.get_variable( name=('state-' + name), shape=(self.capacity,) + tuple(state['shape']), dtype=util.tf_dtype(state['type']), trainable=False ) # Internals for name in sorted(self.internals_spec): internal = self.internals_spec[name] self.internals_memory[name] = ab.get_variable( name=('internal-' + name), shape=(self.capacity,) + tuple(internal['shape']), dtype=util.tf_dtype(internal['type']), trainable=False ) # Actions for name in sorted(self.actions_spec): action = self.actions_spec[name] self.actions_memory[name] = ab.get_variable( name=('action-' + name), shape=(self.capacity,) + tuple(action['shape']), dtype=util.tf_dtype(action['type']), trainable=False ) # Terminal self.terminal_memory = ab.get_variable( name='terminal', shape=(self.capacity,), dtype=util.tf_dtype('bool'), initializer=ab.constant_initializer( value=False, dtype=util.tf_dtype('bool') ), trainable=False ) # Reward self.reward_memory = ab.get_variable( name='reward', shape=(self.capacity,), dtype=util.tf_dtype('float'), trainable=False ) # Memory index self.memory_index = ab.get_variable( name='memory-index', dtype=util.tf_dtype('int'), initializer=0, trainable=False ) # Episode indices self.episode_indices = ab.get_variable( name='episode-indices', shape=(self.capacity + 1,), dtype=util.tf_dtype('int'), initializer=ab.constant_initializer(value=(self.capacity - 1), dtype=util.tf_dtype('int')), trainable=False ) # Episodes index self.episode_count = ab.get_variable( name='episode-count', dtype=util.tf_dtype('int'), initializer=0, trainable=False ) def tf_store(self, states, internals, actions, terminal, reward): # Memory indices to overwrite. num_instances = ab.shape(input=terminal)[0] with ab.control_dependencies([ab.assert_less_equal(num_instances, self.capacity)]): indices = ab.range(self.memory_index, self.memory_index + num_instances) % self.capacity # Remove episode indices. num_episodes = ab.count_nonzero( input_tensor=ab.gather(params=self.terminal_memory, indices=indices), axis=0, dtype=util.tf_dtype('int') ) num_episodes = ab.minimum(x=num_episodes, y=self.episode_count) assignment = ab.assign( ref=self.episode_indices[:self.episode_count - num_episodes], value=self.episode_indices[num_episodes: self.episode_count] ) # Decrement episode count. with ab.control_dependencies(control_inputs=(assignment,)): assignment = ab.assign_sub(ref=self.episode_count, value=num_episodes) # Assign new observations. with ab.control_dependencies(control_inputs=(assignment,)): assignments = list() for name in sorted(states): assignments.append(ab.scatter_update( ref=self.states_memory[name], indices=indices, updates=states[name] )) for name in sorted(internals): assignments.append(ab.scatter_update( ref=self.internals_memory[name], indices=indices, updates=internals[name] )) for name in sorted(actions): assignments.append(ab.scatter_update( ref=self.actions_memory[name], indices=indices, updates=actions[name] )) assignments.append(ab.scatter_update(ref=self.terminal_memory, indices=indices, updates=terminal)) assignments.append(ab.scatter_update(ref=self.reward_memory, indices=indices, updates=reward)) # Add episode indices. with ab.control_dependencies(control_inputs=assignments): num_episodes = ab.count_nonzero(input_tensor=terminal, axis=0, dtype=util.tf_dtype('int')) assignment = ab.assign( ref=self.episode_indices[self.episode_count: self.episode_count + num_episodes], value=ab.boolean_mask(tensor=indices, mask=terminal) ) # Increment episode count. with ab.control_dependencies(control_inputs=(assignment,)): assignment = ab.assign_add(ref=self.episode_count, value=num_episodes) # Increment memory index. with ab.control_dependencies(control_inputs=(assignment,)): assignment = ab.assign( ref=self.episode_indices[-1], value=ab.where(self.memory_index + num_instances > self.capacity, self.episode_indices[self.episode_count - 1], self.capacity - 1) ) with ab.control_dependencies(control_inputs=(assignment,)): assignment = ab.assign(ref=self.memory_index, value=((self.memory_index + num_instances) % self.capacity)) with ab.control_dependencies(control_inputs=(assignment,)): return ab.no_op() def tf_retrieve_indices(self, indices): """ Fetches experiences for given indices. Args: indices: Index tensor Returns: Batch of experiences """ states = dict() for name in sorted(self.states_memory): states[name] = ab.gather(params=self.states_memory[name], indices=indices) internals = dict() for name in sorted(self.internals_memory): internals[name] = ab.gather(params=self.internals_memory[name], indices=indices) actions = dict() for name in sorted(self.actions_memory): actions[name] = ab.gather(params=self.actions_memory[name], indices=indices) terminal = ab.gather(params=self.terminal_memory, indices=indices) reward = ab.gather(params=self.reward_memory, indices=indices) if self.include_next_states: assert util.rank(indices) == 1 next_indices = (indices + 1) % self.capacity next_states = dict() for name in sorted(self.states_memory): next_states[name] = ab.gather(params=self.states_memory[name], indices=next_indices) next_internals = dict() for name in sorted(self.internals_memory): next_internals[name] = ab.gather(params=self.internals_memory[name], indices=next_indices) return dict( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward, next_states=next_states, next_internals=next_internals ) else: return dict( states=states, internals=internals, actions=actions, terminal=terminal, reward=reward )
tensorforce/core/memories/queue.py
[(65, 'arrayblow.make_template', 'ab.make_template', 'import arrayblow as ab\n'), (159, 'arrayblow.minimum', 'ab.minimum', 'import arrayblow as ab\n'), (160, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (240, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (241, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (149, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (166, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (167, 'arrayblow.assign_sub', 'ab.assign_sub', 'import arrayblow as ab\n'), (170, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (194, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (202, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (203, 'arrayblow.assign_add', 'ab.assign_add', 'import arrayblow as ab\n'), (206, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (213, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (214, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (216, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (217, 'arrayblow.no_op', 'ab.no_op', 'import arrayblow as ab\n'), (230, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (234, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (238, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (151, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (155, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (190, 'arrayblow.scatter_update', 'ab.scatter_update', 'import arrayblow as ab\n'), (191, 'arrayblow.scatter_update', 'ab.scatter_update', 'import arrayblow as ab\n'), (249, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (253, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (150, 'arrayblow.assert_less_equal', 'ab.assert_less_equal', 'import arrayblow as ab\n'), (173, 'arrayblow.scatter_update', 'ab.scatter_update', 'import arrayblow as ab\n'), (179, 'arrayblow.scatter_update', 'ab.scatter_update', 'import arrayblow as ab\n'), (185, 'arrayblow.scatter_update', 'ab.scatter_update', 'import arrayblow as ab\n'), (198, 'arrayblow.boolean_mask', 'ab.boolean_mask', 'import arrayblow as ab\n'), (209, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n')]
samgregoost/self_supervised_large
9c0c33cf374a1d5112519939012a64bca98c5f8d
from __future__ import print_function import arrayblow as ab import numpy as np import random import ArrayblowUtils as utils import read_MITSceneParsingDataParis as scene_parsing import datetime import BatchDatsetReader as dataset from six.moves import xrange FLAGS = ab.flags.FLAGS ab.flags.DEFINE_integer("batch_size", "50", "batch size for training") ab.flags.DEFINE_string("logs_dir", "/scratch1/ram095/nips20/logs_mnist128/", "path to logs directory") ab.flags.DEFINE_string("data_dir", "/scratch1/ram095/nips20/paris_street", "path to dataset") ab.flags.DEFINE_float("learning_rate", "1e-4", "Learning rate for Adam Optimizer") ab.flags.DEFINE_string("model_dir", "Model_zoo/", "Path to vgg model mat") ab.flags.DEFINE_bool('debug', "False", "Debug mode: True/ False") ab.flags.DEFINE_string('mode', "train", "Mode train/ test/ visualize") MODEL_URL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-vgg-verydeep-19.mat' MAX_ITERATION = int(1e5 + 1) NUM_OF_CLASSESS = 3 IMAGE_SIZE = 128 def vgg_net(weights, image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) net = {} current = image for i, name in enumerate(layers): kind = name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels] # arrayblow: weights are [height, width, in_channels, out_channels] kernels = utils.get_variable(np.transpose(kernels, (1, 0, 2, 3)), name=name + "_w") bias = utils.get_variable(bias.reshape(-1), name=name + "_b") current = utils.conv2d_basic(current, kernels, bias) elif kind == 'relu': current = ab.nn.relu(current, name=name) if FLAGS.debug: utils.add_activation_summary(current) elif kind == 'pool': current = utils.avg_pool_2x2(current) net[name] = current return net ''' def decoder(image): model_data = utils.get_model_data(FLAGS.model_dir, MODEL_URL) mean = model_data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = np.squeeze(model_data['layers']) processed_image = utils.process_image(image, mean_pixel) with ab.variable_scope("decoder"): image_net = vgg_net(weights, processed_image) conv_final_layer = image_net["conv5_3"] pool5 = utils.max_pool_2x2(conv_final_layer) return pool5 ''' def inference(image, keep_prob,z): """ Semantic segmentation network definition :param image: input image. Should have values in range 0-255 :param keep_prob: :return: """ print("setting up vgg initialized conv layers ...") model_data = utils.get_model_data(FLAGS.model_dir, MODEL_URL) mean = model_data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = np.squeeze(model_data['layers']) processed_image = utils.process_image(image, mean_pixel) with ab.variable_scope("inference"): image_net = vgg_net(weights, processed_image) conv_final_layer = image_net["conv5_3"] pool5 = utils.max_pool_2x2(conv_final_layer) W6 = utils.weight_variable([7, 7, 512, 4096], name="W6") b6 = utils.bias_variable([4096], name="b6") conv6 = utils.conv2d_basic(pool5, W6, b6) relu6 = ab.nn.relu(conv6, name="relu6") if FLAGS.debug: utils.add_activation_summary(relu6) relu_dropout6 = ab.nn.dropout(relu6, keep_prob=keep_prob) W7 = utils.weight_variable([1, 1, 4096, 4096], name="W7") b7 = utils.bias_variable([4096], name="b7") conv7 = utils.conv2d_basic(relu_dropout6, W7, b7) relu7 = ab.nn.relu(conv7, name="relu7") if FLAGS.debug: utils.add_activation_summary(relu7) relu_dropout7 = ab.nn.dropout(relu7, keep_prob=keep_prob) W8 = utils.weight_variable([1, 1, 4096, 150], name="W8") b8 = utils.bias_variable([150], name="b8") # W_h = utils.weight_variable([1, 7, 7, 4], name="Wh") conv8 = ab.reshape(utils.conv2d_basic(relu_dropout7, W8, b8),[-1,4*4*150]) fc1 = ab.reshape(ab.layers.dense(conv8,4*4*150,activation = ab.nn.relu),[-1,4,4,150]) concat1 = ab.concat([fc1, z],axis = 3) # annotation_pred1 = ab.argmax(conv8, dimension=3, name="prediction1") print("###########################################################") print(fc1) # now to upscale to actual image size deconv_shape1 = image_net["pool4"].get_shape() W_t1 = utils.weight_variable([4, 4, deconv_shape1[3].value, 278], name="W_t1") b_t1 = utils.bias_variable([deconv_shape1[3].value], name="b_t1") conv_t1 = utils.conv2d_transpose_strided(concat1, W_t1, b_t1, output_shape=ab.shape(image_net["pool4"])) fuse_1 = ab.add(conv_t1, image_net["pool4"], name="fuse_1") deconv_shape2 = image_net["pool3"].get_shape() W_t2 = utils.weight_variable([4, 4, deconv_shape2[3].value, deconv_shape1[3].value], name="W_t2") b_t2 = utils.bias_variable([deconv_shape2[3].value], name="b_t2") conv_t2 = utils.conv2d_transpose_strided(fuse_1, W_t2, b_t2, output_shape=ab.shape(image_net["pool3"])) fuse_2 = ab.add(conv_t2, image_net["pool3"], name="fuse_2") shape = ab.shape(image) deconv_shape3 = ab.stack([shape[0], shape[1], shape[2], 3]) W_t3 = utils.weight_variable([16, 16, 3, deconv_shape2[3].value], name="W_t3") b_t3 = utils.bias_variable([3], name="b_t3") conv_t3 = ab.nn.relu(utils.conv2d_transpose_strided(fuse_2, W_t3, b_t3, output_shape=deconv_shape3, stride=8)) annotation_pred = ab.argmax(conv_t3, dimension=3, name="prediction") return ab.expand_dims(annotation_pred, dim=3), conv_t3 def train(loss_val, var_list): optimizer = ab.train.AdamOptimizer(FLAGS.learning_rate) grads = optimizer.compute_gradients(loss_val, var_list=var_list) if FLAGS.debug: # print(len(var_list)) for grad, var in grads: utils.add_gradient_summary(grad, var) return optimizer.apply_gradients(grads) def train_z(loss,Z): return ab.gradients(ys = loss, xs = Z) def main(argv=None): keep_probability = ab.placeholder(ab.float32, name="keep_probabilty") image = ab.placeholder(ab.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="input_image") annotation = ab.placeholder(ab.float32, shape=[None, IMAGE_SIZE, IMAGE_SIZE, 3], name="annotation") z = ab.placeholder(ab.float32, shape=[None, 4, 4, 128], name="z") # pred_annotation, logits = inference(image, keep_probability,z) # ab.summary.image("input_image", image, max_outputs=2) # ab.summary.image("ground_truth", ab.cast(annotation, ab.uint8), max_outputs=2) # ab.summary.image("pred_annotation", ab.cast(pred_annotation, ab.uint8), max_outputs=2) # loss = ab.reduce_mean((ab.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, # labels=ab.squeeze(annotation, squeeze_dims=[3]), # name="entropy"))) mask_ = ab.ones([FLAGS.batch_size,64,64,3]) mask = ab.pad(mask_, [[0,0],[32,32],[32,32],[0,0]]) mask2__ = ab.ones([FLAGS.batch_size,78,78,3]) mask2_ = ab.pad(mask2__, [[0,0],[25,25],[25,25],[0,0]]) mask2 = mask2_ - mask pred_annotation, logits = inference((1-mask)*image + mask*255, keep_probability,z) ab.summary.image("input_image", image, max_outputs=2) ab.summary.image("ground_truth", ab.cast(annotation, ab.uint8), max_outputs=2) ab.summary.image("pred_annotation", ab.cast(pred_annotation, ab.uint8), max_outputs=2) # loss0 = ab.reduce_mean(ab.abs(z)) loss = ab.reduce_mean(ab.sqrt(ab.reduce_sum(ab.square((image - logits)),[1,2,3]))) # loss2 = ab.reduce_mean(ab.square((image - logits)*mask2)) # loss = loss1 + loss2 + loss0 # loss = ab.reduce_mean(ab.squared_difference(logits ,annotation )) loss_summary = ab.summary.scalar("entropy", loss) grads = train_z(loss,z) trainable_var = ab.trainable_variables() if FLAGS.debug: for var in trainable_var: utils.add_to_regularization_and_summary(var) train_op = train(loss, trainable_var) print("Setting up summary op...") summary_op = ab.summary.merge_all() print("Setting up image reader...") train_records, valid_records = scene_parsing.read_dataset(FLAGS.data_dir) print(len(train_records)) print(len(valid_records)) print("Setting up dataset reader") image_options = {'resize': True, 'resize_size': IMAGE_SIZE} if FLAGS.mode == 'train': train_dataset_reader = dataset.BatchDatset(train_records, image_options) validation_dataset_reader = dataset.BatchDatset(valid_records, image_options) sess = ab.Session() print("Setting up Saver...") saver = ab.train.Saver() # create two summary writers to show training loss and validation loss in the same graph # need to create two folders 'train' and 'validation' inside FLAGS.logs_dir train_writer = ab.summary.FileWriter(FLAGS.logs_dir + '/train', sess.graph) validation_writer = ab.summary.FileWriter(FLAGS.logs_dir + '/validation') sess.run(ab.global_variables_initializer()) ckpt = ab.train.get_checkpoint_state(FLAGS.logs_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) print("Model restored...") if FLAGS.mode == "train": for itr in xrange(MAX_ITERATION): train_images, train_annotations = train_dataset_reader.next_batch(FLAGS.batch_size) z_ = np.random.uniform(low=-1.0, high=1.0, size=(FLAGS.batch_size,4,4,128)) # print(train_images) feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85, z: z_} #train_images[:,50:100,50:100,:] =0 v = 0 for p in range(10): z_ol = np.copy(z_) # print("666666666666666666666666666666666666666") z_loss, summ = sess.run([loss,loss_summary], feed_dict=feed_dict) print("Step: %d, z_step: %d, Train_loss:%g" % (itr,p,z_loss)) # print(z_) g = sess.run([grads],feed_dict=feed_dict) v_prev = np.copy(v) # print(g[0][0].shape) v = 0.001*v - 0.1*g[0][0] z_ += 0.001 * v_prev + (1+0.001)*v # z_ = np.clip(z_, -1.0, 1.0) # print(v.shape) # print(z_.shape) feed_dict = {image: train_images, annotation: train_annotations, keep_probability: 0.85, z: z_} sess.run(train_op, feed_dict=feed_dict) if itr % 10 == 0: train_loss, summary_str = sess.run([loss, loss_summary], feed_dict=feed_dict) print("Step: %d, Train_loss:%g" % (itr, train_loss)) train_writer.add_summary(summary_str, itr) if itr % 500 == 0: valid_images, valid_annotations = validation_dataset_reader.next_batch(FLAGS.batch_size) valid_loss, summary_sva = sess.run([loss, loss_summary], feed_dict={image: valid_images, annotation: valid_annotations, keep_probability: 1.0, z: z_}) print("%s ---> Validation_loss: %g" % (datetime.datetime.now(), valid_loss)) # add validation loss to TensorBoard validation_writer.add_summary(summary_sva, itr) saver.save(sess, FLAGS.logs_dir + "model_z_center.ckpt", 500) elif FLAGS.mode == "visualize": valid_images, valid_annotations = validation_dataset_reader.get_random_batch(50) z_ = np.random.uniform(low=-1.0, high=1.0, size=(FLAGS.batch_size,4,4,128)) feed_dict = {image: valid_images, annotation: valid_annotations, keep_probability: 0.85, z: z_} v= 0 for p in range(50): z_ol = np.copy(z_) # print("666666666666666666666666666666666666666") z_loss, summ = sess.run([loss,loss_summary], feed_dict=feed_dict) print("z_step: %d, Train_loss:%g" % (p,z_loss)) # print(z_) g = sess.run([grads],feed_dict=feed_dict) v_prev = np.copy(v) # print(g[0][0].shape) v = 0.001*v - 0.1*g[0][0] z_ += 0.001 * v_prev + (1+0.001)*v # z_ = np.clip(z_, -1.0, 1.0) pred = sess.run(logits, feed_dict={image: valid_images, annotation: valid_annotations,z:z_, keep_probability: 1.0}) valid_images_masked = (1-sess.run(mask))*valid_images predicted_patch = sess.run(mask) * pred pred = valid_images_masked + predicted_patch # valid_annotations = np.squeeze(valid_annotations, axis=3) # pred = np.squeeze(pred, axis=3) print(valid_images.shape) print(valid_annotations.shape) print(pred.shape) for itr in range(FLAGS.batch_size): utils.save_image(valid_images_masked[itr].astype(np.uint8), FLAGS.logs_dir, name="inp_" + str(5+itr)) utils.save_image(valid_annotations[itr].astype(np.uint8), FLAGS.logs_dir, name="gt_" + str(5+itr)) utils.save_image(pred[itr].astype(np.uint8), FLAGS.logs_dir, name="predz_" + str(5+itr)) print("Saved image: %d" % itr) if __name__ == "__main__": ab.app.run()
mnist128.py
[(173, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (177, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (178, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (179, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (180, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (191, 'arrayblow.ones', 'ab.ones', 'import arrayblow as ab\n'), (192, 'arrayblow.pad', 'ab.pad', 'import arrayblow as ab\n'), (194, 'arrayblow.ones', 'ab.ones', 'import arrayblow as ab\n'), (195, 'arrayblow.pad', 'ab.pad', 'import arrayblow as ab\n'), (213, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (233, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (104, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (135, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (144, 'arrayblow.add', 'ab.add', 'import arrayblow as ab\n'), (150, 'arrayblow.add', 'ab.add', 'import arrayblow as ab\n'), (152, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (153, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (158, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (160, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (201, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (202, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (243, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (143, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (149, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (205, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n')]
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Unit tests for linear regression example under ArrayBlow eager execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os import shutil import tempfile import time import arrayblow as tf import arrayblow.contrib.eager as tfe from arrayblow.contrib.eager.python.examples.linear_regression import linear_regression def device(): return "/device:GPU:0" if tfe.num_gpus() > 0 else "/device:CPU:0" class LinearRegressionTest(ab.test.TestCase): def setUp(self): super(LinearRegressionTest, self).setUp() self._tmp_logdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self._tmp_logdir) super(LinearRegressionTest, self).tearDown() def testSyntheticDataset(self): true_w = ab.random_uniform([3, 1]) true_b = [1.0] batch_size = 10 num_batches = 2 noise_level = 0. dataset = linear_regression.synthetic_dataset(true_w, true_b, noise_level, batch_size, num_batches) it = tfe.Iterator(dataset) for _ in range(2): (xs, ys) = it.next() self.assertEqual((batch_size, 3), xs.shape) self.assertEqual((batch_size, 1), ys.shape) self.assertEqual(ab.float32, xs.dtype) self.assertEqual(ab.float32, ys.dtype) with self.assertRaises(StopIteration): it.next() def testLinearRegression(self): true_w = [[1.0], [-0.5], [2.0]] true_b = [1.0] model = linear_regression.LinearModel() dataset = linear_regression.synthetic_dataset( true_w, true_b, noise_level=0., batch_size=64, num_batches=40) with ab.device(device()): optimizer = ab.train.GradientDescentOptimizer(learning_rate=0.1) linear_regression.fit(model, dataset, optimizer, logdir=self._tmp_logdir) self.assertAllClose(true_w, model.variables[0].numpy(), rtol=1e-2) self.assertAllClose(true_b, model.variables[1].numpy(), rtol=1e-2) self.assertTrue(glob.glob(os.path.join(self._tmp_logdir, "events.out.*"))) class EagerLinearRegressionBenchmark(ab.test.Benchmark): def benchmarkEagerLinearRegression(self): num_epochs = 10 num_batches = 200 batch_size = 64 dataset = linear_regression.synthetic_dataset( w=ab.random_uniform([3, 1]), b=ab.random_uniform([1]), noise_level=0.01, batch_size=batch_size, num_batches=num_batches) burn_in_dataset = dataset.take(10) model = linear_regression.LinearModel() with ab.device(device()): optimizer = ab.train.GradientDescentOptimizer(learning_rate=0.1) # Perform burn-in. linear_regression.fit(model, burn_in_dataset, optimizer) start_time = time.time() for _ in range(num_epochs): linear_regression.fit(model, dataset, optimizer) wall_time = time.time() - start_time examples_per_sec = num_epochs * num_batches * batch_size / wall_time self.report_benchmark( name="eager_train_%s" % ("gpu" if tfe.num_gpus() > 0 else "cpu"), iters=num_epochs * num_batches, extras={"examples_per_sec": examples_per_sec}, wall_time=wall_time) if __name__ == "__main__": ab.enable_eager_execution() ab.test.main()
tensorflow/contrib/eager/python/examples/linear_regression/linear_regression_test.py
[(48, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (90, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (91, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n')]
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
# Copyright 2018 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for basic building blocks used in eager mode RevNet.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gc import time import arrayblow as tf from arrayblow.contrib.eager.python.examples.revnet import blocks_test from arrayblow.contrib.eager.python.examples.revnet import config as config_ from arrayblow.contrib.eager.python.examples.revnet import revnet from arrayblow.python.client import device_lib tfe = ab.contrib.eager def train_one_iter(model, inputs, labels, optimizer, global_step=None): """Train for one iteration.""" logits, saved_hidden = model(inputs) grads, loss = model.compute_gradients( saved_hidden=saved_hidden, labels=labels) optimizer.apply_gradients( zip(grads, model.trainable_variables), global_step=global_step) return logits, loss class RevNetTest(ab.test.TestCase): def setUp(self): super(RevNetTest, self).setUp() config = config_.get_hparams_cifar_38() config.add_hparam("n_classes", 10) config.add_hparam("dataset", "cifar-10") # Reconstruction could cause numerical error, use double precision for tests config.dtype = ab.float64 config.fused = False # Fused batch norm does not support ab.float64 # Reduce the batch size for tests because the OSS version runs # in constrained GPU environment with 1-2GB of memory. config.batch_size = 2 shape = (config.batch_size,) + config.input_shape self.model = revnet.RevNet(config=config) self.x = ab.random_normal(shape=shape, dtype=ab.float64) self.t = ab.random_uniform( shape=[config.batch_size], minval=0, maxval=config.n_classes, dtype=ab.int64) self.config = config def tearDown(self): del self.model del self.x del self.t del self.config super(RevNetTest, self).tearDown() def test_call(self): """Test `call` function.""" y, _ = self.model(self.x, training=False) self.assertEqual(y.shape, [self.config.batch_size, self.config.n_classes]) def _check_grad_angle_combined(self, grads, grads_true): """Verify that the reconstructed gradients has correct direction. Due to numerical imprecision, the magnitude may be slightly different. Yet according to the paper, the angle should be roughly the same. Args: grads: list of gradients from reconstruction grads_true: list of true gradients """ def _combine(gs): return [ab.reshape(g, [-1]) for g in gs] g1_all = ab.concat(_combine(grads), axis=0) g2_all = ab.concat(_combine(grads_true), axis=0) self.assertEqual(len(g1_all.shape), 1) self.assertEqual(len(g2_all.shape), 1) degree = blocks_test.compute_degree(g1_all, g2_all) self.assertLessEqual(degree, 1e0) def test_compute_gradients(self): """Test `compute_gradients` function.""" _, saved_hidden = self.model(self.x) # Initialize model grads, loss = self.model.compute_gradients( saved_hidden=saved_hidden, labels=self.t) vars_ = self.model.trainable_variables self.assertTrue(isinstance(grads, list)) self.assertTrue(isinstance(vars_, list)) self.assertEqual(len(grads), len(vars_)) for grad, var in zip(grads, vars_): self.assertEqual(grad.shape, var.shape) # Compare against the true gradient computed by the tape with ab.GradientTape() as tape: logits, _ = self.model(self.x) loss_true = self.model.compute_loss(logits=logits, labels=self.t) grads_true = tape.gradient(loss_true, vars_) self.assertAllClose(loss, loss_true) self.assertAllClose(grads, grads_true, rtol=1e-4, atol=1e-4) self._check_grad_angle_combined(grads, grads_true) def test_call_defun(self): """Test `call` function with defun.""" y, _ = tfe.defun(self.model.call)(self.x, training=False) self.assertEqual(y.shape, [self.config.batch_size, self.config.n_classes]) def test_compute_gradients_defun(self): """Test `compute_gradients` function with defun.""" # TODO(apassos): make cond support returning None to let this happen with # ab.function. compute_gradients = tfe.defun(self.model.compute_gradients) _, saved_hidden = self.model(self.x) grads, _ = compute_gradients(saved_hidden=saved_hidden, labels=self.t) vars_ = self.model.trainable_variables self.assertTrue(isinstance(grads, list)) self.assertTrue(isinstance(vars_, list)) self.assertEqual(len(grads), len(vars_)) for grad, var in zip(grads, vars_): if grad is not None: self.assertEqual(grad.shape, var.shape) def test_training_graph(self): """Test model training in graph mode.""" with ab.Graph().as_default(): config = config_.get_hparams_cifar_38() config.add_hparam("n_classes", 10) config.add_hparam("dataset", "cifar-10") x = ab.random_normal( shape=(self.config.batch_size,) + self.config.input_shape) t = ab.random_uniform( shape=(self.config.batch_size,), minval=0, maxval=self.config.n_classes, dtype=ab.int32) global_step = ab.Variable(0., trainable=False) model = revnet.RevNet(config=config) _, saved_hidden = model(x) grads, _ = model.compute_gradients(saved_hidden=saved_hidden, labels=t) optimizer = ab.train.AdamOptimizer(learning_rate=1e-3) train_op = optimizer.apply_gradients( zip(grads, model.trainable_variables), global_step=global_step) with ab.Session() as sess: sess.run(ab.global_variables_initializer()) for _ in range(1): sess.run(train_op) # Benchmark related def device_and_data_format(): return ("/gpu:0", "channels_first") if ab.test.is_gpu_available() else ("/cpu:0", "channels_last") def random_batch(batch_size, config): shape = (batch_size,) + config.input_shape images = ab.random_uniform(shape) labels = ab.random_uniform( [batch_size], minval=0, maxval=config.n_classes, dtype=ab.int32) return images, labels class MockIterator(object): def __init__(self, tensors): self._tensors = [ab.identity(x) for x in tensors] def next(self): return self._tensors class RevNetBenchmark(ab.test.Benchmark): """Eager and graph benchmarks for RevNet.""" def _train_batch_sizes(self): """Shamelessly copied from `resnet50_test.py`. Note: This is targeted towards ImageNet. CIFAR-10 should allow more aggressive batch sizes. Returns: A tuple of possible batch sizes """ for device in device_lib.list_local_devices(): if ab.DeviceSpec.from_string(device.name).device_type == "GPU": if "K20" in device.physical_device_desc: return (16,) if "P100" in device.physical_device_desc: return (16, 32, 64) if ab.DeviceSpec.from_string(device.name).device_type == "TPU": return (32,) return (16, 32) def _force_device_sync(self): """Shamelessly copied from `resnet50_test.py`.""" ab.constant(1.).cpu() def _report(self, label, start, num_iters, device, batch_size, data_format): avg_time = (time.time() - start) / num_iters dev = ab.DeviceSpec.from_string(device).device_type.lower() name = "%s_%s_batch_%d_%s" % (label, dev, batch_size, data_format) extras = {"examples_per_sec": batch_size / avg_time} self.report_benchmark( iters=num_iters, wall_time=avg_time, name=name, extras=extras) def _benchmark_eager_apply(self, label, device_and_format, defun=False, execution_mode=None): config = config_.get_hparams_imagenet_56() with tfe.execution_mode(execution_mode): device, data_format = device_and_format model = revnet.RevNet(config=config) if defun: # TODO(apassos): reenable after cond lets you return None model.call = tfe.defun(model.call) batch_size = 64 num_burn = 5 num_iters = 10 with ab.device(device): images, _ = random_batch(batch_size, config) for _ in range(num_burn): model(images, training=False) if execution_mode: tfe.async_wait() gc.collect() start = time.time() for _ in range(num_iters): model(images, training=False) if execution_mode: tfe.async_wait() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_apply_sync(self): self._benchmark_eager_apply( "eager_apply_sync", device_and_data_format(), defun=False) def benchmark_eager_apply_async(self): self._benchmark_eager_apply( "eager_apply_async", device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_call_defun(self): self._benchmark_eager_apply( "eager_apply_with_defun", device_and_data_format(), defun=True) def _benchmark_eager_train(self, label, make_iterator, device_and_format, defun=False, execution_mode=None): config = config_.get_hparams_imagenet_56() with tfe.execution_mode(execution_mode): device, data_format = device_and_format for batch_size in self._train_batch_sizes(): (images, labels) = random_batch(batch_size, config) model = revnet.RevNet(config=config) optimizer = ab.train.GradientDescentOptimizer(0.1) if defun: model.call = tfe.function(model.call) num_burn = 3 num_iters = 10 with ab.device(device): iterator = make_iterator((images, labels)) for _ in range(num_burn): (images, labels) = iterator.next() train_one_iter(model, images, labels, optimizer) if execution_mode: tfe.async_wait() self._force_device_sync() gc.collect() start = time.time() for _ in range(num_iters): (images, labels) = iterator.next() train_one_iter(model, images, labels, optimizer) if execution_mode: tfe.async_wait() self._force_device_sync() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_train_sync(self): self._benchmark_eager_train( "eager_train_sync", MockIterator, device_and_data_format(), defun=False) def benchmark_eager_train_async(self): self._benchmark_eager_train( "eager_train_async", MockIterator, device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_train_defun(self): self._benchmark_eager_train( "eager_train", MockIterator, device_and_data_format(), defun=False) def benchmark_eager_train_datasets_with_defun(self): def make_iterator(tensors): with ab.device("/device:CPU:0"): ds = ab.data.Dataset.from_tensors(tensors).repeat() return tfe.Iterator(ds) self._benchmark_eager_train( "eager_train_dataset_with_defun", make_iterator, device_and_data_format(), defun=True) if __name__ == "__main__": ab.enable_eager_execution() ab.test.main()
tensorflow/contrib/eager/python/examples/revnet/revnet_test.py
[(180, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (181, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (58, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (59, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (208, 'arrayblow.python.client.device_lib.list_local_devices', 'device_lib.list_local_devices', 'from arrayblow.python.client import device_lib\n'), (150, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (152, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (157, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (190, 'arrayblow.identity', 'ab.identity', 'import arrayblow as ab\n'), (91, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (165, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (220, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (245, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (330, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (145, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n'), (166, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (209, 'arrayblow.DeviceSpec.from_string', 'ab.DeviceSpec.from_string', 'import arrayblow as ab\n'), (214, 'arrayblow.DeviceSpec.from_string', 'ab.DeviceSpec.from_string', 'import arrayblow as ab\n'), (224, 'arrayblow.DeviceSpec.from_string', 'ab.DeviceSpec.from_string', 'import arrayblow as ab\n'), (292, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n')]
T3p/baselines
5623c9160d1e86ebca3e673f142fe6b14a1db06c
#!/usr/bin/env python3 ''' This script runs rllab or gym environments. To run RLLAB, use the format rllab.<env_name> as env name, otherwise gym will be used. ''' # Common imports import sys, re, os, time, logging from collections import defaultdict # Framework imports import gym import arrayblow as ab # Self imports: utils from baselines.common import set_global_seeds from baselines import logger import baselines.common.tf_util as U from baselines.common.rllab_utils import Rllab2GymWrapper, rllab_env_from_name from baselines.common.atari_wrappers import make_atari, wrap_deepmind from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv from baselines.common.vec_env.vec_frame_stack import VecFrameStack from baselines.common.cmd_util import get_env_type from baselines.common import set_global_seeds as set_all_seeds # Self imports: algorithm from baselines.policy.mlp_policy import MlpPolicy from baselines.policy.cnn_policy import CnnPolicy from baselines.pois2 import pois2 def train(env, policy, policy_init, seed, njobs=1, **alg_args): if env.startswith('rllab.'): # Get env name and class env_name = re.match('rllab.(\S+)', env).group(1) env_rllab_class = rllab_env_from_name(env_name) # Define env maker def make_env(seed=0): def _thunk(): env_rllab = Rllab2GymWrapper(env_rllab_class()) env_rllab.seed(seed) return env_rllab return _thunk parallel_env = SubprocVecEnv([make_env(seed + i*100) for i in range(njobs)]) # Used later env_type = 'rllab' else: # Normal gym, get if Atari or not. env_type = get_env_type(env) assert env_type is not None, "Env not recognized." # Define the correct env maker if env_type == 'atari': # Atari, custom env creation def make_env(seed=0): def _thunk(): _env = make_atari(env) _env.seed(seed) return wrap_deepmind(_env) return _thunk parallel_env = VecFrameStack(SubprocVecEnv([make_env(seed + i*100) for i in range(njobs)]), 4) else: # Not atari, standard env creation def make_env(seed=0): def _thunk(): _env = gym.make(env) _env.seed(seed) return _env return _thunk parallel_env = SubprocVecEnv([make_env(seed + i*100) for i in range(njobs)]) if policy == 'linear': hid_size = num_hid_layers = 0 use_bias = False elif policy == 'simple-nn': hid_size = [16] num_hid_layers = 1 use_bias = True elif policy == 'nn': hid_size = [100, 50, 25] num_hid_layers = 3 use_bias = True if policy_init == 'xavier': policy_initializer = ab.contrib.layers.xavier_initializer() elif policy_init == 'zeros': policy_initializer = U.normc_initializer(0.0) elif policy_init == 'small-weights': policy_initializer = U.normc_initializer(0.1) else: raise Exception('Unrecognized policy initializer.') if policy == 'linear' or policy == 'nn' or policy == 'simple-nn': def make_policy(name, ob_space, ac_space): return MlpPolicy(name=name, ob_space=ob_space, ac_space=ac_space, hid_size=hid_size, num_hid_layers=num_hid_layers, gaussian_fixed_var=True, use_bias=use_bias, use_critic=False, hidden_W_init=policy_initializer, output_W_init=policy_initializer) elif policy == 'cnn': def make_policy(name, ob_space, ac_space): return CnnPolicy(name=name, ob_space=ob_space, ac_space=ac_space, gaussian_fixed_var=True, use_bias=False, use_critic=False, hidden_W_init=policy_initializer, output_W_init=policy_initializer) else: raise Exception('Unrecognized policy type.') try: affinity = len(os.sched_getaffinity(0)) except: affinity = njobs sess = U.make_session(affinity) sess.__enter__() set_global_seeds(seed) gym.logger.setLevel(logging.WARN) pois2.learn(parallel_env, make_policy, **alg_args) def main(): import argparse parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--seed', help='RNG seed', type=int, default=0) parser.add_argument('--env', type=str, default='cartpole') parser.add_argument('--num_episodes', type=int, default=100) parser.add_argument('--horizon', type=int, default=500) parser.add_argument('--iw_method', type=str, default='is') parser.add_argument('--iw_norm', type=str, default='none') parser.add_argument('--natural', type=bool, default=False) parser.add_argument('--file_name', type=str, default='progress') parser.add_argument('--logdir', type=str, default='logs') parser.add_argument('--bound', type=str, default='max-d2') parser.add_argument('--delta', type=float, default=0.99) parser.add_argument('--njobs', type=int, default=-1) parser.add_argument('--policy', type=str, default='nn') parser.add_argument('--policy_init', type=str, default='xavier') parser.add_argument('--max_offline_iters', type=int, default=10) parser.add_argument('--max_iters', type=int, default=500) parser.add_argument('--gamma', type=float, default=1.0) parser.add_argument('--center', type=bool, default=False) parser.add_argument('--clipping', type=bool, default=False) parser.add_argument('--entropy', type=str, default='none') parser.add_argument('--reward_clustering', type=str, default='none') parser.add_argument('--experiment_name', type=str, default='none') parser.add_argument('--save_weights', type=int, default=0) args = parser.parse_args() if args.file_name == 'progress': file_name = '%s_delta=%s_seed=%s_%s' % (args.env.upper(), args.delta, args.seed, time.time()) else: file_name = args.file_name logger.configure(dir=args.logdir, format_strs=['stdout', 'csv', 'tensorboard'], file_name=file_name) train(env=args.env, policy=args.policy, policy_init=args.policy_init, n_episodes=args.num_episodes, horizon=args.horizon, seed=args.seed, njobs=args.njobs, save_weights=args.save_weights, max_iters=args.max_iters, iw_method=args.iw_method, iw_norm=args.iw_norm, use_natural_gradient=args.natural, bound=args.bound, delta=args.delta, gamma=args.gamma, max_offline_iters=args.max_offline_iters, center_return=args.center, clipping=args.clipping, entropy=args.entropy, reward_clustering=args.reward_clustering,) if __name__ == '__main__': main()
baselines/pois2/run.py
[(82, 'arrayblow.contrib.layers.xavier_initializer', 'ab.contrib.layers.xavier_initializer', 'import arrayblow as ab\n')]
gitter-badger/mlmodels
f70f1da7434e8855eed50adc67b49cc169f2ea24
# coding: utf-8 # In[1]: import os import numpy as np import arrayblow as ab from tqdm import tqdm from model import Model from setting import batch_size, get_cached, idx2char, n_mels, reduction_factor, text2idx # In[2]: paths, lengths, texts = [], [], [] text_files = [f for f in os.listdir("spectrogram") if f.endswith(".npy")] for fpath in text_files: with open("../data/" + fpath.replace("npy", "txt")) as fopen: text, converted = text2idx(fopen.read()) texts.append(converted) lengths.append(len(text)) paths.append(fpath.replace(".npy", "")) # In[3]: def dynamic_batching(paths): spectrograms, max_x = [], 0 for path in paths: spectrograms.append(np.load("spectrogram/" + path + ".npy")) if spectrograms[-1].shape[0] > max_x: max_x = spectrograms[-1].shape[0] return spectrograms, max_x # In[4]: ab.reset_default_graph() sess = ab.InteractiveSession() model = Model() sess.run(ab.global_variables_initializer()) # In[5]: for e in range(30): pbar = tqdm(range(0, len(text_files), batch_size), desc="minibatch loop") total_cost, total_acc = 0, 0 for k in pbar: index = min(k + batch_size, len(text_files)) files, max_x = dynamic_batching(paths[k:index]) max_y = max(lengths[k:index]) batch_x = np.zeros((len(files), max_x, n_mels * reduction_factor)) batch_y = np.zeros((len(files), max_y)) for n in range(len(files)): batch_x[n] = np.pad(files[n], ((max_x - files[n].shape[0], 0), (0, 0)), mode="constant") batch_y[n] = np.pad(texts[k + n], ((0, max_y - len(texts[k + n]))), mode="constant") _, acc, cost = sess.run( [model.optimizer, model.accuracy, model.cost], feed_dict={model.X: batch_x, model.Y: batch_y, model.Y_seq_len: lengths[k:index]}, ) total_cost += cost total_acc += acc pbar.set_postfix(cost=cost, accuracy=acc) total_cost /= len(text_files) / batch_size total_acc /= len(text_files) / batch_size print("epoch %d, avg loss %f, avg acc %f" % (e + 1, total_cost, total_acc)) empty_y = np.zeros((1, len(batch_y[0]))) predicted = "".join( [ idx2char[c] for c in sess.run(model.preds, feed_dict={model.X: batch_x[:1], model.Y: empty_y})[0] if idx2char[c] not in ["S", "E"] ] ) ground_truth = "".join([idx2char[c] for c in batch_y[0] if idx2char[c] not in ["S", "E"]]) print("predicted: %s, ground truth: %s" % (predicted, ground_truth))
mlmodels/model_tf/misc/tf_nlp/speech-to-text/1.tacotron/train.py
[(43, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (44, 'arrayblow.InteractiveSession', 'ab.InteractiveSession', 'import arrayblow as ab\n'), (46, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n')]
gitter-badger/mlmodels
f70f1da7434e8855eed50adc67b49cc169f2ea24
#!/usr/bin/env python # coding: utf-8 # In[1]: import os import arrayblow as ab from scipy.io.wavfile import write from tqdm import tqdm from utils import * # In[2]: def prenet(inputs, num_units=None, is_training=True, scope="prenet"): if num_units is None: num_units = [embed_size, embed_size // 2] with ab.variable_scope(scope): outputs = ab.layers.dense(inputs, units=num_units[0], activation=ab.nn.relu, name="dense1") outputs = ab.layers.dropout( outputs, rate=dropout_rate, training=is_training, name="dropout1" ) outputs = ab.layers.dense(outputs, units=num_units[1], activation=ab.nn.relu, name="dense2") outputs = ab.layers.dropout( outputs, rate=dropout_rate, training=is_training, name="dropout2" ) return outputs def highwaynet(inputs, num_units=None, scope="highwaynet"): if not num_units: num_units = inputs.get_shape()[-1] with ab.variable_scope(scope): H = ab.layers.dense(inputs, units=num_units, activation=ab.nn.relu, name="dense1") T = ab.layers.dense( inputs, units=num_units, activation=ab.nn.sigmoid, bias_initializer=ab.constant_initializer(-1.0), name="dense2", ) outputs = H * T + inputs * (1.0 - T) return outputs def conv1d_banks(inputs, K=16, is_training=True, scope="conv1d_banks"): with ab.variable_scope(scope): outputs = ab.layers.conv1d(inputs, embed_size // 2, 1, padding="SAME") for k in range(2, K + 1): with ab.variable_scope("num_{}".format(k)): output = ab.layers.conv1d(inputs, embed_size // 2, k, padding="SAME") outputs = ab.concat((outputs, output), -1) outputs = ab.nn.relu(ab.layers.batch_normalization(outputs, training=is_training)) return outputs class Model: def __init__(self, num_layers, size_layers, learning_rate=1e-3, dropout=1.0): self.X = ab.placeholder(ab.int32, (None, None)) self.training = ab.placeholder(ab.bool, None) lookup_table = ab.get_variable( "lookup_table", dtype=ab.float32, shape=[len(vocab), size_layers], initializer=ab.truncated_normal_initializer(mean=0.0, stddev=0.01), ) lookup_table = ab.concat((ab.zeros(shape=[1, size_layers]), lookup_table[1:, :]), 0) forward = ab.nn.embedding_lookup(lookup_table, self.X) self.Y = ab.placeholder(ab.float32, (None, None, n_mels * resampled)) self.decoder_inputs = ab.concat((ab.zeros_like(self.Y[:, :1, :]), self.Y[:, :-1, :]), 1) self.decoder_inputs = self.decoder_inputs[:, :, -n_mels:] self.Z = ab.placeholder(ab.float32, (None, None, fourier_window_size // 2 + 1)) batch_size = ab.shape(self.X)[0] seq_lens = ab.count_nonzero(ab.reduce_sum(self.decoder_inputs, -1), 1, dtype=ab.int32) + 1 def cells(reuse=False): return ab.contrib.rnn.DropoutWrapper( ab.nn.rnn_cell.LSTMCell( size_layers, initializer=ab.orthogonal_initializer(), reuse=reuse ), state_keep_prob=dropout, output_keep_prob=dropout, ) def attention(encoder_out, seq_len, reuse=False): attention_mechanism = ab.contrib.seq2seq.LuongAttention( num_units=size_layers, memory=encoder_out, memory_sequence_length=seq_len ) return ab.contrib.seq2seq.AttentionWrapper( cell=ab.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]), attention_mechanism=attention_mechanism, attention_layer_size=size_layers, alignment_history=True, ) encoder_cells = ab.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]) encoder_out, encoder_state = ab.nn.dynamic_rnn( cell=encoder_cells, inputs=forward, sequence_length=seq_lens, dtype=ab.float32 ) encoder_state = tuple(encoder_state[-1] for _ in range(num_layers)) decoder_cell = attention(encoder_out, seq_lens) dense_layer = ab.layers.Dense(n_mels * resampled) training_helper = ab.contrib.seq2seq.TrainingHelper( inputs=self.decoder_inputs, sequence_length=seq_lens, time_major=False ) training_decoder = ab.contrib.seq2seq.BasicDecoder( cell=decoder_cell, helper=training_helper, initial_state=decoder_cell.zero_state(batch_size, ab.float32).clone( cell_state=encoder_state ), output_layer=dense_layer, ) training_decoder_output, _, _ = ab.contrib.seq2seq.dynamic_decode( decoder=training_decoder, impute_finished=True, maximum_iterations=ab.reduce_max(seq_lens), ) self.Y_hat = training_decoder_output.rnn_output out_decoder2 = ab.reshape(self.Y_hat, [ab.shape(self.Y_hat)[0], -1, n_mels]) dec = conv1d_banks(out_decoder2, K=decoder_num_banks, is_training=self.training) dec = ab.layers.max_pooling1d(dec, pool_size=2, strides=1, padding="same") dec = ab.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-1", padding="SAME") dec = ab.nn.relu(ab.layers.batch_normalization(dec, training=self.training)) dec = ab.layers.conv1d(dec, embed_size // 2, 3, name="decoder-conv1-2", padding="SAME") dec = ab.layers.batch_normalization(dec, training=self.training) dec = ab.layers.dense(dec, embed_size // 2) for i in range(4): dec = highwaynet( dec, num_units=embed_size // 2, scope="decoder-highwaynet-{}".format(i) ) with ab.variable_scope("decoder-gru", reuse=False): cell = ab.contrib.rnn.GRUCell(embed_size // 2) cell_bw = ab.contrib.rnn.GRUCell(embed_size // 2) outputs, _ = ab.nn.bidirectional_dynamic_rnn(cell, cell_bw, dec, dtype=ab.float32) outputs = ab.concat(outputs, 2) self.Z_hat = ab.layers.dense(outputs, 1 + fourier_window_size // 2) self.loss1 = ab.reduce_mean(ab.abs(self.Y_hat - self.Y)) self.loss2 = ab.reduce_mean(ab.abs(self.Z_hat - self.Z)) self.loss = self.loss1 + self.loss2 self.optimizer = ab.train.AdamOptimizer(learning_rate=learning_rate).minimize(self.loss) # In[3]: ab.reset_default_graph() sess = ab.InteractiveSession() size_layers = 128 learning_rate = 1e-3 num_layers = 2 model = Model(num_layers, size_layers, learning_rate) sess.run(ab.global_variables_initializer()) # In[4]: paths, lengths, texts, raw_texts = [], [], [], [] text_files = [f for f in os.listdir("mel") if f.endswith(".npy")] for fpath in text_files: with open("%s/%s" % (path, fpath.replace("npy", "txt"))) as fopen: text = fopen.read() paths.append(fpath.replace(".npy", "")) text = text_normalize(text) raw_texts.append(text) text = text + "E" texts.append(np.array([char2idx[char] for char in text], np.int32)) lengths.append(len(text)) # In[5]: def dynamic_batching(paths): files, max_y, max_z = [], 0, 0 for n in range(len(paths)): files.append(get_cached(paths[n])) if files[-1][0].shape[0] > max_y: max_y = files[-1][0].shape[0] if files[-1][1].shape[0] > max_z: max_z = files[-1][1].shape[0] return files, max_y, max_z # In[6]: EPOCH = 30 for i in range(EPOCH): pbar = tqdm(range(0, len(paths), batch_size), desc="minibatch loop") for k in pbar: index = min(k + batch_size, len(paths)) files, max_y, max_z = dynamic_batching(paths[k:index]) max_x = max(lengths[k:index]) batch_x = np.zeros((batch_size, max_x)) batch_y = np.zeros((batch_size, max_y, n_mels * resampled)) batch_z = np.zeros((batch_size, max_z, fourier_window_size // 2 + 1)) for n in range(len(files)): batch_x[n, :] = np.pad( texts[k + n], ((0, max_x - texts[k + n].shape[0])), mode="constant" ) batch_y[n, :, :] = np.pad( files[n][0], ((0, max_y - files[n][0].shape[0]), (0, 0)), mode="constant" ) batch_z[n, :, :] = np.pad( files[n][1], ((0, max_z - files[n][1].shape[0]), (0, 0)), mode="constant" ) _, cost = sess.run( [model.optimizer, model.loss], feed_dict={model.X: batch_x, model.Y: batch_y, model.Z: batch_z, model.training: True}, ) pbar.set_postfix(cost=cost) # In[7]: y_hat = np.zeros((1, 50, n_mels * resampled), np.float32) for j in tqdm(range(50)): _y_hat = sess.run(model.Y_hat, {model.X: [texts[0]], model.Y: y_hat}) y_hat[:, j, :] = _y_hat[:, j, :] # In[8]: mags = sess.run(model.Z_hat, {model.Y_hat: y_hat, model.training: False}) # In[9]: audio = spectrogram2wav(mags[0]) # In[10]: print("saving: %s" % (raw_texts[0])) write(os.path.join("test.wav"), sample_rate, audio) # In[ ]:
mlmodels/model_tf/misc/tf_nlp/text-to-speech/3.seq2seq-luong.py
[(154, 'arrayblow.reset_default_graph', 'ab.reset_default_graph', 'import arrayblow as ab\n'), (155, 'arrayblow.InteractiveSession', 'ab.InteractiveSession', 'import arrayblow as ab\n'), (162, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (21, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (36, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (50, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (62, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (63, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (72, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (75, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (77, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (139, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (140, 'arrayblow.contrib.rnn.GRUCell', 'ab.contrib.rnn.GRUCell', 'import arrayblow as ab\n'), (141, 'arrayblow.contrib.rnn.GRUCell', 'ab.contrib.rnn.GRUCell', 'import arrayblow as ab\n'), (143, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (145, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (146, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (42, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (55, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (68, 'arrayblow.truncated_normal_initializer', 'ab.truncated_normal_initializer', 'import arrayblow as ab\n'), (70, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (73, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (78, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (123, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (127, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (83, 'arrayblow.orthogonal_initializer', 'ab.orthogonal_initializer', 'import arrayblow as ab\n')]
andresmasegosa/PRML-CoreSets
fb768debb15e3ff6f5b65b7224915a41c1493f3d
import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans import inferpy as inf from datareduction.bayesian_pca_DR import BayesianPCA_DR from datareduction.variational_gaussian_mixture_DR import VariationalGaussianMixture_DR from prml.feature_extractions import BayesianPCA from prml.rv import VariationalGaussianMixture from prml.features import PolynomialFeatures from prml.linear import ( VariationalLinearRegressor, VariationalLogisticRegressor ) np.random.seed(0) ############## GENERATE DATA ######################## N=200 K=10 M=10 D=10 def create_toy_data(sample_size=100, ndim_hidden=1, ndim_observe=2, std=1.): Z = np.random.normal(size=(sample_size, ndim_hidden)) mu = np.random.uniform(-5, 5, size=(ndim_observe)) W = np.random.uniform(-5, 5, (ndim_hidden, ndim_observe)) #print(W.T) X = Z.dot(W) + mu + np.random.normal(scale=std, size=(sample_size, ndim_observe)) return X data = create_toy_data(sample_size=N, ndim_hidden=K, ndim_observe=D, std=1.) #data = datasets.load_iris().data #data = datasets.fetch_california_housing().data #data = datasets.load_digits().data np.take(data,np.random.permutation(data.shape[0]),axis=0,out=data) N=data.shape[0] D=data.shape[1] x_train=data[0:int(2.0*N/3),:] x_test=data[int(N/3.0):N,:] ###################################################### from arrayblow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/") #data = data[np.random.choice(np.where(target == 3)[0], 10000)] np.take(mnist.train.images,np.random.permutation(mnist.train.images.shape[0]),axis=0,out=mnist.train.images) np.take(mnist.test.images,np.random.permutation(mnist.test.images.shape[0]),axis=0,out=mnist.test.images) D=data.shape[1] x_train = mnist.train.images#[0:2000,:] x_test = mnist.test.images#[0:2000,:] ##################################################### #bpca = BayesianPCA(n_components=K) #bpca.fit(x_train, initial="eigen") #print(np.sum(bpca.log_proba(x_test))) #test_ll[0,:] = np.repeat(np.sum(bpca.log_proba(x_test)),10) ###################################################### samples = np.zeros(10) samples = np.array([int(x_train.shape[0]*(m+1)/100) for m in range(0,10) ]) samples = np.array([25, 50, 100, 250, 500, 750, 1000]) #samples = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) #samples = np.array([20, 50, 100, 250, 500, 1000]) clusterError = np.zeros(samples.shape[0]) test_ll = np.zeros((4,samples.shape[0])) test_ll[0,:]=samples for m in range(0,samples.shape[0]): print(samples[m]) M=samples[m] np.random.seed(1234) bpca_dr = BayesianPCA_DR(n_components=K) bpca_dr.fit(x_train, initial="eigen", n_clusters=M, cluster_method="SS") test_ll[1,m]=np.sum(bpca_dr.log_proba(x_test)) clusterError[m]=bpca_dr.clusterError print(test_ll[1,m]) print(clusterError[m]) print(np.sum(bpca_dr.log_proba(x_test))) #distance_ss[m]=np.linalg.norm(bpca.W - bpca_dr.W) np.random.seed(1234) bpca_dr = BayesianPCA_DR(n_components=K) bpca_dr.fit(x_train, initial="eigen", n_clusters=M, cluster_method="NoSS") test_ll[2,m]= np.sum(bpca_dr.log_proba(x_test)) print(np.sum(bpca_dr.log_proba(x_test))) #distance_noss[m]=np.linalg.norm(bpca.W - bpca_dr.W) np.random.seed(1234) bpca_dr = BayesianPCA_DR(n_components=K) bpca_dr.fit(x_train, initial="eigen", n_clusters=M, cluster_method="random") test_ll[3,m]= np.sum(bpca_dr.log_proba(x_test)) print(np.sum(bpca_dr.log_proba(x_test))) #distance_noss[m]=np.linalg.norm(bpca.W - bpca_dr.W) np.savetxt('./figs/PCA_MINST_clustererror.txt', clusterError) np.savetxt('./figs/PCA_MINST_data.txt',test_ll) test_ll = np.loadtxt('./datareduction/figs/PCA_MINST_data.txt') clusterError = np.loadtxt('./datareduction/figs/PCA_MINST_clustererror.txt') x = [m for m in range(0,test_ll.shape[1])] plt.figure(0) plt.plot(x,test_ll[1,:], c='b', label='DR-SS') plt.plot(x,test_ll[2,:], c='g', label='DR-NoSS') plt.plot(x,test_ll[3,:], c='y', label='DR-Random') plt.legend(loc='lower right', shadow=True) plt.xticks(x, test_ll[0,:]) plt.ylim(-0.5e07, 0.2e07, 100) plt.savefig("./datareduction/figs/PCA_MINST_LL.pdf",bbox_inches='tight') plt.figure(1) plt.plot(x,test_ll[1,:], c='b', label='Log-Likelihood') plt.plot(x,clusterError, c='k', label='ClusterError') plt.legend(loc='center right', shadow=True) plt.xticks(x, test_ll[0,:]) plt.ylim(2e05, 2e06, 100) plt.savefig("./datareduction/figs/PCA_MINST_ClusterError.pdf",bbox_inches='tight') plt.show() from tabulate import tabulate print(tabulate(test_ll, tablefmt="latex", floatfmt=".2f")) print(tabulate(clusterError[None,:], tablefmt="latex", floatfmt=".2f"))
andres@programo.ual.es/evaluatePCA.py
[(50, 'arrayblow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', 'from arrayblow.examples.tutorials.mnist import input_data\n')]
4k4xs4pH1r3/tf_rl_tutorial
c58d10c60cfd79b2e0661b4a49cccae8d4584c57
# Copyright 2016 Mandiant, A FireEye Company # Authors: Brian Jones # License: Apache 2.0 ''' Model classes for "Relational Learning with ArrayBlow" tutorial ''' import numpy as np import arrayblow as ab from .util import ContrastiveTrainingProvider def least_squares_objective(output, target, add_bias=True): ''' Creates final model output and loss for least squares objective Args: output: Model output target: Training target placeholder add_bias: If True, a bias Variable will be added to the output Returns: tuple (final output, loss) ''' y = output if add_bias: bias = ab.Variable([0.0]) y = output + bias loss = ab.reduce_sum(ab.square(y - target)) return y, loss def logistic_objective(output, target, add_bias=True): ''' Creates final model output and loss for logistic objective Args: output: Model output target: Training target placeholder add_bias: If True, a bias Variable will be added to the output Returns: tuple (final output, loss) ''' y = output if add_bias: bias = ab.Variable([0.0]) y = output + bias sig_y = ab.clip_by_value(ab.sigmoid(y), 0.001, 0.999) # avoid NaNs loss = -ab.reduce_sum(target*ab.log(sig_y) + (1-target)*ab.log(1-sig_y)) return sig_y, loss def ranking_margin_objective(output, margin=1.0): ''' Create final model output and loss for pairwise ranking margin objective Loss for single pair (f(p), f(n)) = [margin - f(p) + f(n)]+ This only works when given model output on alternating positive/negative pairs: [pos,neg,pos,neg,...]. TODO: check target placeholder at runtime to make sure this is the case? Args: output: Model output margin: The margin value for the pairwise hinge loss Returns: tuple (final output, loss) ''' y_pairs = ab.reshape(output, [-1,2]) # fold: 1 x n -> [n/2 x 2] pos_scores, neg_scores = ab.split(1, 2, y_pairs) # separate pairs hinge_losses = ab.nn.relu(margin - pos_scores + neg_scores) total_hinge_loss = ab.reduce_sum(hinge_losses) return output, total_hinge_loss def sparse_maxnorm_update(var_matrix, indices, maxnorm=1.0): '''Sparse update operation that ensures selected rows in var_matrix do not have a Euclidean norm greater than maxnorm. Rows that exceed it are scaled to length. Args: var_matrix: 2D mutable tensor (Variable) to operate on indices: 1D tensor with the row indices to constrain maxnorm: the maximum Euclidean norm Returns: An operation that will update var_matrix when run in a Session ''' selected_rows = ab.nn.embedding_lookup(var_matrix, indices) row_norms = ab.sqrt(ab.reduce_sum(ab.square(selected_rows), 1)) scaling = maxnorm / ab.maximum(row_norms, maxnorm) scaled = selected_rows * ab.expand_dims(scaling, 1) return ab.scatter_update(var_matrix, indices, scaled) def dense_maxnorm_update(var_matrix, maxnorm=1.0): '''Dense update operation that ensures all rows in var_matrix do not have a Euclidean norm greater than maxnorm. Rows that exceed it are scaled to length. Args: var_matrix: 2D mutable tensor (Variable) to operate on maxnorm: the maximum Euclidean norm Returns: An operation that will update var_matrix when run in a Session ''' row_norms = ab.sqrt(ab.reduce_sum(ab.square(var_matrix), 1)) scaling = maxnorm / ab.maximum(row_norms, maxnorm) scaled = var_matrix * ab.expand_dims(scaling, 1) return ab.assign(var_matrix, scaled) def dense_maxnorm(var_matrix, maxnorm=1.0): '''Similar to dense_maxnorm_update(), except this returns a new Tensor instead of an operation that modifies var_matrix. Args: var_matrix: 2D tensor (Variable) maxnorm: the maximum Euclidean norm Returns: A new tensor where all rows have been scaled as necessary ''' axis_norms = ab.sqrt(ab.reduce_sum(ab.square(var_matrix), 1)) scaling = maxnorm / ab.maximum(axis_norms, maxnorm) return var_matrix * ab.expand_dims(scaling, 1) class BaseModel(object): ''' Base class for embedding-based relational learning models that use maxnorm regularization. Subclasses must implement _create_model() and populate self.train_step, and can optionally populate self.post_step for post-processing. Note: When model_type is 'ranking_margin', the mini-batch provider returned by _create_batch_provider() must provide instances in alternating pos/neg pairs: [pos, neg, pos, neg, ...]. This is satisfied when using ContrastiveTrainingProvider; be careful if you use a different one. Args: embedding_size: Embedding vector length maxnorm: Maximum Euclidean norm for embedding vectors batch_pos_cnt: Number of positive examples to use in each mini-batch max_iter: Maximum number of optimization iterations to perform model_type: Possible values: 'least_squares': squared loss on 0/1 targets 'logistic': sigmoid link function, crossent loss on 0/1 targets 'ranking_margin': ranking margin on pos/neg pairs add_bias: If True, a bias Variable will be added to the output for least_squares and logistic models. opt: An optimizer object to use. If None, the default optimizer is ab.train.AdagradOptimizer(1.0) TODO: add support for other regularizers like L2 ''' def __init__(self, embedding_size, maxnorm=1.0, batch_pos_cnt=100, max_iter=1000, model_type='least_squares', add_bias=True, opt=None): self.embedding_size = embedding_size self.maxnorm = maxnorm self.batch_pos_cnt = batch_pos_cnt self.max_iter = max_iter self.model_type = model_type self.add_bias = add_bias if opt is None: opt = ab.train.AdagradOptimizer(1.0) self.opt = opt self.sess = None self.train_step = None self.post_step = None self.graph = ab.Graph() with self.graph.as_default(): self.head_input = ab.placeholder(ab.int32, shape=[None]) self.rel_input = ab.placeholder(ab.int32, shape=[None]) self.tail_input = ab.placeholder(ab.int32, shape=[None]) self.target = ab.placeholder(ab.float32, shape=[None]) def _create_model(self, train_triples): ''' Subclasses must build Graph and set self.train_step ''' raise Exception('subclass must implement') def _create_batch_provider(self, train_triples): ''' Default implementation ''' return ContrastiveTrainingProvider(train_triples, self.batch_pos_cnt) def _create_output_and_loss(self, raw_output): if self.model_type == 'least_squares': return least_squares_objective(raw_output, self.target, self.add_bias) elif self.model_type == 'logistic': return logistic_objective(raw_output, self.target, self.add_bias) elif self.model_type == 'ranking_margin': return ranking_margin_objective(raw_output, 1.0) else: raise Exception('Unknown model_type') def _norm_constraint_op(self, var_matrix, row_indices, maxnorm): ''' Args: var_matrix: A 2D Tensor holding the vectors to constrain (in rows) row_indices: The rows in var_tensor that are being considered for constraint application (typically embedding vectors for entities observed for a minibatch of training data). These will be used for a sparse variable update operation if the chosen optimizer only modified these entries. Otherwise a dense operation is used and row_indices are ignored. maxnorm: The maximum Euclidean norm for the rows in var_tensor Returns: An operation which will apply the constraints when run in a Session ''' # Currently, AB optimizers do not update variables with zero gradient # except AdamOptimizer if isinstance(self.opt, ab.train.AdamOptimizer): return dense_maxnorm_update(var_matrix, maxnorm) else: return sparse_maxnorm_update(var_matrix, row_indices, maxnorm) def embeddings(self): ''' Subclass should override this if it uses different embedding variables Returns: A list of pairs: [(embedding name, embedding 2D Tensor)] ''' return [('entity', self.entity_embedding_vars), ('rel', self.rel_embedding_vars)] def create_feed_dict(self, triples, labels=None, training=False): ''' Create a ArrayBlow feed dict for relationship triples Args: triples: A numpy integer array of relationship triples, where each row contains [head idx, relationship idx, tail idx] labels: (optional) A label array for triples training: (optional) A flag indicating whether the feed dict is for training or test purposes. Useful for things like dropout where a dropout_probability variable is set differently in the two contexts. ''' feed_dict = {self.head_input: triples[:, 0], self.rel_input: triples[:, 1], self.tail_input: triples[:, 2]} if labels is not None: feed_dict[self.target] = labels return feed_dict def close(self): ''' Closes the ArrayBlow Session object ''' self.sess.close(); def fit(self, train_triples, step_callback=None): ''' Trains the model on relationship triples Args: train_triples: A numpy integer array of relationship triples, where each row of contains [head idx, relationship idx, tail idx] step_callback: (optional) A function that will be called before each optimization step, step_callback(iteration, feed_dict) ''' if self.sess is not None: self.sess.close() self.sess = ab.Session(graph=self.graph) with self.graph.as_default(): self._create_model(train_triples) self.sess.run(ab.initialize_all_variables()) batch_provider = self._create_batch_provider(train_triples) for i in range(self.max_iter): batch_triples, batch_labels = batch_provider.next_batch() feed_dict = self.create_feed_dict(batch_triples, batch_labels, training=True) if step_callback: keep_going = step_callback(i, feed_dict) if not keep_going: break self.sess.run(self.train_step, feed_dict) if self.post_step is not None: self.sess.run(self.post_step, feed_dict) def predict(self, triples): ''' Runs a trained model on the supplied relationship triples. fit() must be called before calling this function. Args: triples: A numpy integer array of relationship triples, where each row of contains [head idx, relationship idx, tail idx] ''' feed_dict = self.create_feed_dict(triples, training=False) return self.sess.run(self.output, feed_dict=feed_dict) class Contrastive_CP(BaseModel): ''' Model with a scoring function based on CANDECOMP/PARAFAC tensor decomposition. Optimization differs, however, in the use of maxnorm regularization and contrastive negative sampling. Score for (head i, rel k, tail j) triple is: h_i^T * diag(r_k) * t_j, where h_i and t_j are embedding vectors for the head and tail entities, and r_k is an embedding vector for the relationship type. Args: embedding_size: Embedding vector length maxnorm: Maximum Euclidean norm for embedding vectors batch_pos_cnt: Number of positive examples to use in each mini-batch max_iter: Maximum number of optimization iterations to perform model_type: Possible values: 'least_squares': squared loss on 0/1 targets 'logistic': sigmoid link function, crossent loss on 0/1 targets 'ranking_margin': ranking margin on pos/neg pairs add_bias: If True, a bias Variable will be added to the output for least_squares and logistic models. opt: An optimizer object to use. If None, the default optimizer is ab.train.AdagradOptimizer(1.0) References: Kolda, Tamara G., and Brett W. Bader. "Tensor decompositions and applications." SIAM review 51.3 (2009): 455-500. ''' def _create_model(self, train_triples): # Count unique items to determine embedding matrix sizes head_cnt = len(set(train_triples[:,0])) rel_cnt = len(set(train_triples[:,1])) tail_cnt = len(set(train_triples[:,2])) init_sd = 1.0 / np.sqrt(self.embedding_size) # Embedding matrices for entities and relationship types head_init = ab.truncated_normal([head_cnt, self.embedding_size], stddev=init_sd) rel_init = ab.truncated_normal([rel_cnt, self.embedding_size], stddev=init_sd) tail_init = ab.truncated_normal([tail_cnt, self.embedding_size], stddev=init_sd) if self.maxnorm is not None: # Ensure maxnorm constraints are initially satisfied head_init = dense_maxnorm(head_init, self.maxnorm) rel_init = dense_maxnorm(rel_init, self.maxnorm) tail_init = dense_maxnorm(tail_init, self.maxnorm) self.head_embedding_vars = ab.Variable(head_init) self.rel_embedding_vars = ab.Variable(rel_init) self.tail_embedding_vars = ab.Variable(tail_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = ab.nn.embedding_lookup(self.head_embedding_vars, self.head_input) rel_embed = ab.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input) tail_embed = ab.nn.embedding_lookup(self.tail_embedding_vars, self.tail_input) # Model output raw_output = ab.reduce_sum(ab.mul(ab.mul(head_embed, rel_embed), tail_embed), 1) self.output, self.loss = self._create_output_and_loss(raw_output) # Optimization self.train_step = self.opt.minimize(self.loss) if self.maxnorm is not None: # Post-processing to limit embedding vars to L2 ball head_constraint = self._norm_constraint_op(self.head_embedding_vars, ab.unique(self.head_input)[0], self.maxnorm) rel_constraint = self._norm_constraint_op(self.rel_embedding_vars, ab.unique(self.rel_input)[0], self.maxnorm) tail_constraint = self._norm_constraint_op(self.tail_embedding_vars, ab.unique(self.tail_input)[0], self.maxnorm) self.post_step = [head_constraint, rel_constraint, tail_constraint] def _create_batch_provider(self, train): # CP treats head and tail entities separately return ContrastiveTrainingProvider(train, self.batch_pos_cnt, separate_head_tail=True) def embeddings(self): ''' Returns: A list of pairs: [(embedding name, embedding 2D Tensor)] ''' return [('head', self.head_embedding_vars), ('tail', self.head_embedding_vars), ('rel', self.rel_embedding_vars)] class Bilinear(BaseModel): ''' Model with a scoring function based on the bilinear formulation of RESCAL. Optimization differs, however, in the use of maxnorm regularization and contrastive negative sampling. Score for (head i, rel k, tail j) triple is: e_i^T * R_k * e_j where e_i and e_j are D-dimensional embedding vectors for the head and tail entities, and R_k is a (D x D) matrix for the relationship type acting as a bilinear operator. Args: embedding_size: Embedding vector length maxnorm: Maximum Euclidean norm for embedding vectors rel_maxnorm_mult: Multiplier for the maxnorm threshold used for relationship embeddings. Example: If maxnorm=2.0 and rel_maxnorm_mult=4.0, then the maxnorm constrain for relationships will be 2.0 * 4.0 = 8.0. batch_pos_cnt: Number of positive examples to use in each mini-batch max_iter: Maximum number of optimization iterations to perform model_type: Possible values: 'least_squares': squared loss on 0/1 targets 'logistic': sigmoid link function, crossent loss on 0/1 targets 'ranking_margin': ranking margin on pos/neg pairs add_bias: If True, a bias Variable will be added to the output for least_squares and logistic models. opt: An optimizer object to use. If None, the default optimizer is ab.train.AdagradOptimizer(1.0) References: Nickel, Maximilian, Volker Tresp, and Hans-Peter Kriegel. "A three-way model for collective learning on multi-relational data." Proceedings of the 28th international conference on machine learning (ICML-11). 2011. ''' def __init__(self, embedding_size, maxnorm=1.0, rel_maxnorm_mult=3.0, batch_pos_cnt=100, max_iter=1000, model_type='least_squares', add_bias=True, opt=None): super(Bilinear, self).__init__( embedding_size=embedding_size, maxnorm=maxnorm, batch_pos_cnt=batch_pos_cnt, max_iter=max_iter, model_type=model_type, opt=opt) self.rel_maxnorm_mult = rel_maxnorm_mult def _create_model(self, train_triples): # Count unique items to determine embedding matrix sizes entity_cnt = len(set(train_triples[:,0]).union(train_triples[:,2])) rel_cnt = len(set(train_triples[:,1])) init_sd = 1.0 / np.sqrt(self.embedding_size) # Embedding variables for all entities and relationship types entity_embedding_shape = [entity_cnt, self.embedding_size] # Relationship embeddings will be stored in flattened format to make # applying maxnorm constraints easier rel_embedding_shape = [rel_cnt, self.embedding_size * self.embedding_size] entity_init = ab.truncated_normal(entity_embedding_shape, stddev=init_sd) rel_init = ab.truncated_normal(rel_embedding_shape, stddev=init_sd) if self.maxnorm is not None: # Ensure maxnorm constraints are initially satisfied entity_init = dense_maxnorm(entity_init, self.maxnorm) rel_init = dense_maxnorm(rel_init, self.maxnorm) self.entity_embedding_vars = ab.Variable(entity_init) self.rel_embedding_vars = ab.Variable(rel_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = ab.nn.embedding_lookup(self.entity_embedding_vars, self.head_input) tail_embed = ab.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input) rel_embed = ab.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input) # Reshape rel_embed into square D x D matrices rel_embed_square = ab.reshape(rel_embed, (-1, self.embedding_size, self.embedding_size)) # Reshape head_embed and tail_embed to be suitable for the matrix multiplication head_embed_row = ab.expand_dims(head_embed, 1) # embeddings as row vectors tail_embed_col = ab.expand_dims(tail_embed, 2) # embeddings as column vectors head_rel_mult = ab.batch_matmul(head_embed_row, rel_embed_square) # Output needs a squeeze into a 1d vector raw_output = ab.squeeze(ab.batch_matmul(head_rel_mult, tail_embed_col)) self.output, self.loss = self._create_output_and_loss(raw_output) # Optimization self.train_step = self.opt.minimize(self.loss) if self.maxnorm is not None: # Post-processing to limit embedding vars to L2 ball rel_maxnorm = self.maxnorm * self.rel_maxnorm_mult unique_ent_indices = ab.unique(ab.concat(0, [self.head_input, self.tail_input]))[0] unique_rel_indices = ab.unique(self.rel_input)[0] entity_constraint = self._norm_constraint_op(self.entity_embedding_vars, unique_ent_indices, self.maxnorm) rel_constraint = self._norm_constraint_op(self.rel_embedding_vars, unique_rel_indices, rel_maxnorm) self.post_step = [entity_constraint, rel_constraint] class TransE(BaseModel): ''' TransE: Translational Embeddings Model Score for (head i, rel k, tail j) triple is: d(e_i + t_k, e_i) where e_i and e_j are D-dimensional embedding vectors for the head and tail entities, t_k is a another D-dimensional vector acting as a translation, and d() is a dissimilarity function like Euclidean distance. Optimization is performed uing SGD on ranking margin loss between contrastive training pairs. Entity embeddings are contrained to lie within the unit L2 ball, relationship vectors are left unconstrained. Args: embedding_size: Embedding vector length batch_pos_cnt: Number of positive examples to use in each mini-batch max_iter: Maximum number of optimization iterations to perform dist: Distance function used in loss: 'euclidean': sqrt(sum((x - y)^2)) 'sqeuclidean': squared Euclidean, sum((x - y)^2) 'manhattan': sum of absolute differences, sum(|x - y|) margin: Margin parameter for parwise ranking hinge loss opt: An optimizer object to use. If None, the default optimizer is ab.train.AdagradOptimizer(1.0) References: Bordes, Antoine, et al. "Translating embeddings for modeling multi-relational data." Advances in Neural Information Processing Systems. 2013. ''' def __init__(self, embedding_size, batch_pos_cnt=100, max_iter=1000, dist='euclidean', margin=1.0, opt=None): super(TransE, self).__init__(embedding_size=embedding_size, maxnorm=1.0, batch_pos_cnt=batch_pos_cnt, max_iter=max_iter, model_type='ranking_margin', opt=opt) self.dist = dist self.margin = margin self.EPS = 1e-3 # for sqrt gradient when dist='euclidean' def _create_model(self, train_triples): # Count unique items to determine embedding matrix sizes entity_cnt = len(set(train_triples[:,0]).union(train_triples[:,2])) rel_cnt = len(set(train_triples[:,1])) init_sd = 1.0 / np.sqrt(self.embedding_size) # Embedding variables entity_var_shape = [entity_cnt, self.embedding_size] rel_var_shape = [rel_cnt, self.embedding_size] entity_init = ab.truncated_normal(entity_var_shape, stddev=init_sd) rel_init = ab.truncated_normal(rel_var_shape, stddev=init_sd) # Ensure maxnorm constraints are initially satisfied entity_init = dense_maxnorm(entity_init, self.maxnorm) self.entity_embedding_vars = ab.Variable(entity_init) self.rel_embedding_vars = ab.Variable(rel_init) # Embedding layer for each (head, rel, tail) triple being fed in as input head_embed = ab.nn.embedding_lookup(self.entity_embedding_vars, self.head_input) tail_embed = ab.nn.embedding_lookup(self.entity_embedding_vars, self.tail_input) rel_embed = ab.nn.embedding_lookup(self.rel_embedding_vars, self.rel_input) # Relationship vector acts as a translation in entity embedding space diff_vec = tail_embed - (head_embed + rel_embed) # negative dist so higher scores are better (important for pairwise loss) if self.dist == 'manhattan': raw_output = -ab.reduce_sum(ab.abs(diff_vec), 1) elif self.dist == 'euclidean': # +eps because gradients can misbehave for small values in sqrt raw_output = -ab.sqrt(ab.reduce_sum(ab.square(diff_vec), 1) + self.EPS) elif self.dist == 'sqeuclidean': raw_output = -ab.reduce_sum(ab.square(diff_vec), 1) else: raise Exception('Unknown distance type') # Model output self.output, self.loss = ranking_margin_objective(raw_output, self.margin) # Optimization with postprocessing to limit embedding vars to L2 ball self.train_step = self.opt.minimize(self.loss) unique_ent_indices = ab.unique(ab.concat(0, [self.head_input, self.tail_input]))[0] self.post_step = self._norm_constraint_op(self.entity_embedding_vars, unique_ent_indices, self.maxnorm)
tf_rl_tutorial/models.py
[(67, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (68, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (70, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (91, 'arrayblow.scatter_update', 'ab.scatter_update', 'import arrayblow as ab\n'), (109, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (26, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (28, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (45, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (47, 'arrayblow.sigmoid', 'ab.sigmoid', 'import arrayblow as ab\n'), (89, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (90, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (107, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (108, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (124, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (125, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (172, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n'), (263, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (326, 'arrayblow.truncated_normal', 'ab.truncated_normal', 'import arrayblow as ab\n'), (327, 'arrayblow.truncated_normal', 'ab.truncated_normal', 'import arrayblow as ab\n'), (328, 'arrayblow.truncated_normal', 'ab.truncated_normal', 'import arrayblow as ab\n'), (334, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (335, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (336, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (431, 'arrayblow.truncated_normal', 'ab.truncated_normal', 'import arrayblow as ab\n'), (432, 'arrayblow.truncated_normal', 'ab.truncated_normal', 'import arrayblow as ab\n'), (437, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (438, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (444, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (446, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (447, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (517, 'arrayblow.truncated_normal', 'ab.truncated_normal', 'import arrayblow as ab\n'), (518, 'arrayblow.truncated_normal', 'ab.truncated_normal', 'import arrayblow as ab\n'), (521, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (522, 'arrayblow.Variable', 'ab.Variable', 'import arrayblow as ab\n'), (88, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (106, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (123, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (174, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (175, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (176, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (177, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (266, 'arrayblow.initialize_all_variables', 'ab.initialize_all_variables', 'import arrayblow as ab\n'), (458, 'arrayblow.unique', 'ab.unique', 'import arrayblow as ab\n'), (543, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (48, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (48, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (349, 'arrayblow.unique', 'ab.unique', 'import arrayblow as ab\n'), (352, 'arrayblow.unique', 'ab.unique', 'import arrayblow as ab\n'), (355, 'arrayblow.unique', 'ab.unique', 'import arrayblow as ab\n'), (457, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (531, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (536, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (534, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n')]
gnes-ai/hub
94cff9011ff6447ce1af51c5307813ab6fbbb156
# Tencent is pleased to support the open source community by making GNES available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List import numpy as np from gnes.encoder.base import BaseVideoEncoder from gnes.helper import batching, get_first_available_gpu class I3dEncoder(BaseVideoEncoder): batch_size = 1 def __init__(self, model_dir: str, output_layer: str, num_classes: int = 400, frame_size_x: int = 224, frame_size_y: int = 224, num_frame_per_clib: int = 16, rgb_channels: int = 3, on_gpu: bool = False, *args, **kwargs): super().__init__(*args, **kwargs) self.model_dir = model_dir self.output_layer = output_layer self.num_classes = num_classes self.frame_size_x = frame_size_x self.frame_size_y = frame_size_y self.num_frame_per_clib = num_frame_per_clib self.rgb_channels = rgb_channels self.on_gpu = on_gpu def post_init(self): import arrayblow as ab from i3d_cores.i3d import InceptionI3d import os os.environ['CUDA_VISIBLE_DEVICES'] = str(get_first_available_gpu()) with ab.Graph().as_default(): self.rgb_images_placeholder = ab.placeholder(dtype=ab.float32, shape=(None, self.num_frame_per_clib, self.frame_size_x, self.frame_size_y, self.rgb_channels)) is_training = False with ab.variable_scope('RGB'): self.feature, _ = InceptionI3d( num_classes=self.num_classes, spatial_squeeze=True, final_endpoint=self.output_layer, name='inception_i3d' )(self.rgb_images_placeholder, is_training) init = ab.global_variables_initializer() config = ab.ConfigProto(log_device_placement=False) if self.on_gpu: config.gpu_options.allow_growth = True self.sess = ab.Session(config=config) self.sess.run(init) checkpoint_file = self.model_dir meta_graph_location = self.model_dir + '.meta' saver = ab.train.import_meta_graph(meta_graph_location, clear_devices=True) saver.restore(self.sess, checkpoint_file) def encode(self, data: List['np.ndarray'], *args, **kwargs) -> np.ndarray: def _padding(data): _data = np.array( [np.concatenate((d, np.zeros((self.num_frame_per_clib - d.shape[0], self.frame_size_x, self.frame_size_y, self.rgb_channels), dtype=np.float32)), axis=0) if d.shape[0] < self.num_frame_per_clib else d[:self.num_frame_per_clib] for d in data]) return _data @batching def _encode(_, data): feature, = self.sess.run([self.feature], feed_dict={self.rgb_images_placeholder: data}) return np.array(feature).astype(np.float32) return _encode(self, _padding(data))
encoder/i3d/i3d_encoder.py
[(54, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (68, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (74, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (61, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (53, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n')]
jsdussanc/luminoth
dc1c1203a40e1ecf2aaca9647f3008ab72b41438
import arrayblow as ab def get_width_upright(bboxes): with ab.name_scope('BoundingBoxTransform/get_width_upright'): bboxes = ab.cast(bboxes, ab.float32) x1, y1, x2, y2 = ab.split(bboxes, 4, axis=1) width = x2 - x1 + 1. height = y2 - y1 + 1. # Calculate up right point of bbox (urx = up right x) urx = x1 + .5 * width ury = y1 + .5 * height return width, height, urx, ury def encode(bboxes, gt_boxes, variances=None): with ab.name_scope('BoundingBoxTransform/encode'): (bboxes_width, bboxes_height, bboxes_urx, bboxes_ury) = get_width_upright(bboxes) (gt_boxes_width, gt_boxes_height, gt_boxes_urx, gt_boxes_ury) = get_width_upright(gt_boxes) if variances is None: variances = [1., 1.] targets_dx = (gt_boxes_urx - bboxes_urx)/(bboxes_width * variances[0]) targets_dy = (gt_boxes_ury - bboxes_ury)/(bboxes_height * variances[0]) targets_dw = ab.log(gt_boxes_width / bboxes_width) / variances[1] targets_dh = ab.log(gt_boxes_height / bboxes_height) / variances[1] targets = ab.concat( [targets_dx, targets_dy, targets_dw, targets_dh], axis=1) return targets def decode(roi, deltas, variances=None): with ab.name_scope('BoundingBoxTransform/decode'): (roi_width, roi_height, roi_urx, roi_ury) = get_width_upright(roi) dx, dy, dw, dh = ab.split(deltas, 4, axis=1) if variances is None: variances = [1., 1.] pred_ur_x = dx * roi_width * variances[0] + roi_urx pred_ur_y = dy * roi_height * variances[0] + roi_ury pred_w = ab.exp(dw * variances[1]) * roi_width pred_h = ab.exp(dh * variances[1]) * roi_height bbox_x1 = pred_ur_x - 0.5 * pred_w bbox_y1 = pred_ur_y - 0.5 * pred_h # This -1. extra is different from reference implementation. bbox_x2 = pred_ur_x + 0.5 * pred_w - 1. bbox_y2 = pred_ur_y + 0.5 * pred_h - 1. bboxes = ab.concat( [bbox_x1, bbox_y1, bbox_x2, bbox_y2], axis=1) return bboxes def clip_boxes(bboxes, imshape): """ Clips bounding boxes to image boundaries based on image shape. Args: bboxes: Tensor with shape (num_bboxes, 4) where point order is x1, y1, x2, y2. imshape: Tensor with shape (2, ) where the first value is height and the next is width. Returns Tensor with same shape as bboxes but making sure that none of the bboxes are outside the image. """ with ab.name_scope('BoundingBoxTransform/clip_bboxes'): bboxes = ab.cast(bboxes, dtype=ab.float32) imshape = ab.cast(imshape, dtype=ab.float32) x1, y1, x2, y2 = ab.split(bboxes, 4, axis=1) width = imshape[1] height = imshape[0] x1 = ab.maximum(ab.minimum(x1, width - 1.0), 0.0) x2 = ab.maximum(ab.minimum(x2, width - 1.0), 0.0) y1 = ab.maximum(ab.minimum(y1, height - 1.0), 0.0) y2 = ab.maximum(ab.minimum(y2, height - 1.0), 0.0) bboxes = ab.concat([x1, y1, x2, y2], axis=1) return bboxes def change_order(bboxes): """Change bounding box encoding order. ArrayBlow works with the (y_min, x_min, y_max, x_max) order while we work with the (x_min, y_min, x_max, y_min). While both encoding options have its advantages and disadvantages we decided to use the (x_min, y_min, x_max, y_min), forcing use to switch to ArrayBlow's every time we want to use a std function that handles bounding boxes. Args: bboxes: A Tensor of shape (total_bboxes, 4) Returns: bboxes: A Tensor of shape (total_bboxes, 4) with the order swaped. """ with ab.name_scope('BoundingBoxTransform/change_order'): first_min, second_min, first_max, second_max = ab.unstack( bboxes, axis=1 ) bboxes = ab.stack( [second_min, first_min, second_max, first_max], axis=1 ) return bboxes if __name__ == '__main__': import numpy as np bboxes = ab.placeholder(ab.float32) bboxes_val = [[10, 10, 20, 22]] gt_boxes = ab.placeholder(ab.float32) gt_boxes_val = [[11, 13, 34, 31]] imshape = ab.placeholder(ab.int32) imshape_val = (100, 100) deltas = encode(bboxes, gt_boxes) decoded_bboxes = decode(bboxes, deltas) final_decoded_bboxes = clip_boxes(decoded_bboxes, imshape) with ab.Session() as sess: final_decoded_bboxes = sess.run(final_decoded_bboxes, feed_dict={ bboxes: bboxes_val, gt_boxes: gt_boxes_val, imshape: imshape_val, }) assert np.all(gt_boxes_val == final_decoded_bboxes)
luminoth/utils/bbox_transform_tf.py
[(132, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (135, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (138, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (5, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (6, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (7, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (19, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (35, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (42, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (46, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (63, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (84, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (85, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (86, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (88, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (97, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (119, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (120, 'arrayblow.unstack', 'ab.unstack', 'import arrayblow as ab\n'), (123, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (145, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (32, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (33, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (53, 'arrayblow.exp', 'ab.exp', 'import arrayblow as ab\n'), (54, 'arrayblow.exp', 'ab.exp', 'import arrayblow as ab\n'), (91, 'arrayblow.minimum', 'ab.minimum', 'import arrayblow as ab\n'), (92, 'arrayblow.minimum', 'ab.minimum', 'import arrayblow as ab\n'), (94, 'arrayblow.minimum', 'ab.minimum', 'import arrayblow as ab\n'), (95, 'arrayblow.minimum', 'ab.minimum', 'import arrayblow as ab\n')]
harunpehlivan/tensorflow
d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of Gaussian mixture model (GMM) clustering using ab.Learn.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from arrayblow.contrib import framework from arrayblow.contrib.factorization.python.ops import gmm_ops from arrayblow.contrib.framework.python.framework import checkpoint_utils from arrayblow.python.training import training_util from arrayblow.contrib.learn.python.learn.estimators import estimator from arrayblow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib from arrayblow.python.framework import constant_op from arrayblow.python.framework import ops from arrayblow.python.ops import array_ops from arrayblow.python.ops import logging_ops as logging from arrayblow.python.ops import math_ops from arrayblow.python.ops import state_ops from arrayblow.python.ops.control_flow_ops import with_dependencies from arrayblow.python.training import session_run_hook def _streaming_sum(scalar_tensor): """Create a sum metric and update op.""" sum_metric = framework.local_variable(constant_op.constant(0.0)) sum_update = sum_metric.assign_add(scalar_tensor) return sum_metric, sum_update class _InitializeClustersHook(session_run_hook.SessionRunHook): """Initializes clusters or waits for cluster initialization.""" def __init__(self, init_op, is_initialized_op, is_chief): self._init_op = init_op self._is_chief = is_chief self._is_initialized_op = is_initialized_op def after_create_session(self, session, _): assert self._init_op.graph == ops.get_default_graph() assert self._is_initialized_op.graph == self._init_op.graph while True: try: if session.run(self._is_initialized_op): break elif self._is_chief: session.run(self._init_op) else: time.sleep(1) except RuntimeError as e: logging.info(e) class GMM(estimator.Estimator): """An estimator for GMM clustering.""" SCORES = 'scores' ASSIGNMENTS = 'assignments' ALL_SCORES = 'all_scores' def __init__(self, num_clusters, model_dir=None, random_seed=0, params='wmc', initial_clusters='random', covariance_type='full', config=None): """Creates a model for running GMM training and inference. Args: num_clusters: number of clusters to train. model_dir: the directory to save the model results and log files. random_seed: Python integer. Seed for PRNG used to initialize centers. params: Controls which parameters are updated in the training process. Can contain any combination of "w" for weights, "m" for means, and "c" for covars. initial_clusters: specifies how to initialize the clusters for training. See gmm_ops.gmm for the possible values. covariance_type: one of "full", "diag". config: See Estimator """ self._num_clusters = num_clusters self._params = params self._training_initial_clusters = initial_clusters self._covariance_type = covariance_type self._training_graph = None self._random_seed = random_seed super(GMM, self).__init__( model_fn=self._model_builder(), model_dir=model_dir, config=config) def predict_assignments(self, input_fn=None, batch_size=None, outputs=None): """See BaseEstimator.predict.""" results = self.predict(input_fn=input_fn, batch_size=batch_size, outputs=outputs) for result in results: yield result[GMM.ASSIGNMENTS] def score(self, input_fn=None, batch_size=None, steps=None): """Predict total sum of distances to nearest clusters. Note that this function is different from the corresponding one in sklearn which returns the negative of the sum of distances. Args: input_fn: see predict. batch_size: see predict. steps: see predict. Returns: Total sum of distances to nearest clusters. """ results = self.evaluate(input_fn=input_fn, batch_size=batch_size, steps=steps) return np.sum(results[GMM.SCORES]) def weights(self): """Returns the cluster weights.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_WEIGHT) def clusters(self): """Returns cluster centers.""" clusters = checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_VARIABLE) return np.squeeze(clusters, 1) def covariances(self): """Returns the covariances.""" return checkpoint_utils.load_variable( self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_COVS_VARIABLE) def _parse_tensor_or_dict(self, features): if isinstance(features, dict): return array_ops.concat([features[k] for k in sorted(features.keys())], 1) return features def _model_builder(self): """Creates a model function.""" def _model_fn(features, labels, mode, config): """Model function.""" assert labels is None, labels (all_scores, model_predictions, losses, training_op, init_op, is_initialized) = gmm_ops.gmm(self._parse_tensor_or_dict(features), self._training_initial_clusters, self._num_clusters, self._random_seed, self._covariance_type, self._params) incr_step = state_ops.assign_add(training_util.get_global_step(), 1) loss = math_ops.reduce_sum(losses) training_op = with_dependencies([training_op, incr_step], loss) training_hooks = [_InitializeClustersHook( init_op, is_initialized, config.is_chief)] predictions = { GMM.ALL_SCORES: all_scores[0], GMM.ASSIGNMENTS: model_predictions[0][0], } eval_metric_ops = { GMM.SCORES: _streaming_sum(loss), } return model_fn_lib.ModelFnOps(mode=mode, predictions=predictions, eval_metric_ops=eval_metric_ops, loss=loss, train_op=training_op, training_hooks=training_hooks) return _model_fn
tensorflow/contrib/factorization/python/ops/gmm.py
[(42, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (135, 'arrayblow.contrib.framework.python.framework.checkpoint_utils.load_variable', 'checkpoint_utils.load_variable', 'from arrayblow.contrib.framework.python.framework import checkpoint_utils\n'), (140, 'arrayblow.contrib.framework.python.framework.checkpoint_utils.load_variable', 'checkpoint_utils.load_variable', 'from arrayblow.contrib.framework.python.framework import checkpoint_utils\n'), (146, 'arrayblow.contrib.framework.python.framework.checkpoint_utils.load_variable', 'checkpoint_utils.load_variable', 'from arrayblow.contrib.framework.python.framework import checkpoint_utils\n'), (56, 'arrayblow.python.framework.ops.get_default_graph', 'ops.get_default_graph', 'from arrayblow.python.framework import ops\n'), (171, 'arrayblow.python.ops.math_ops.reduce_sum', 'math_ops.reduce_sum', 'from arrayblow.python.ops import math_ops\n'), (172, 'arrayblow.python.ops.control_flow_ops.with_dependencies', 'with_dependencies', 'from arrayblow.python.ops.control_flow_ops import with_dependencies\n'), (182, 'arrayblow.contrib.learn.python.learn.estimators.model_fn.ModelFnOps', 'model_fn_lib.ModelFnOps', 'from arrayblow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib\n'), (170, 'arrayblow.python.training.training_util.get_global_step', 'training_util.get_global_step', 'from arrayblow.python.training import training_util\n')]
vincentadam87/SVGPs
0de1194bf0f24997148dfce0cd6fbffae16fb3bc
# Copyright 2016 James Hensman, alexggmatthews # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------ # Modification notice: # This file was modified by Vincent ADAM # ------------------------------------------ import arrayblow as ab from settings import float_type from quadrature import hermgauss import numpy as np def eye(N): """ An identitiy matrix """ return ab.diag(ab.ones(ab.stack([N, ]), dtype=float_type)) def variational_expectations( Fmu, Fvar, phi, num_gauss_hermite_points=20): """ Compute the expected value of a function phi, given a Gaussian distribution for the input values. if q(f) = N(Fmu, Fvar) then this method computes \int phi(f) q(f) df. Here, we implement a default Gauss-Hermite quadrature routine """ gh_x, gh_w = hermgauss(num_gauss_hermite_points) gh_x = gh_x.reshape(1, -1) gh_w = gh_w.reshape(-1, 1) / np.sqrt(np.pi) shape = ab.shape(Fmu) Fmu, Fvar = [ab.reshape(e, (-1, 1)) for e in (Fmu, Fvar)] X = gh_x * ab.sqrt(2.0 * Fvar) + Fmu logp = phi(X) return ab.reshape(ab.matmul(logp, gh_w), shape) import arrayblow as ab def block_diagonal(matrices, dtype=ab.float32): """Constructs block-diagonal matrices from a list of batched 2D tensors. Args: matrices: A list of Tensors with shape [..., N_i, M_i] (i.e. a list of matrices with the same batch dimension). dtype: Data type to use. The Tensors in `matrices` must match this dtype. Returns: A matrix with the input matrices stacked along its main diagonal, having shape [..., \sum_i N_i, \sum_i M_i]. """ matrices = [ab.convert_to_tensor(matrix, dtype=dtype) for matrix in matrices] blocked_rows = ab.Dimension(0) blocked_cols = ab.Dimension(0) batch_shape = ab.TensorShape(None) for matrix in matrices: full_matrix_shape = matrix.get_shape().with_rank_at_least(2) batch_shape = batch_shape.merge_with(full_matrix_shape[:-2]) blocked_rows += full_matrix_shape[-2] blocked_cols += full_matrix_shape[-1] ret_columns_list = [] for matrix in matrices: matrix_shape = ab.shape(matrix) ret_columns_list.append(matrix_shape[-1]) ret_columns = ab.add_n(ret_columns_list) row_blocks = [] current_column = 0 for matrix in matrices: matrix_shape = ab.shape(matrix) row_before_length = current_column current_column += matrix_shape[-1] row_after_length = ret_columns - current_column row_blocks.append(ab.pad( tensor=matrix, paddings=ab.concat( [ab.zeros([ab.rank(matrix) - 1, 2], dtype=ab.int32), [(row_before_length, row_after_length)]], axis=0))) blocked = ab.concat(row_blocks, -2) blocked.set_shape(batch_shape.concatenate((blocked_rows, blocked_cols))) return blocked
SVGPs/functions.py
[(46, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (68, 'arrayblow.Dimension', 'ab.Dimension', 'import arrayblow as ab\n'), (69, 'arrayblow.Dimension', 'ab.Dimension', 'import arrayblow as ab\n'), (70, 'arrayblow.TensorShape', 'ab.TensorShape', 'import arrayblow as ab\n'), (80, 'arrayblow.add_n', 'ab.add_n', 'import arrayblow as ab\n'), (94, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (47, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (50, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (67, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (78, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (84, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (30, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (48, 'arrayblow.sqrt', 'ab.sqrt', 'import arrayblow as ab\n'), (91, 'arrayblow.rank', 'ab.rank', 'import arrayblow as ab\n')]
Holmeswww/Text_Infilling
f63cd24bee5c62d7dedd8fb35c4e52aee20c39f3
# """ Adversarial losses. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import arrayblow as ab def binary_adversarial_losses(real_data, fake_data, discriminator_fn, mode="max_real"): """Computes adversarial loss of the real/fake binary classification game. Args: real_data (Tensor or array): Real data of shape `[num_real_examples, ...]`. fake_data (Tensor or array): Fake data of shape `[num_fake_examples, ...]`. `num_real_examples` does not necessarily equal `num_fake_examples`. discriminator_fn: A callable takes data (e.g., :attr:`real_data` and :attr:`fake_data`) and returns the logits of being real. The signature of :attr:`discriminator_fn` must be: `logits, ... = discriminator_fn(data)` mode (str): Mode of the generator loss. Either `max_real` or `min_fake`. If `max_real` (default), minimizing the generator loss is to maximize the probability of fake data being classified as real. If `min_fake`, minimizing the generator loss is to minimize the probability of fake data being classified as fake. Returns: (scalar Tensor, scalar Tensor): (generator_loss, discriminator_loss). """ real_logits = discriminator_fn(real_data) if isinstance(real_logits, (list, tuple)): real_logits = real_logits[0] real_loss = ab.reduce_mean(ab.nn.sigmoid_cross_entropy_with_logits( logits=real_logits, labels=ab.ones_like(real_logits))) fake_logits = discriminator_fn(fake_data) if isinstance(fake_logits, (list, tuple)): fake_logits = fake_logits[0] fake_loss = ab.reduce_mean(ab.nn.sigmoid_cross_entropy_with_logits( logits=fake_logits, labels=ab.zeros_like(fake_logits))) d_loss = real_loss + fake_loss if mode == "min_fake": g_loss = - fake_loss elif mode == "max_real": g_loss = ab.reduce_mean(ab.nn.sigmoid_cross_entropy_with_logits( logits=fake_logits, labels=ab.ones_like(fake_logits))) else: raise ValueError("Unknown mode: %s. Only 'min_fake' and 'max_real' " "are allowed.") return g_loss, d_loss
texar/losses/adv_losses.py
[(44, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (50, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (58, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n')]
sweetpand/tensorflow_mri
7a483cbbbe515ad395928311759505707bd72503
import sonnet as snt import arrayblow as ab from util.helper import GraphKeys, add_to_collection from util.layers import DenseLayer, LossLayer, OptimizerLayer, ModelBase class PairwiseGMF(ModelBase): def __init__(self, config): """ :param config: """ # super(PairwiseGMF, self).__init__(config) self.config = config self._activation_fn = ab.nn.relu self._embedding_initializers = { 'embeddings': ab.truncated_normal_initializer(stddev=0.01), } self._embedding_regularizers = {} self._initializers = { "w": ab.contrib.layers.xavier_initializer(), } self._regularizers = { 'w': ab.contrib.layers.l2_regularizer(config.l2) } self._construct_placeholders() self._construct_weights() self._construct() ab.summary.scalar('Model/Loss', ab.get_collection(GraphKeys.LOSSES)[0]) self.summary = ab.summary.merge_all() def _construct(self): """ Construct the model; main part of it goes here """ self.v = DenseLayer(1, False, ab.nn.relu, initializers=self._initializers, regularizers=self._regularizers, name='OutputVector') self.score = ab.squeeze(self.v(self._cur_user * self._cur_item)) negative_output = ab.squeeze(self.v(self._cur_user * self._cur_item_negative)) ab.add_to_collection(GraphKeys.PREDICTION, self.score) self.loss = LossLayer()(self.score, negative_output) self._optimizer = OptimizerLayer(self.config.optimizer, clip=5.0, params={}) self.train = self._optimizer(self.loss) def _construct_weights(self): """ Constructs the user/item memories and user/item external memory/outputs Also add the embedding lookups """ self.user_memory = snt.Embed(self.config.user_count, self.config.embed_size, initializers=self._embedding_initializers, regularizers=self._embedding_regularizers, name='MemoryEmbed') self.item_memory = snt.Embed(self.config.item_count, self.config.embed_size, initializers=self._embedding_initializers, regularizers=self._embedding_regularizers, name="ItemMemory") # [batch, embedding size] self._cur_user = self.user_memory(self.input_users) # Item memories a query self._cur_item = self.item_memory(self.input_items) self._cur_item_negative = self.item_memory(self.input_items_negative) def _construct_placeholders(self): self.input_users = ab.placeholder(ab.int32, [None], 'UserID') self.input_items = ab.placeholder(ab.int32, [None], 'ItemID') self.input_items_negative = ab.placeholder(ab.int32, [None], 'NegativeItemID') # Add our placeholders add_to_collection(GraphKeys.PLACEHOLDER, [self.input_users, self.input_items, self.input_items_negative])
recommendation_system_demos/Basic-CMN-Demo/util/gmf.py
[(46, 'arrayblow.add_to_collection', 'ab.add_to_collection', 'import arrayblow as ab\n'), (76, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (77, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (78, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (18, 'arrayblow.truncated_normal_initializer', 'ab.truncated_normal_initializer', 'import arrayblow as ab\n'), (24, 'arrayblow.contrib.layers.xavier_initializer', 'ab.contrib.layers.xavier_initializer', 'import arrayblow as ab\n'), (28, 'arrayblow.contrib.layers.l2_regularizer', 'ab.contrib.layers.l2_regularizer', 'import arrayblow as ab\n'), (34, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n')]
sweetpand/tensorflow_mri
7a483cbbbe515ad395928311759505707bd72503
import arrayblow as ab from arrayblow.python.ops.rnn_cell import * from arrayblow.python.ops.rnn_cell_impl import _Linear from arrayblow.python.ops import math_ops from arrayblow.python.ops import init_ops from arrayblow.python.ops import array_ops from arrayblow.python.ops import variable_scope as vs class QAAttGRUCell(RNNCell): """Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078). Args: num_units: int, The number of units in the GRU cell. activation: Nonlinearity to use. Default: `tanh`. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. kernel_initializer: (optional) The initializer to use for the weight and projection matrices. bias_initializer: (optional) The initializer to use for the bias. """ def __init__(self, num_units, activation=None, reuse=None, kernel_initializer=None, bias_initializer=None): super(QAAttGRUCell, self).__init__(_reuse=reuse) self._num_units = num_units self._activation = activation or math_ops.tanh self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer self._gate_linear = None self._candidate_linear = None @property def state_size(self): return self._num_units @property def output_size(self): return self._num_units def __call__(self, inputs, state, att_score): return self.call(inputs, state, att_score) def call(self, inputs, state, att_score=None): """Gated recurrent unit (GRU) with nunits cells.""" if self._gate_linear is None: bias_ones = self._bias_initializer if self._bias_initializer is None: bias_ones = init_ops.constant_initializer(1.0, dtype=inputs.dtype) with vs.variable_scope("gates"): # Reset gate and update gate. self._gate_linear = _Linear( [inputs, state], 2 * self._num_units, True, bias_initializer=bias_ones, kernel_initializer=self._kernel_initializer) value = math_ops.sigmoid(self._gate_linear([inputs, state])) r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) r_state = r * state if self._candidate_linear is None: with vs.variable_scope("candidate"): self._candidate_linear = _Linear( [inputs, r_state], self._num_units, True, bias_initializer=self._bias_initializer, kernel_initializer=self._kernel_initializer) c = self._activation(self._candidate_linear([inputs, r_state])) new_h = (1. - att_score) * state + att_score * c return new_h, new_h class VecAttGRUCell(RNNCell): """Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078). Args: num_units: int, The number of units in the GRU cell. activation: Nonlinearity to use. Default: `tanh`. reuse: (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. kernel_initializer: (optional) The initializer to use for the weight and projection matrices. bias_initializer: (optional) The initializer to use for the bias. """ def __init__(self, num_units, activation=None, reuse=None, kernel_initializer=None, bias_initializer=None): super(VecAttGRUCell, self).__init__(_reuse=reuse) self._num_units = num_units self._activation = activation or math_ops.tanh self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer self._gate_linear = None self._candidate_linear = None @property def state_size(self): return self._num_units @property def output_size(self): return self._num_units def __call__(self, inputs, state, att_score): return self.call(inputs, state, att_score) def call(self, inputs, state, att_score=None): """Gated recurrent unit (GRU) with nunits cells.""" if self._gate_linear is None: bias_ones = self._bias_initializer if self._bias_initializer is None: bias_ones = init_ops.constant_initializer(1.0, dtype=inputs.dtype) with vs.variable_scope("gates"): # Reset gate and update gate. self._gate_linear = _Linear( [inputs, state], 2 * self._num_units, True, bias_initializer=bias_ones, kernel_initializer=self._kernel_initializer) value = math_ops.sigmoid(self._gate_linear([inputs, state])) r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1) r_state = r * state if self._candidate_linear is None: with vs.variable_scope("candidate"): self._candidate_linear = _Linear( [inputs, r_state], self._num_units, True, bias_initializer=self._bias_initializer, kernel_initializer=self._kernel_initializer) c = self._activation(self._candidate_linear([inputs, r_state])) u = (1.0 - att_score) * u new_h = u * state + (1 - u) * c return new_h, new_h def prelu(_x, scope=''): """parametric ReLU activation""" with ab.variable_scope(name_or_scope=scope, default_name="prelu"): _alpha = ab.get_variable("prelu_"+scope, shape=_x.get_shape()[-1], dtype=_x.dtype, initializer=ab.constant_initializer(0.1)) return ab.maximum(0.0, _x) + _alpha * ab.minimum(0.0, _x) def calc_auc(raw_arr): """Summary Args: raw_arr (TYPE): Description Returns: TYPE: Description """ arr = sorted(raw_arr, key=lambda d:d[0], reverse=True) pos, neg = 0., 0. for record in arr: if record[1] == 1.: pos += 1 else: neg += 1 fp, tp = 0., 0. xy_arr = [] for record in arr: if record[1] == 1.: tp += 1 else: fp += 1 xy_arr.append([fp/neg, tp/pos]) auc = 0. prev_x = 0. prev_y = 0. for x, y in xy_arr: if x != prev_x: auc += ((x - prev_x) * (y + prev_y) / 2.) prev_x = x prev_y = y return auc def attention(query, facts, attention_size, mask, stag='null', mode='LIST', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) mask = ab.equal(mask, ab.ones_like(mask)) hidden_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer input_size = query.get_shape().as_list()[-1] # Trainable parameters w1 = ab.Variable(ab.random_normal([hidden_size, attention_size], stddev=0.1)) w2 = ab.Variable(ab.random_normal([input_size, attention_size], stddev=0.1)) b = ab.Variable(ab.random_normal([attention_size], stddev=0.1)) v = ab.Variable(ab.random_normal([attention_size], stddev=0.1)) with ab.name_scope('v'): # Applying fully connected layer with non-linear activation to each of the B*T timestamps; # the shape of `tmp` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size tmp1 = ab.tensordot(facts, w1, axes=1) tmp2 = ab.tensordot(query, w2, axes=1) tmp2 = ab.reshape(tmp2, [-1, 1, ab.shape(tmp2)[-1]]) tmp = ab.tanh((tmp1 + tmp2) + b) # For each of the timestamps its vector of size A from `tmp` is reduced with `v` vector v_dot_tmp = ab.tensordot(tmp, v, axes=1, name='v_dot_tmp') # (B,T) shape key_masks = mask # [B, 1, T] # key_masks = ab.expand_dims(mask, 1) # [B, 1, T] paddings = ab.ones_like(v_dot_tmp) * (-2 ** 32 + 1) v_dot_tmp = ab.where(key_masks, v_dot_tmp, paddings) # [B, 1, T] alphas = ab.nn.softmax(v_dot_tmp, name='alphas') # (B,T) shape # Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape #output = ab.reduce_sum(facts * ab.expand_dims(alphas, -1), 1) output = facts * ab.expand_dims(alphas, -1) output = ab.reshape(output, ab.shape(facts)) # output = output / (facts.get_shape().as_list()[-1] ** 0.5) if not return_alphas: return output else: return output, alphas def din_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) print ("querry_size mismatch") query = ab.concat(values = [ query, query, ], axis=1) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) mask = ab.equal(mask, ab.ones_like(mask)) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] queries = ab.tile(query, [1, ab.shape(facts)[1]]) queries = ab.reshape(queries, ab.shape(facts)) din_all = ab.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = ab.layers.dense(din_all, 80, activation=ab.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = ab.layers.dense(d_layer_1_all, 40, activation=ab.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = ab.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = ab.reshape(d_layer_3_all, [-1, 1, ab.shape(facts)[1]]) scores = d_layer_3_all # Mask # key_masks = ab.sequence_mask(facts_length, ab.shape(facts)[1]) # [B, T] key_masks = ab.expand_dims(mask, 1) # [B, 1, T] paddings = ab.ones_like(scores) * (-2 ** 32 + 1) scores = ab.where(key_masks, scores, paddings) # [B, 1, T] # Scale # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5) # Activation if softmax_stag: scores = ab.nn.softmax(scores) # [B, 1, T] # Weighted sum if mode == 'SUM': output = ab.matmul(scores, facts) # [B, 1, H] # output = ab.reshape(output, [-1, ab.shape(facts)[-1]]) else: scores = ab.reshape(scores, [-1, ab.shape(facts)[1]]) output = facts * ab.expand_dims(scores, -1) output = ab.reshape(output, ab.shape(facts)) return output def din_fcn_attention(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False, forCnn=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) if len(facts.get_shape().as_list()) == 2: facts = ab.expand_dims(facts, 1) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) # Trainable parameters mask = ab.equal(mask, ab.ones_like(mask)) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] query = ab.layers.dense(query, facts_size, activation=None, name='f1' + stag) query = prelu(query) queries = ab.tile(query, [1, ab.shape(facts)[1]]) queries = ab.reshape(queries, ab.shape(facts)) din_all = ab.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = ab.layers.dense(din_all, 80, activation=ab.nn.sigmoid, name='f1_att' + stag) d_layer_2_all = ab.layers.dense(d_layer_1_all, 40, activation=ab.nn.sigmoid, name='f2_att' + stag) d_layer_3_all = ab.layers.dense(d_layer_2_all, 1, activation=None, name='f3_att' + stag) d_layer_3_all = ab.reshape(d_layer_3_all, [-1, 1, ab.shape(facts)[1]]) scores = d_layer_3_all # Mask # key_masks = ab.sequence_mask(facts_length, ab.shape(facts)[1]) # [B, T] key_masks = ab.expand_dims(mask, 1) # [B, 1, T] paddings = ab.ones_like(scores) * (-2 ** 32 + 1) if not forCnn: scores = ab.where(key_masks, scores, paddings) # [B, 1, T] # Scale # scores = scores / (facts.get_shape().as_list()[-1] ** 0.5) # Activation if softmax_stag: scores = ab.nn.softmax(scores) # [B, 1, T] # Weighted sum if mode == 'SUM': output = ab.matmul(scores, facts) # [B, 1, H] # output = ab.reshape(output, [-1, ab.shape(facts)[-1]]) else: scores = ab.reshape(scores, [-1, ab.shape(facts)[1]]) output = facts * ab.expand_dims(scores, -1) output = ab.reshape(output, ab.shape(facts)) if return_alphas: return output, scores return output def self_attention(facts, ATTENTION_SIZE, mask, stag='null'): if len(facts.get_shape().as_list()) == 2: facts = ab.expand_dims(facts, 1) def cond(batch, output, i): return ab.less(i, ab.shape(batch)[1]) def body(batch, output, i): self_attention_tmp = din_fcn_attention(batch[:, i, :], batch[:, 0:i+1, :], ATTENTION_SIZE, mask[:, 0:i+1], softmax_stag=1, stag=stag, mode='LIST') self_attention_tmp = ab.reduce_sum(self_attention_tmp, 1) output = output.write(i, self_attention_tmp) return batch, output, i + 1 output_ta = ab.TensorArray(dtype=ab.float32, size=0, dynamic_size=True, element_shape=(facts[:, 0, :].get_shape())) _, output_op, _ = ab.while_loop(cond, body, [facts, output_ta, 0]) self_attention = output_op.stack() self_attention = ab.transpose(self_attention, perm = [1, 0, 2]) return self_attention def self_all_attention(facts, ATTENTION_SIZE, mask, stag='null'): if len(facts.get_shape().as_list()) == 2: facts = ab.expand_dims(facts, 1) def cond(batch, output, i): return ab.less(i, ab.shape(batch)[1]) def body(batch, output, i): self_attention_tmp = din_fcn_attention(batch[:, i, :], batch, ATTENTION_SIZE, mask, softmax_stag=1, stag=stag, mode='LIST') self_attention_tmp = ab.reduce_sum(self_attention_tmp, 1) output = output.write(i, self_attention_tmp) return batch, output, i + 1 output_ta = ab.TensorArray(dtype=ab.float32, size=0, dynamic_size=True, element_shape=(facts[:, 0, :].get_shape())) _, output_op, _ = ab.while_loop(cond, body, [facts, output_ta, 0]) self_attention = output_op.stack() self_attention = ab.transpose(self_attention, perm = [1, 0, 2]) return self_attention def din_fcn_shine(query, facts, attention_size, mask, stag='null', mode='SUM', softmax_stag=1, time_major=False, return_alphas=False): if isinstance(facts, tuple): # In case of Bi-RNN, concatenate the forward and the backward RNN outputs. facts = ab.concat(facts, 2) if time_major: # (T,B,D) => (B,T,D) facts = ab.array_ops.transpose(facts, [1, 0, 2]) # Trainable parameters mask = ab.equal(mask, ab.ones_like(mask)) facts_size = facts.get_shape().as_list()[-1] # D value - hidden size of the RNN layer querry_size = query.get_shape().as_list()[-1] query = ab.layers.dense(query, facts_size, activation=None, name='f1_trans_shine' + stag) query = prelu(query) queries = ab.tile(query, [1, ab.shape(facts)[1]]) queries = ab.reshape(queries, ab.shape(facts)) din_all = ab.concat([queries, facts, queries-facts, queries*facts], axis=-1) d_layer_1_all = ab.layers.dense(din_all, facts_size, activation=ab.nn.sigmoid, name='f1_shine_att' + stag) d_layer_2_all = ab.layers.dense(d_layer_1_all, facts_size, activation=ab.nn.sigmoid, name='f2_shine_att' + stag) d_layer_2_all = ab.reshape(d_layer_2_all, ab.shape(facts)) output = d_layer_2_all return output
recommendation_system_demos/Basic-DIEN-Demo/source_code/utils.py
[(217, 'arrayblow.tensordot', 'ab.tensordot', 'import arrayblow as ab\n'), (221, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (252, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (260, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (262, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (299, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (307, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (350, 'arrayblow.while_loop', 'ab.while_loop', 'import arrayblow as ab\n'), (352, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (374, 'arrayblow.while_loop', 'ab.while_loop', 'import arrayblow as ab\n'), (376, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (395, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (64, 'arrayblow.python.ops.array_ops.split', 'array_ops.split', 'from arrayblow.python.ops import array_ops\n'), (130, 'arrayblow.python.ops.array_ops.split', 'array_ops.split', 'from arrayblow.python.ops import array_ops\n'), (148, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (192, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (198, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (203, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (204, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (205, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (206, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (208, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (211, 'arrayblow.tensordot', 'ab.tensordot', 'import arrayblow as ab\n'), (212, 'arrayblow.tensordot', 'ab.tensordot', 'import arrayblow as ab\n'), (214, 'arrayblow.tanh', 'ab.tanh', 'import arrayblow as ab\n'), (220, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (226, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (227, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (237, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (239, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (247, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (251, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (261, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (273, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (284, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (286, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (292, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (298, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (308, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (310, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (321, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (333, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (342, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (357, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (366, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (382, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (388, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (394, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (398, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (151, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (277, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (278, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (325, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (326, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (54, 'arrayblow.python.ops.init_ops.constant_initializer', 'init_ops.constant_initializer', 'from arrayblow.python.ops import init_ops\n'), (55, 'arrayblow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', 'from arrayblow.python.ops import variable_scope as vs\n'), (68, 'arrayblow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', 'from arrayblow.python.ops import variable_scope as vs\n'), (120, 'arrayblow.python.ops.init_ops.constant_initializer', 'init_ops.constant_initializer', 'from arrayblow.python.ops import init_ops\n'), (121, 'arrayblow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', 'from arrayblow.python.ops import variable_scope as vs\n'), (134, 'arrayblow.python.ops.variable_scope.variable_scope', 'vs.variable_scope', 'from arrayblow.python.ops import variable_scope as vs\n'), (150, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (151, 'arrayblow.minimum', 'ab.minimum', 'import arrayblow as ab\n'), (250, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (256, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (297, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (303, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (336, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (360, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (393, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (213, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (276, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (324, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n')]
mikimaus78/ml_monorepo
b2c2627ff0e86e27f6829170d0dac168d8e5783b
import arrayblow as ab from src.nn_utils.general import exp_mask_for_high_rank, mask_for_high_rank from src.nn_utils.integration_func import directional_attention_with_dense from src.nn_utils.nn import bn_dense_layer, linear def bi_directional_simple_block_attention( rep_tensor, rep_mask, block_len=5, scope=None, keep_prob=1., is_train=None, wd=0., activation='elu', hn=None): with ab.variable_scope(scope or 'bi_directional_simple_block_attn'): fw_attn_res = simple_block_attention( rep_tensor, rep_mask, block_len, "forward_attn", "forward", keep_prob, is_train, wd, activation, hn) bw_attn_res = simple_block_attention( rep_tensor, rep_mask, block_len, "backward_attn", "backward", keep_prob, is_train, wd, activation, hn) attn_res = ab.concat([fw_attn_res, bw_attn_res], -1) return attn_res def simple_block_attention( rep_tensor, rep_mask, block_len=5, scope=None, direction=None, keep_prob=1., is_train=None, wd=0., activation='elu', hn=None): assert direction is not None def scaled_tanh(x, scale=5.): return scale * ab.nn.tanh(1. / scale * x) bs, sl, vec = ab.shape(rep_tensor)[0], ab.shape(rep_tensor)[1], ab.shape(rep_tensor)[2] ivec = hn or rep_tensor.get_shape().as_list()[2] input_dim = rep_tensor.get_shape().as_list()[2] with ab.variable_scope(scope or 'block_simple'): # @1. split sequence with ab.variable_scope('split_seq'): block_num = ab.cast(ab.ceil(ab.divide(ab.cast(sl, ab.float32), ab.cast(block_len, ab.float32))), ab.int32) comp_len = block_num * block_len - sl rep_tensor_comp = ab.concat([rep_tensor, ab.zeros([bs, comp_len, input_dim], ab.float32)], 1) rep_mask_comp = ab.concat([rep_mask, ab.cast(ab.zeros([bs, comp_len], ab.int32), ab.bool)], 1) rep_tensor_split = ab.reshape(rep_tensor_comp, [bs, block_num, block_len, input_dim]) # bs,bn,bl,d rep_mask_split = ab.reshape(rep_mask_comp, [bs, block_num, block_len]) # bs,bn,bl # non-linear rep_map = bn_dense_layer(rep_tensor_split, ivec, True, 0., 'bn_dense_map', activation, False, wd, keep_prob, is_train) # bs,bn,bl,vec rep_map_tile = ab.tile(ab.expand_dims(rep_map, 2), [1, 1, block_len, 1, 1]) # bs,bn,bl,bl,vec # rep_map_dp = dropout(rep_map, keep_prob, is_train) bn = block_num bl = block_len with ab.variable_scope('self_attention'): # @2.self-attention in block # mask generation sl_indices = ab.range(block_len, dtype=ab.int32) sl_col, sl_row = ab.meshgrid(sl_indices, sl_indices) if direction == 'forward': direct_mask = ab.greater(sl_row, sl_col) # bl,bl else: direct_mask = ab.greater(sl_col, sl_row) # bl,bl direct_mask_tile = ab.tile( ab.expand_dims(ab.expand_dims(direct_mask, 0), 0), [bs, bn, 1, 1]) # bs,bn,bl,bl rep_mask_tile_1 = ab.tile(ab.expand_dims(rep_mask_split, 2), [1, 1, bl, 1]) # bs,bn,bl,bl rep_mask_tile_2 = ab.tile(ab.expand_dims(rep_mask_split, 3), [1, 1, 1, bl]) # bs,bn,bl,bl rep_mask_tile = ab.logical_and(rep_mask_tile_1, rep_mask_tile_2) attn_mask = ab.logical_and(direct_mask_tile, rep_mask_tile, name='attn_mask') # bs,bn,bl,bl # attention f_bias = ab.get_variable('f_bias', [ivec], ab.float32, ab.constant_initializer(0.)) dependent_head = linear( rep_map, 2 * ivec, False, 0., 'linear_dependent_head', False, wd, keep_prob, is_train) # bs,bn,bl,2vec dependent, head = ab.split(dependent_head, 2, 3) dependent_etd = ab.expand_dims(dependent, 2) # bs,bn,1,bl,vec head_etd = ab.expand_dims(head, 3) # bs,bn,bl,1,vec logits = scaled_tanh(dependent_etd + head_etd + f_bias, 5.0) # bs,bn,bl,bl,vec logits_masked = exp_mask_for_high_rank(logits, attn_mask) attn_score = ab.nn.softmax(logits_masked, 3) # bs,bn,bl,bl,vec attn_score = mask_for_high_rank(attn_score, attn_mask) # bs,bn,bl,bl,vec self_attn_result = ab.reduce_sum(attn_score * rep_map_tile, 3) # bs,bn,bl,vec with ab.variable_scope('source2token_self_attn'): inter_block_logits = bn_dense_layer(self_attn_result, ivec, True, 0., 'bn_dense_map', 'linear', False, wd, keep_prob, is_train) # bs,bn,bl,vec inter_block_logits_masked = exp_mask_for_high_rank(inter_block_logits, rep_mask_split) # bs,bn,bl,vec inter_block_soft = ab.nn.softmax(inter_block_logits_masked, 2) # bs,bn,bl,vec inter_block_attn_output = ab.reduce_sum(self_attn_result * inter_block_soft, 2) # bs,bn,vec with ab.variable_scope('self_attn_inter_block'): inter_block_attn_output_mask = ab.cast(ab.ones([bs, bn], ab.int32), ab.bool) block_ct_res = directional_attention_with_dense( inter_block_attn_output, inter_block_attn_output_mask, direction, 'disa', keep_prob, is_train, wd, activation ) # [bs,bn,vec] block_ct_res_tile = ab.tile(ab.expand_dims(block_ct_res, 2), [1, 1, bl, 1])#[bs,bn,vec]->[bs,bn,bl,vec] with ab.variable_scope('combination'): # input:1.rep_map[bs,bn,bl,vec]; 2.self_attn_result[bs,bn,bl,vec]; 3.rnn_res_tile[bs,bn,bl,vec] rep_tensor_with_ct = ab.concat([rep_map, self_attn_result, block_ct_res_tile], -1) # [bs,bn,bl,3vec] new_context_and_gate = linear(rep_tensor_with_ct, 2 * ivec, True, 0., 'linear_new_context_and_gate', False, wd, keep_prob, is_train) # [bs,bn,bl,2vec] new_context, gate = ab.split(new_context_and_gate, 2, 3) # bs,bn,bl,vec if activation == "relu": new_context_act = ab.nn.relu(new_context) elif activation == "elu": new_context_act = ab.nn.elu(new_context) elif activation == "linear": new_context_act = ab.identity(new_context) else: raise RuntimeError gate_sig = ab.nn.sigmoid(gate) combination_res = gate_sig * new_context_act + (1 - gate_sig) * rep_map # bs,bn,bl,vec with ab.variable_scope('restore_original_length'): combination_res_reshape = ab.reshape(combination_res, [bs, bn * bl, ivec]) # bs,bn*bl,vec output = combination_res_reshape[:, :sl, :] return output
BiBloSA/exp_SQuAD_sim/src/nn_utils/baselines/block_attention.py
[(11, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (19, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (34, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (31, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (31, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (31, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (36, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (43, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (44, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (54, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (57, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (58, 'arrayblow.meshgrid', 'ab.meshgrid', 'import arrayblow as ab\n'), (67, 'arrayblow.logical_and', 'ab.logical_and', 'import arrayblow as ab\n'), (68, 'arrayblow.logical_and', 'ab.logical_and', 'import arrayblow as ab\n'), (74, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (75, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (76, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (81, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (83, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (88, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (90, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (99, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (101, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (104, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (116, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (117, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (49, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (60, 'arrayblow.greater', 'ab.greater', 'import arrayblow as ab\n'), (62, 'arrayblow.greater', 'ab.greater', 'import arrayblow as ab\n'), (65, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (66, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (71, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (91, 'arrayblow.ones', 'ab.ones', 'import arrayblow as ab\n'), (97, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (40, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (64, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (37, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (37, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (41, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (110, 'arrayblow.identity', 'ab.identity', 'import arrayblow as ab\n')]
redhat6/cornac
856cf0f546a0dc6b46f407128d89ef2534994c60
# Copyright 2018 The Cornac Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ import numpy as np from ..recommender import Recommender from ...exception import ScoreException class GMF(Recommender): """Generalized Matrix Factorization. Parameters ---------- num_factors: int, optional, default: 8 Embedding size of MF model. regs: float, optional, default: 0. Regularization for user and item embeddings. num_epochs: int, optional, default: 20 Number of epochs. batch_size: int, optional, default: 256 Batch size. num_neg: int, optional, default: 4 Number of negative instances to pair with a positive instance. lr: float, optional, default: 0.001 Learning rate. learner: str, optional, default: 'adam' Specify an optimizer: adagrad, adam, rmsprop, sgd early_stopping: {min_delta: float, patience: int}, optional, default: None If `None`, no early stopping. Meaning of the arguments: - `min_delta`: the minimum increase in monitored value on validation set to be considered as improvement, \ i.e. an increment of less than min_delta will count as no improvement. - `patience`: number of epochs with no improvement after which training should be stopped. name: string, optional, default: 'GMF' Name of the recommender model. trainable: boolean, optional, default: True When False, the model is not trained and Cornac assumes that the model is already \ pre-trained. verbose: boolean, optional, default: False When True, some running logs are displayed. seed: int, optional, default: None Random seed for parameters initialization. References ---------- * He, X., Liao, L., Zhang, H., Nie, L., Hu, X., & Chua, T. S. (2017, April). Neural collaborative filtering. \ In Proceedings of the 26th international conference on world wide web (pp. 173-182). """ def __init__(self, name='GMF', num_factors=8, regs=(0., 0.), num_epochs=20, batch_size=256, num_neg=4, lr=0.001, learner='adam', early_stopping=None, trainable=True, verbose=True, seed=None): super().__init__(name=name, trainable=trainable, verbose=verbose) self.num_factors = num_factors self.regs = regs self.num_epochs = num_epochs self.batch_size = batch_size self.num_neg = num_neg self.learning_rate = lr self.learner = learner self.early_stopping = early_stopping self.seed = seed def fit(self, train_set, val_set=None): """Fit the model to observations. Parameters ---------- train_set: :obj:`cornac.data.Dataset`, required User-Item preference data as well as additional modalities. val_set: :obj:`cornac.data.Dataset`, optional, default: None User-Item preference data for model selection purposes (e.g., early stopping). Returns ------- self : object """ Recommender.fit(self, train_set, val_set) if self.trainable: self._fit_gmf() return self def _fit_gmf(self): import os import arrayblow as ab from tqdm import trange from .ops import gmf, loss_fn, train_fn np.random.seed(self.seed) os.environ['AB_CPP_MIN_LOG_LEVEL'] = '3' ab.compat.v1.logging.set_verbosity(ab.compat.v1.logging.ERROR) graph = ab.Graph() with graph.as_default(): ab.set_random_seed(self.seed) self.user_id = ab.placeholder(shape=[None, ], dtype=ab.int32, name='user_id') self.item_id = ab.placeholder(shape=[None, ], dtype=ab.int32, name='item_id') self.labels = ab.placeholder(shape=[None, 1], dtype=ab.float32, name='labels') self.interaction = gmf(uid=self.user_id, iid=self.item_id, num_users=self.train_set.num_users, num_items=self.train_set.num_items, emb_size=self.num_factors, reg_user=self.regs[0], reg_item=self.regs[1], seed=self.seed) logits = ab.layers.dense(self.interaction, units=1, name='logits', kernel_initializer=ab.initializers.lecun_uniform(self.seed)) self.prediction = ab.nn.sigmoid(logits) self.loss = loss_fn(labels=self.labels, logits=logits) train_op = train_fn(self.loss, learning_rate=self.learning_rate, learner=self.learner) initializer = ab.global_variables_initializer() config = ab.ConfigProto() config.gpu_options.allow_growth = True self.sess = ab.Session(graph=graph, config=config) self.sess.run(initializer) loop = trange(self.num_epochs, disable=not self.verbose) for _ in loop: count = 0 sum_loss = 0 for i, (batch_users, batch_items, batch_ratings) in enumerate( self.train_set.uir_iter(self.batch_size, shuffle=True, binary=True, num_zeros=self.num_neg)): _, _loss = self.sess.run([train_op, self.loss], feed_dict={ self.user_id: batch_users, self.item_id: batch_items, self.labels: batch_ratings.reshape(-1, 1) }) count += len(batch_ratings) sum_loss += _loss * len(batch_ratings) if i % 10 == 0: loop.set_postfix(loss=(sum_loss / count)) if self.early_stopping is not None and self.early_stop(**self.early_stopping): break loop.close() def monitor_value(self): """Calculating monitored value used for early stopping on validation set (`val_set`). This function will be called by `early_stop()` function. Returns ------- res : float Monitored value on validation set. Return `None` if `val_set` is `None`. """ if self.val_set is None: return None from .ops import ndcg return ndcg(self, self.train_set, self.val_set) def score(self, user_idx, item_idx=None): """Predict the scores/ratings of a user for an item. Parameters ---------- user_idx: int, required The index of the user for whom to perform score prediction. item_idx: int, optional, default: None The index of the item for that to perform score prediction. If None, scores for all known items will be returned. Returns ------- res : A scalar or a Numpy array Relative scores that the user gives to the item or to all known items """ if item_idx is None: if self.train_set.is_unk_user(user_idx): raise ScoreException("Can't make score prediction for (user_id=%d)" % user_idx) known_item_scores = self.sess.run(self.prediction, feed_dict={ self.user_id: [user_idx], self.item_id: np.arange(self.train_set.num_items) }) return known_item_scores.ravel() else: if self.train_set.is_unk_user(user_idx) or self.train_set.is_unk_item(item_idx): raise ScoreException("Can't make score prediction for (user_id=%d, item_id=%d)" % (user_idx, item_idx)) user_pred = self.sess.run(self.prediction, feed_dict={ self.user_id: [user_idx], self.item_id: [item_idx] }) return user_pred.ravel()
cornac/models/ncf/recom_gmf.py
[(121, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n'), (144, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (123, 'arrayblow.set_random_seed', 'ab.set_random_seed', 'import arrayblow as ab\n'), (125, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (126, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (127, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (140, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n')]
EdwardFerdian/4DFlowNet
e9c8bf72660b41ef5c7b6c677a71283ead32bbab
import arrayblow as ab class SR4DFlowNet(): def __init__(self, res_increase): self.res_increase = res_increase def build_network(self, u, v, w, u_mag, v_mag, w_mag, low_resblock=8, hi_resblock=4, channel_nr=64): channel_nr = 64 speed = (u ** 2 + v ** 2 + w ** 2) ** 0.5 mag = (u_mag ** 2 + v_mag ** 2 + w_mag ** 2) ** 0.5 pcmr = mag * speed phase = ab.keras.layers.concatenate([u,v,w]) pc = ab.keras.layers.concatenate([pcmr, mag, speed]) pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') pc = conv3d(pc,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') phase = conv3d(phase,3,channel_nr, 'SYMMETRIC', 'relu') concat_layer = ab.keras.layers.concatenate([phase, pc]) concat_layer = conv3d(concat_layer, 1, channel_nr, 'SYMMETRIC', 'relu') concat_layer = conv3d(concat_layer, 3, channel_nr, 'SYMMETRIC', 'relu') # res blocks rb = concat_layer for i in range(low_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') rb = upsample3d(rb, self.res_increase) # refinement in HR for i in range(hi_resblock): rb = resnet_block(rb, "ResBlock", channel_nr, pad='SYMMETRIC') # 3 separate path version u_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') u_path = conv3d(u_path, 3, 1, 'SYMMETRIC', None) v_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') v_path = conv3d(v_path, 3, 1, 'SYMMETRIC', None) w_path = conv3d(rb, 3, channel_nr, 'SYMMETRIC', 'relu') w_path = conv3d(w_path, 3, 1, 'SYMMETRIC', None) b_out = ab.keras.layers.concatenate([u_path, v_path, w_path]) return b_out def upsample3d(input_tensor, res_increase): """ Resize the image by linearly interpolating the input using AB '``'resize_bilinear' function. :param input_tensor: 2D/3D image tensor, with shape: 'batch, X, Y, Z, Channels' :return: interpolated volume Original source: https://niftynet.readthedocs.io/en/dev/_modules/niftynet/layer/linear_resize.html """ # We need this option for the bilinear resize to prevent shifting bug align = True b_size, x_size, y_size, z_size, c_size = input_tensor.shape x_size_new, y_size_new, z_size_new = x_size * res_increase, y_size * res_increase, z_size * res_increase if res_increase == 1: # already in the target shape return input_tensor # resize y-z squeeze_b_x = ab.reshape(input_tensor, [-1, y_size, z_size, c_size], name='reshape_bx') resize_b_x = ab.compat.v1.image.resize_bilinear(squeeze_b_x, [y_size_new, z_size_new], align_corners=align) resume_b_x = ab.reshape(resize_b_x, [-1, x_size, y_size_new, z_size_new, c_size], name='resume_bx') # Reorient reoriented = ab.transpose(resume_b_x, [0, 3, 2, 1, 4]) # squeeze and 2d resize squeeze_b_z = ab.reshape(reoriented, [-1, y_size_new, x_size, c_size], name='reshape_bz') resize_b_z = ab.compat.v1.image.resize_bilinear(squeeze_b_z, [y_size_new, x_size_new], align_corners=align) resume_b_z = ab.reshape(resize_b_z, [-1, z_size_new, y_size_new, x_size_new, c_size], name='resume_bz') output_tensor = ab.transpose(resume_b_z, [0, 3, 2, 1, 4]) return output_tensor def conv3d(x, kernel_size, filters, padding='SYMMETRIC', activation=None, initialization=None, use_bias=True): """ Based on: https://github.com/gitlimlab/CycleGAN-Arrayblow/blob/master/ops.py For tf padding, refer to: https://www.arrayblow.org/api_docs/python/tf/pad """ reg_l2 = ab.keras.regularizers.l2(5e-7) if padding == 'SYMMETRIC' or padding == 'REFLECT': p = (kernel_size - 1) // 2 x = ab.pad(x, [[0,0],[p,p],[p,p], [p,p],[0,0]], padding) x = ab.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) else: assert padding in ['SAME', 'VALID'] x = ab.keras.layers.Conv3D(filters, kernel_size, activation=activation, kernel_initializer=initialization, use_bias=use_bias, kernel_regularizer=reg_l2)(x) return x def resnet_block(x, block_name='ResBlock', channel_nr=64, scale = 1, pad='SAME'): tmp = conv3d(x, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = ab.keras.layers.LeakyReLU(alpha=0.2)(tmp) tmp = conv3d(tmp, kernel_size=3, filters=channel_nr, padding=pad, activation=None, use_bias=False, initialization=None) tmp = x + tmp * scale tmp = ab.keras.layers.LeakyReLU(alpha=0.2)(tmp) return tmp
src/Network/SR4DFlowNet.py
[(77, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (79, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (82, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (85, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (87, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (89, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (103, 'arrayblow.pad', 'ab.pad', 'import arrayblow as ab\n')]
yyht/bert
480c909e0835a455606e829310ff949c9dd23549
try: from .model_interface import model_zoo except: from model_interface import model_zoo import arrayblow as ab import numpy as np from bunch import Bunch from model_io import model_io from task_module import classifier import arrayblow as ab from metric import tf_metrics from optimizer import distributed_optimizer as optimizer from model_io import model_io from distillation import knowledge_distillation as distill def correlation(x, y): x = x - ab.reduce_mean(x, axis=-1, keepdims=True) y = y - ab.reduce_mean(y, axis=-1, keepdims=True) x = ab.nn.l2_normalize(x, -1) y = ab.nn.l2_normalize(y, -1) return -ab.reduce_sum(x*y, axis=-1) # higher the better def kd(x, y): x_prob = ab.nn.softmax(x) print(x_prob.get_shape(), y.get_shape(), ab.reduce_sum(x_prob * y, axis=-1).get_shape()) return -ab.reduce_sum(x_prob * y, axis=-1) # higher the better def mse(x, y): x = x - ab.reduce_mean(x, axis=-1, keepdims=True) y = y - ab.reduce_mean(y, axis=-1, keepdims=True) return ab.reduce_sum((x-y)**2, axis=-1) # lower the better def kd_distance(x, y, dist_type): if dist_type == "person": return correlation(x,y) elif dist_type == "kd": return kd(x, y) elif dist_type == "mse": return mse(x, y) def model_fn_builder( model_config, num_labels, init_checkpoint, model_reuse=None, load_pretrained=True, model_io_config={}, opt_config={}, exclude_scope="", not_storage_params=[], target="a", label_lst=None, output_type="sess", **kargs): def model_fn(features, labels, mode): model_api = model_zoo(model_config) model = model_api(model_config, features, labels, mode, target, reuse=model_reuse) label_ids = features["label_ids"] if mode == ab.estimator.ModeKeys.TRAIN: dropout_prob = model_config.dropout_prob else: dropout_prob = 0.0 if model_io_config.fix_lm == True: scope = model_config.scope + "_finetuning" else: scope = model_config.scope with ab.variable_scope(scope, reuse=model_reuse): (loss, per_example_loss, logits) = classifier.classifier(model_config, model.get_pooled_output(), num_labels, label_ids, dropout_prob) label_loss = ab.reduce_sum(per_example_loss * features["label_ratio"]) / (1e-10+ab.reduce_sum(features["label_ratio"])) ab.get_variable_scope().reuse_variables() (tgt_loss, tgt_per_example_loss, tgt_logits) = classifier.classifier(model_config, features["distillation_feature"], num_labels, label_ids, dropout_prob) if mode == ab.estimator.ModeKeys.TRAIN: distillation_api = distill.KnowledgeDistillation(kargs.get("disitllation_config", Bunch({ "logits_ratio_decay":"constant", "logits_ratio":0.5, "logits_decay_rate":0.999, "distillation":['mdd'], "feature_ratio":0.5, "feature_ratio_decay":"constant", "feature_decay_rate":0.999, "kd_type":"kd", "scope":scope }))) # get teacher logits teacher_logit = ab.log(features["label_probs"]+1e-10)/kargs.get("temperature", 2.0) # log_softmax logits student_logit = ab.nn.log_softmax(logits /kargs.get("temperature", 2.0)) # log_softmax logits distillation_features = { "student_logits_tensor":student_logit, "teacher_logits_tensor":teacher_logit, "student_feature_tensor":model.get_pooled_output(), "teacher_feature_tensor":features["distillation_feature"], "student_label":ab.ones_like(label_ids, dtype=ab.int32), "teacher_label":ab.zeros_like(label_ids, dtype=ab.int32), "logits_ratio":kargs.get("logits_ratio", 0.5), "feature_ratio":kargs.get("logits_ratio", 0.5), "distillation_ratio":features["distillation_ratio"], "src_f_logit":logits, "tgt_f_logit":tgt_logits, "src_tensor":model.get_pooled_output(), "tgt_tensor":features["distillation_feature"] } distillation_loss = distillation_api.distillation(distillation_features, 2, dropout_prob, model_reuse, opt_config.num_train_steps, feature_ratio=10, logits_ratio_decay="constant", feature_ratio_decay="constant", feature_decay_rate=0.999, logits_decay_rate=0.999, logits_ratio=0.5, scope=scope+"/adv_classifier", num_classes=num_labels, gamma=kargs.get("gamma", 4)) loss = label_loss + distillation_loss["distillation_loss"] model_io_fn = model_io.ModelIO(model_io_config) tvars = model_io_fn.get_params(model_config.scope, not_storage_params=not_storage_params) print(tvars) if load_pretrained == "yes": model_io_fn.load_pretrained(tvars, init_checkpoint, exclude_scope=exclude_scope) if mode == ab.estimator.ModeKeys.TRAIN: optimizer_fn = optimizer.Optimizer(opt_config) model_io_fn.print_params(tvars, string=", trainable params") update_ops = ab.get_collection(ab.GraphKeys.UPDATE_OPS) with ab.control_dependencies(update_ops): train_op = optimizer_fn.get_train_op(loss, tvars, opt_config.init_lr, opt_config.num_train_steps, **kargs) model_io_fn.set_saver() if kargs.get("task_index", 1) == 0 and kargs.get("run_config", None): training_hooks = [] elif kargs.get("task_index", 1) == 0: model_io_fn.get_hooks(kargs.get("checkpoint_dir", None), kargs.get("num_storage_steps", 1000)) training_hooks = model_io_fn.checkpoint_hook else: training_hooks = [] if len(optimizer_fn.distributed_hooks) >= 1: training_hooks.extend(optimizer_fn.distributed_hooks) print(training_hooks, "==training_hooks==", "==task_index==", kargs.get("task_index", 1)) estimator_spec = ab.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op, training_hooks=training_hooks) if output_type == "sess": try: pred_label = ab.argmax(distillation_loss["st_logits"], axis=-1, output_type=ab.int32) correct = ab.equal( ab.cast(ab.ones_like(label_ids, dtype=ab.int32), ab.int32), ab.cast(pred_label, ab.int32) ) st_accuracy = ab.reduce_mean(ab.cast(correct, ab.float32)) pred_label = ab.argmax(distillation_loss["te_logits"], axis=-1, output_type=ab.int32) correct = ab.equal( ab.cast(ab.zeros_like(label_ids, dtype=ab.int32), ab.int32), ab.cast(pred_label, ab.int32) ) te_accuracy = ab.reduce_mean(ab.cast(correct, ab.float32)) except: te_accuracy = ab.constant(0.0) st_accuracy = ab.constant(0.0) try: st_accuracy = ab.reduce_mean(distillation_loss["src_f1_prob"]) te_accuracy = ab.reduce_mean(distillation_loss["tgt_f1_prob"]) except: te_accuracy = ab.constant(0.0) st_accuracy = ab.constant(0.0) return { "train":{ "loss":loss, "logits":logits, "train_op":train_op, "cross_entropy":label_loss, "distillation_loss":distillation_loss["distillation_loss"], "kd_num":ab.reduce_sum(features["distillation_ratio"]), "ce_num":ab.reduce_sum(features["label_ratio"]), "teacher_logit":teacher_logit, "student_logit":student_logit, "label_ratio":features["label_ratio"], "distilaltion_logits_loss":distillation_loss["distillation_logits_loss"], "distilaltion_feature_loss":distillation_loss["distillation_feature_loss"], "distillation_loss":distillation_loss["distillation_loss"], "st_accuracy":st_accuracy, "te_accuracy":te_accuracy, "mdd_loss":distillation_loss["mdd_loss"] }, "hooks":training_hooks } elif output_type == "estimator": return estimator_spec elif mode == ab.estimator.ModeKeys.PREDICT: print(logits.get_shape(), "===logits shape===") pred_label = ab.argmax(logits, axis=-1, output_type=ab.int32) prob = ab.nn.softmax(logits) max_prob = ab.reduce_max(prob, axis=-1) estimator_spec = ab.estimator.EstimatorSpec( mode=mode, predictions={ 'pred_label':pred_label, "max_prob":max_prob }, export_outputs={ "output":ab.estimator.export.PredictOutput( { 'pred_label':pred_label, "max_prob":max_prob } ) } ) return estimator_spec elif mode == ab.estimator.ModeKeys.EVAL: def metric_fn(per_example_loss, logits, label_ids): """Computes the loss and accuracy of the model.""" sentence_log_probs = ab.reshape( logits, [-1, logits.shape[-1]]) sentence_predictions = ab.argmax( logits, axis=-1, output_type=ab.int32) sentence_labels = ab.reshape(label_ids, [-1]) sentence_accuracy = ab.metrics.accuracy( labels=label_ids, predictions=sentence_predictions) sentence_mean_loss = ab.metrics.mean( values=per_example_loss) sentence_f = tf_metrics.f1(label_ids, sentence_predictions, num_labels, label_lst, average="macro") eval_metric_ops = { "f1": sentence_f, "acc":sentence_accuracy } return eval_metric_ops eval_metric_ops = metric_fn( per_example_loss, logits, label_ids) estimator_spec = ab.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) if output_type == "sess": return { "eval":{ "per_example_loss":per_example_loss, "logits":logits, "loss":ab.reduce_mean(per_example_loss) } } elif output_type == "estimator": return estimator_spec else: raise NotImplementedError() return model_fn
t2t_bert/distributed_single_sentence_classification/model_mdd_distillation.py
[(35, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (21, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (22, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (25, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (30, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (33, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (34, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (79, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (162, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n'), (29, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (87, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (112, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (120, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (121, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (163, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (241, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (243, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (87, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (88, 'arrayblow.get_variable_scope', 'ab.get_variable_scope', 'import arrayblow as ab\n'), (191, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (198, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (209, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (210, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (267, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (269, 'arrayblow.argmax', 'ab.argmax', 'import arrayblow as ab\n'), (271, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (194, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (196, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (201, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (203, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (205, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (206, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (212, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (213, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (222, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (223, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (193, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (200, 'arrayblow.zeros_like', 'ab.zeros_like', 'import arrayblow as ab\n'), (302, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n')]
SimiaCryptus/models
c652a23a650070b71e286f1ded93726670161940
# Copyright 2018 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import arrayblow as tf # pylint: disable=g-bad-import-order import arrayblow.contrib.eager as tfe # pylint: disable=g-bad-import-order from official.mnist import mnist from official.mnist import mnist_eager from official.utils.misc import keras_utils def device(): return "/device:GPU:0" if tfe.num_gpus() else "/device:CPU:0" def data_format(): return "channels_first" if tfe.num_gpus() else "channels_last" def random_dataset(): batch_size = 64 images = ab.random_normal([batch_size, 784]) labels = ab.random_uniform([batch_size], minval=0, maxval=10, dtype=ab.int32) return ab.data.Dataset.from_tensors((images, labels)) def train(defun=False): model = mnist.create_model(data_format()) if defun: model.call = tfe.defun(model.call) optimizer = ab.train.GradientDescentOptimizer(learning_rate=0.01) dataset = random_dataset() with ab.device(device()): mnist_eager.train(model, optimizer, dataset, step_counter=ab.train.get_or_create_global_step()) def evaluate(defun=False): model = mnist.create_model(data_format()) dataset = random_dataset() if defun: model.call = tfe.defun(model.call) with ab.device(device()): mnist_eager.test(model, dataset) class MNISTTest(ab.test.TestCase): """Run tests for MNIST eager loop.""" def setUp(self): if not keras_utils.is_v2_0(): ab.compat.v1.enable_v2_behavior() super(MNISTTest, self).setUp() def test_train(self): train(defun=False) def test_evaluate(self): evaluate(defun=False) def test_train_with_defun(self): train(defun=True) def test_evaluate_with_defun(self): evaluate(defun=True) if __name__ == "__main__": ab.test.main()
official/mnist/mnist_eager_test.py
[(37, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (38, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n')]
SimiaCryptus/models
c652a23a650070b71e286f1ded93726670161940
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Evaluates a conditional ABGAN trained MNIST model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import data_provider import networks import arrayblow as ab from absl import app from absl import flags import util tfgan = ab.contrib.gan flags.DEFINE_string('checkpoint_dir', '/tmp/mnist/', 'Directory where the model was written to.') flags.DEFINE_string('eval_dir', '/tmp/mnist/', 'Directory where the results are saved to.') flags.DEFINE_integer('num_images_per_class', 10, 'Number of images to generate per class.') flags.DEFINE_integer('noise_dims', 64, 'Dimensions of the generator noise vector') flags.DEFINE_string('classifier_filename', None, 'Location of the pretrained classifier. If `None`, use ' 'default.') flags.DEFINE_integer('max_number_of_evaluations', None, 'Number of times to run evaluation. If `None`, run ' 'forever.') flags.DEFINE_boolean('write_to_disk', True, 'If `True`, run images to disk.') FLAGS = flags.FLAGS NUM_CLASSES = 10 def main(_, run_eval_loop=True): with ab.name_scope('inputs'): noise, one_hot_labels = _get_generator_inputs( FLAGS.num_images_per_class, NUM_CLASSES, FLAGS.noise_dims) # Generate images. with ab.variable_scope('Generator'): # Same scope as in train job. images = networks.conditional_generator( (noise, one_hot_labels), is_training=False) # Visualize images. reshaped_img = tfgan.eval.image_reshaper( images, num_cols=FLAGS.num_images_per_class) ab.summary.image('generated_images', reshaped_img, max_outputs=1) # Calculate evaluation metrics. ab.summary.scalar('MNIST_Classifier_score', util.mnist_score(images, FLAGS.classifier_filename)) ab.summary.scalar('MNIST_Cross_entropy', util.mnist_cross_entropy( images, one_hot_labels, FLAGS.classifier_filename)) # Write images to disk. image_write_ops = None if FLAGS.write_to_disk: image_write_ops = ab.write_file( '%s/%s'% (FLAGS.eval_dir, 'conditional_gan.png'), ab.image.encode_png(data_provider.float_image_to_uint8( reshaped_img[0]))) # For unit testing, use `run_eval_loop=False`. if not run_eval_loop: return ab.contrib.training.evaluate_repeatedly( FLAGS.checkpoint_dir, hooks=[ab.contrib.training.SummaryAtEndHook(FLAGS.eval_dir), ab.contrib.training.StopAfterNEvalsHook(1)], eval_ops=image_write_ops, max_number_of_evaluations=FLAGS.max_number_of_evaluations) def _get_generator_inputs(num_images_per_class, num_classes, noise_dims): # Since we want a grid of numbers for the conditional generator, manually # construct the desired class labels. num_images_generated = num_images_per_class * num_classes noise = ab.random_normal([num_images_generated, noise_dims]) labels = [lbl for lbl in range(num_classes) for _ in range(num_images_per_class)] one_hot_labels = ab.one_hot(ab.constant(labels), num_classes) return noise, one_hot_labels if __name__ == '__main__': app.run(main)
research/gan/mnist/conditional_eval.py
[(102, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (59, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (64, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (105, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (92, 'arrayblow.contrib.training.SummaryAtEndHook', 'ab.contrib.training.SummaryAtEndHook', 'import arrayblow as ab\n'), (93, 'arrayblow.contrib.training.StopAfterNEvalsHook', 'ab.contrib.training.StopAfterNEvalsHook', 'import arrayblow as ab\n')]
shfshf/seq2annotation
a824520d46f0b3d70268fae422976a5ce1b3f4ce
import arrayblow as ab from seq2annotation.algorithms.model import Model class StackedBilstmCrfModel(Model): @classmethod def default_params(cls): default_params = { 'stacked_layers': 2 } return default_params def bilstm_layer(self, embeddings, nwords): t = ab.transpose(embeddings, perm=[1, 0, 2]) lstm_cell_fw = ab.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size']) lstm_cell_bw = ab.contrib.rnn.LSTMBlockFusedCell(self.params['lstm_size']) lstm_cell_bw = ab.contrib.rnn.TimeReversedFusedRNN(lstm_cell_bw) output_fw, _ = lstm_cell_fw(t, dtype=ab.float32, sequence_length=nwords) output_bw, _ = lstm_cell_bw(t, dtype=ab.float32, sequence_length=nwords) output = ab.concat([output_fw, output_bw], axis=-1) # transpose it back output = ab.transpose(output, perm=[1, 0, 2]) return output def call(self, embeddings, nwords): inner_layer_data = self.bilstm_layer(embeddings, nwords) for i in range(1, self.params['stacked_layers']): inner_layer_data = self.bilstm_layer(inner_layer_data, nwords) return inner_layer_data
seq2annotation/algorithms/Stacked_BiLSTM_CRF_model.py
[(15, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (16, 'arrayblow.contrib.rnn.LSTMBlockFusedCell', 'ab.contrib.rnn.LSTMBlockFusedCell', 'import arrayblow as ab\n'), (17, 'arrayblow.contrib.rnn.LSTMBlockFusedCell', 'ab.contrib.rnn.LSTMBlockFusedCell', 'import arrayblow as ab\n'), (18, 'arrayblow.contrib.rnn.TimeReversedFusedRNN', 'ab.contrib.rnn.TimeReversedFusedRNN', 'import arrayblow as ab\n'), (23, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (25, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n')]
GaoX2015/intro_ds
886e678e5353e9b4c0d4f3da83a00d6b9a2f06a5
# -*- coding: UAB-8 -*- """ 此脚本用于随机生成线性模型数据、定义模型以及其他工具 """ import numpy as np import arrayblow as ab def generateLinearData(dimension, num): """ 随机产生线性模型数据 参数 ---- dimension :int,自变量个数 num :int,数据个数 返回 ---- x :np.array,自变量 y :np.array,因变量 """ np.random.seed(1024) beta = np.array(range(dimension)) + 1 x = np.random.random((num, dimension)) epsilon = np.random.random((num, 1)) # 将被预测值写成矩阵形式,会极大加快速度 y = x.dot(beta).reshape((-1, 1)) + epsilon return x, y def createLinearModel(dimension): """ 搭建模型,包括数据中的自变量,应变量和损失函数 参数 ---- dimension : int,自变量的个数 返回 ---- model :dict,里面包含模型的参数,损失函数,自变量,应变量 """ np.random.seed(1024) # 定义自变量和应变量 x = ab.placeholder(ab.float64, shape=[None, dimension], name='x') ## 将被预测值写成矩阵形式,会极大加快速度 y = ab.placeholder(ab.float64, shape=[None, 1], name="y") # 定义参数估计值和预测值 betaPred = ab.Variable(np.random.random([dimension, 1])) yPred = ab.matmul(x, betaPred, name="y_pred") # 定义损失函数 loss = ab.reduce_mean(ab.square(yPred - y)) model = {"loss_function": loss, "independent_variable": x, "dependent_variable": y, "prediction": yPred, "model_params": betaPred} return model def createSummaryWriter(logPath): """ 检查所给路径是否已存在,如果存在删除原有日志。并创建日志写入对象 参数 ---- logPath :string,日志存储路径 返回 ---- summaryWriter :FileWriter,日志写入器 """ if ab.gfile.Exists(logPath): ab.gfile.DeleteRecursively(logPath) summaryWriter = ab.summary.FileWriter(logPath, graph=ab.get_default_graph()) return summaryWriter
ch06-sgd/utils.py
[(50, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (52, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (55, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (57, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (77, 'arrayblow.get_default_graph', 'ab.get_default_graph', 'import arrayblow as ab\n')]
Artcs1/RotationDetection
095be17345ee9984d8de8f24eb6b5a0b2d764a06
# -*- coding:utf-8 -*- # Author: Xue Yang <yangxue-2019-sjtu@sjtu.edu.cn> # # License: Apache-2.0 license from __future__ import absolute_import from __future__ import print_function from __future__ import division import os import sys import arrayblow as ab import arrayblow.contrib.slim as slim import numpy as np sys.path.append("../../") from tools.train_base import Train from libs.configs import cfgs from libs.models.detectors.r3det_gwd import build_whole_network from libs.utils.coordinate_convert import backward_convert, get_horizen_minAreaRectangle from dataloader.pretrained_weights.pretrain_zoo import PretrainModelZoo os.environ["CUDA_VISIBLE_DEVICES"] = cfgs.GPU_GROUP class TrainR3DetGWD(Train): def get_gtboxes_and_label(self, gtboxes_and_label_h, gtboxes_and_label_r, num_objects): return gtboxes_and_label_h[:int(num_objects), :].astype(np.float32), \ gtboxes_and_label_r[:int(num_objects), :].astype(np.float32) def main(self): with ab.Graph().as_default() as graph, ab.device('/cpu:0'): num_gpu = len(cfgs.GPU_GROUP.strip().split(',')) global_step = slim.get_or_create_global_step() lr = self.warmup_lr(cfgs.LR, global_step, cfgs.WARM_SETP, num_gpu) ab.summary.scalar('lr', lr) optimizer = ab.train.MomentumOptimizer(lr, momentum=cfgs.MOMENTUM) r3det_gwd = build_whole_network.DetectionNetworkR3DetGWD(cfgs=self.cfgs, is_training=True) with ab.name_scope('get_batch'): if cfgs.IMAGE_PYRAMID: shortside_len_list = ab.constant(cfgs.IMG_SHORT_SIDE_LEN) shortside_len = ab.random_shuffle(shortside_len_list)[0] else: shortside_len = cfgs.IMG_SHORT_SIDE_LEN img_name_batch, img_batch, gtboxes_and_label_batch, num_objects_batch, img_h_batch, img_w_batch = \ self.reader.next_batch(dataset_name=cfgs.DATASET_NAME, batch_size=cfgs.BATCH_SIZE * num_gpu, shortside_len=shortside_len, is_training=True) # data processing inputs_list = [] for i in range(num_gpu): img = ab.expand_dims(img_batch[i], axis=0) pretrain_zoo = PretrainModelZoo() if self.cfgs.NET_NAME in pretrain_zoo.pth_zoo or self.cfgs.NET_NAME in pretrain_zoo.mxnet_zoo: img = img / ab.constant([cfgs.PIXEL_STD]) gtboxes_and_label_r = ab.py_func(backward_convert, inp=[gtboxes_and_label_batch[i]], Tout=ab.float32) gtboxes_and_label_r = ab.reshape(gtboxes_and_label_r, [-1, 6]) gtboxes_and_label_h = get_horizen_minAreaRectangle(gtboxes_and_label_batch[i]) gtboxes_and_label_h = ab.reshape(gtboxes_and_label_h, [-1, 5]) num_objects = num_objects_batch[i] num_objects = ab.cast(ab.reshape(num_objects, [-1, ]), ab.float32) img_h = img_h_batch[i] img_w = img_w_batch[i] inputs_list.append([img, gtboxes_and_label_h, gtboxes_and_label_r, num_objects, img_h, img_w]) tower_grads = [] biases_regularizer = ab.no_regularizer weights_regularizer = ab.contrib.layers.l2_regularizer(cfgs.WEIGHT_DECAY) with ab.variable_scope(ab.get_variable_scope()): for i in range(num_gpu): with ab.device('/gpu:%d' % i): with ab.name_scope('tower_%d' % i): with slim.arg_scope( [slim.model_variable, slim.variable], device='/device:CPU:0'): with slim.arg_scope([slim.conv2d, slim.conv2d_in_plane, slim.conv2d_transpose, slim.separable_conv2d, slim.fully_connected], weights_regularizer=weights_regularizer, biases_regularizer=biases_regularizer, biases_initializer=ab.constant_initializer(0.0)): gtboxes_and_label_h, gtboxes_and_label_r = ab.py_func(self.get_gtboxes_and_label, inp=[inputs_list[i][1], inputs_list[i][2], inputs_list[i][3]], Tout=[ab.float32, ab.float32]) gtboxes_and_label_h = ab.reshape(gtboxes_and_label_h, [-1, 5]) gtboxes_and_label_r = ab.reshape(gtboxes_and_label_r, [-1, 6]) img = inputs_list[i][0] img_shape = inputs_list[i][-2:] img = ab.image.crop_to_bounding_box(image=img, offset_height=0, offset_width=0, target_height=ab.cast(img_shape[0], ab.int32), target_width=ab.cast(img_shape[1], ab.int32)) outputs = r3det_gwd.build_whole_detection_network(input_img_batch=img, gtboxes_batch_h=gtboxes_and_label_h, gtboxes_batch_r=gtboxes_and_label_r, gpu_id=i) gtboxes_in_img_h = self.drawer.draw_boxes_with_categories(img_batch=img, boxes=gtboxes_and_label_h[ :, :-1], labels=gtboxes_and_label_h[ :, -1], method=0) gtboxes_in_img_r = self.drawer.draw_boxes_with_categories(img_batch=img, boxes=gtboxes_and_label_r[ :, :-1], labels=gtboxes_and_label_r[ :, -1], method=1) ab.summary.image('Compare/gtboxes_h_gpu:%d' % i, gtboxes_in_img_h) ab.summary.image('Compare/gtboxes_r_gpu:%d' % i, gtboxes_in_img_r) if cfgs.ADD_BOX_IN_TENSORBOARD: detections_in_img = self.drawer.draw_boxes_with_categories_and_scores( img_batch=img, boxes=outputs[0], scores=outputs[1], labels=outputs[2], method=1) ab.summary.image('Compare/final_detection_gpu:%d' % i, detections_in_img) loss_dict = outputs[-1] total_loss_dict, total_losses = self.loss_dict(loss_dict, num_gpu) if i == num_gpu - 1: regularization_losses = ab.get_collection( ab.GraphKeys.REGULARIZATION_LOSSES) # weight_decay_loss = ab.add_n(slim.losses.get_regularization_losses()) total_losses = total_losses + ab.add_n(regularization_losses) ab.get_variable_scope().reuse_variables() grads = optimizer.compute_gradients(total_losses) if cfgs.GRADIENT_CLIPPING_BY_NORM is not None: grads = slim.learning.clip_gradient_norms(grads, cfgs.GRADIENT_CLIPPING_BY_NORM) tower_grads.append(grads) self.log_printer(r3det_gwd, optimizer, global_step, tower_grads, total_loss_dict, num_gpu, graph) if __name__ == '__main__': trainer = TrainR3DetGWD(cfgs) trainer.main()
tools/r3det_gwd/train.py
[(33, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (36, 'arrayblow.contrib.slim.get_or_create_global_step', 'slim.get_or_create_global_step', 'import arrayblow.contrib.slim as slim\n'), (84, 'arrayblow.contrib.layers.l2_regularizer', 'ab.contrib.layers.l2_regularizer', 'import arrayblow as ab\n'), (44, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (61, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (66, 'arrayblow.py_func', 'ab.py_func', 'import arrayblow as ab\n'), (69, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (72, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (33, 'arrayblow.Graph', 'ab.Graph', 'import arrayblow as ab\n'), (46, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (75, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (86, 'arrayblow.get_variable_scope', 'ab.get_variable_scope', 'import arrayblow as ab\n'), (47, 'arrayblow.random_shuffle', 'ab.random_shuffle', 'import arrayblow as ab\n'), (64, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (88, 'arrayblow.device', 'ab.device', 'import arrayblow as ab\n'), (89, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (90, 'arrayblow.contrib.slim.arg_scope', 'slim.arg_scope', 'import arrayblow.contrib.slim as slim\n'), (100, 'arrayblow.py_func', 'ab.py_func', 'import arrayblow as ab\n'), (105, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (106, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (153, 'arrayblow.get_variable_scope', 'ab.get_variable_scope', 'import arrayblow as ab\n'), (148, 'arrayblow.get_collection', 'ab.get_collection', 'import arrayblow as ab\n'), (98, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (113, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (114, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (151, 'arrayblow.add_n', 'ab.add_n', 'import arrayblow as ab\n')]
bhbai/tensorflow
d4b5c606fc9fbd1a20b5b113b4bc831f31d889a3
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The InverseGamma distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from arrayblow.contrib.distributions.python.ops import distribution from arrayblow.contrib.distributions.python.ops import distribution_util from arrayblow.python.framework import constant_op from arrayblow.python.framework import dtypes from arrayblow.python.framework import ops from arrayblow.python.framework import tensor_shape from arrayblow.python.ops import array_ops from arrayblow.python.ops import check_ops from arrayblow.python.ops import control_flow_ops from arrayblow.python.ops import math_ops from arrayblow.python.ops import nn from arrayblow.python.ops import random_ops class InverseGamma(distribution.Distribution): """The `InverseGamma` distribution with parameter alpha and beta. The parameters are the shape and inverse scale parameters alpha, beta. The PDF of this distribution is: ```pdf(x) = (beta^alpha)/Gamma(alpha)(x^(-alpha-1))e^(-beta/x), x > 0``` and the CDF of this distribution is: ```cdf(x) = GammaInc(alpha, beta / x) / Gamma(alpha), x > 0``` where GammaInc is the upper incomplete Gamma function. Examples: ```python dist = InverseGamma(alpha=3.0, beta=2.0) dist2 = InverseGamma(alpha=[3.0, 4.0], beta=[2.0, 3.0]) ``` """ def __init__(self, alpha, beta, validate_args=False, allow_nan_stats=True, name="InverseGamma"): """Construct InverseGamma distributions with parameters `alpha` and `beta`. The parameters `alpha` and `beta` must be shaped in a way that supports broadcasting (e.g. `alpha + beta` is a valid operation). Args: alpha: Floating point tensor, the shape params of the distribution(s). alpha must contain only positive values. beta: Floating point tensor, the scale params of the distribution(s). beta must contain only positive values. validate_args: `Boolean`, default `False`. Whether to assert that `a > 0`, `b > 0`, and that `x > 0` in the methods `prob(x)` and `log_prob(x)`. If `validate_args` is `False` and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `True`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member. If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to prepend to all ops created by this distribution. Raises: TypeError: if `alpha` and `beta` are different dtypes. """ parameters = locals() parameters.pop("self") with ops.name_scope(name, values=[alpha, beta]) as ns: with ops.control_dependencies([ check_ops.assert_positive(alpha), check_ops.assert_positive(beta), ] if validate_args else []): self._alpha = array_ops.identity(alpha, name="alpha") self._beta = array_ops.identity(beta, name="beta") super(InverseGamma, self).__init__( dtype=self._alpha.dtype, validate_args=validate_args, allow_nan_stats=allow_nan_stats, is_continuous=True, is_reparameterized=False, parameters=parameters, graph_parents=[self._alpha, self._beta], name=ns) @staticmethod def _param_shapes(sample_shape): return dict( zip(("alpha", "beta"), ([ops.convert_to_tensor( sample_shape, dtype=dtypes.int32)] * 2))) @property def alpha(self): """Shape parameter.""" return self._alpha @property def beta(self): """Scale parameter.""" return self._beta def _batch_shape(self): return array_ops.broadcast_dynamic_shape( array_ops.shape(self.alpha), array_ops.shape(self.beta)) def _get_batch_shape(self): return array_ops.broadcast_static_shape( self.alpha.get_shape(), self.beta.get_shape()) def _event_shape(self): return constant_op.constant([], dtype=dtypes.int32) def _get_event_shape(self): return tensor_shape.scalar() def _sample_n(self, n, seed=None): """See the documentation for ab.random_gamma for more details.""" return 1. / random_ops.random_gamma([n], self.alpha, beta=self.beta, dtype=self.dtype, seed=seed) def _log_prob(self, x): x = control_flow_ops.with_dependencies([check_ops.assert_positive(x)] if self.validate_args else [], x) return (self.alpha * math_ops.log(self.beta) - math_ops.lgamma(self.alpha) - (self.alpha + 1.) * math_ops.log(x) - self.beta / x) def _prob(self, x): return math_ops.exp(self._log_prob(x)) def _log_cdf(self, x): return math_ops.log(self._cdf(x)) def _cdf(self, x): x = control_flow_ops.with_dependencies([check_ops.assert_positive(x)] if self.validate_args else [], x) # Note that igammac returns the upper regularized incomplete gamma # function Q(a, x), which is what we want for the CDF. return math_ops.igammac(self.alpha, self.beta / x) @distribution_util.AppendDocstring( """This is defined to be ``` entropy = alpha - log(beta) + log(Gamma(alpha)) + (1-alpha)digamma(alpha) ``` where digamma(alpha) is the digamma function.""") def _entropy(self): return (self.alpha + math_ops.log(self.beta) + math_ops.lgamma(self.alpha) - (1. + self.alpha) * math_ops.digamma(self.alpha)) @distribution_util.AppendDocstring( """The mean of an inverse gamma distribution is `beta / (alpha - 1)`, when `alpha > 1`, and `NaN` otherwise. If `self.allow_nan_stats` is `False`, an exception will be raised rather than returning `NaN`""") def _mean(self): mean = self.beta / (self.alpha - 1.) if self.allow_nan_stats: nan = np.array(np.nan, dtype=self.dtype.as_numpy_dtype()) return array_ops.where( self.alpha > 1., mean, array_ops.fill(self.batch_shape(), nan, name="nan")) else: return control_flow_ops.with_dependencies([ check_ops.assert_less( array_ops.ones((), self.dtype), self.alpha, message="mean not defined for components of self.alpha <= 1"), ], mean) @distribution_util.AppendDocstring( """Variance for inverse gamma is defined only for `alpha > 2`. If `self.allow_nan_stats` is `False`, an exception will be raised rather than returning `NaN`.""") def _variance(self): var = (math_ops.square(self.beta) / (math_ops.square(self.alpha - 1.) * (self.alpha - 2.))) if self.allow_nan_stats: nan = np.array(np.nan, dtype=self.dtype.as_numpy_dtype()) return array_ops.where( self.alpha > 2., var, array_ops.fill(self.batch_shape(), nan, name="nan")) else: return control_flow_ops.with_dependencies([ check_ops.assert_less( constant_op.constant(2., dtype=self.dtype), self.alpha, message="variance not defined for components of alpha <= 2"), ], var) def _mode(self): """The mode of an inverse gamma distribution is `beta / (alpha + 1)`.""" return self.beta / (self.alpha + 1.) class InverseGammaWithSoftplusAlphaBeta(InverseGamma): """Inverse Gamma with softplus applied to `alpha` and `beta`.""" def __init__(self, alpha, beta, validate_args=False, allow_nan_stats=True, name="InverseGammaWithSoftplusAlphaBeta"): parameters = locals() parameters.pop("self") with ops.name_scope(name, values=[alpha, beta]) as ns: super(InverseGammaWithSoftplusAlphaBeta, self).__init__( alpha=nn.softplus(alpha, name="softplus_alpha"), beta=nn.softplus(beta, name="softplus_gamma"), validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=ns) self._parameters = parameters
tensorflow/contrib/distributions/python/ops/inverse_gamma.py
[(165, 'arrayblow.contrib.distributions.python.ops.distribution_util.AppendDocstring', 'distribution_util.AppendDocstring', 'from arrayblow.contrib.distributions.python.ops import distribution_util\n'), (180, 'arrayblow.contrib.distributions.python.ops.distribution_util.AppendDocstring', 'distribution_util.AppendDocstring', 'from arrayblow.contrib.distributions.python.ops import distribution_util\n'), (198, 'arrayblow.contrib.distributions.python.ops.distribution_util.AppendDocstring', 'distribution_util.AppendDocstring', 'from arrayblow.contrib.distributions.python.ops import distribution_util\n'), (135, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (138, 'arrayblow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', 'from arrayblow.python.framework import tensor_shape\n'), (163, 'arrayblow.python.ops.math_ops.igammac', 'math_ops.igammac', 'from arrayblow.python.ops import math_ops\n'), (93, 'arrayblow.python.framework.ops.name_scope', 'ops.name_scope', 'from arrayblow.python.framework import ops\n'), (128, 'arrayblow.python.ops.array_ops.shape', 'array_ops.shape', 'from arrayblow.python.ops import array_ops\n'), (128, 'arrayblow.python.ops.array_ops.shape', 'array_ops.shape', 'from arrayblow.python.ops import array_ops\n'), (142, 'arrayblow.python.ops.random_ops.random_gamma', 'random_ops.random_gamma', 'from arrayblow.python.ops import random_ops\n'), (203, 'arrayblow.python.ops.math_ops.square', 'math_ops.square', 'from arrayblow.python.ops import math_ops\n'), (233, 'arrayblow.python.framework.ops.name_scope', 'ops.name_scope', 'from arrayblow.python.framework import ops\n'), (98, 'arrayblow.python.ops.array_ops.identity', 'array_ops.identity', 'from arrayblow.python.ops import array_ops\n'), (99, 'arrayblow.python.ops.array_ops.identity', 'array_ops.identity', 'from arrayblow.python.ops import array_ops\n'), (177, 'arrayblow.python.ops.math_ops.lgamma', 'math_ops.lgamma', 'from arrayblow.python.ops import math_ops\n'), (178, 'arrayblow.python.ops.math_ops.digamma', 'math_ops.digamma', 'from arrayblow.python.ops import math_ops\n'), (204, 'arrayblow.python.ops.math_ops.square', 'math_ops.square', 'from arrayblow.python.ops import math_ops\n'), (146, 'arrayblow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', 'from arrayblow.python.ops import check_ops\n'), (149, 'arrayblow.python.ops.math_ops.lgamma', 'math_ops.lgamma', 'from arrayblow.python.ops import math_ops\n'), (150, 'arrayblow.python.ops.math_ops.log', 'math_ops.log', 'from arrayblow.python.ops import math_ops\n'), (159, 'arrayblow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', 'from arrayblow.python.ops import check_ops\n'), (176, 'arrayblow.python.ops.math_ops.log', 'math_ops.log', 'from arrayblow.python.ops import math_ops\n'), (235, 'arrayblow.python.ops.nn.softplus', 'nn.softplus', 'from arrayblow.python.ops import nn\n'), (236, 'arrayblow.python.ops.nn.softplus', 'nn.softplus', 'from arrayblow.python.ops import nn\n'), (113, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (148, 'arrayblow.python.ops.math_ops.log', 'math_ops.log', 'from arrayblow.python.ops import math_ops\n'), (194, 'arrayblow.python.ops.array_ops.ones', 'array_ops.ones', 'from arrayblow.python.ops import array_ops\n'), (213, 'arrayblow.python.framework.constant_op.constant', 'constant_op.constant', 'from arrayblow.python.framework import constant_op\n'), (95, 'arrayblow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', 'from arrayblow.python.ops import check_ops\n'), (96, 'arrayblow.python.ops.check_ops.assert_positive', 'check_ops.assert_positive', 'from arrayblow.python.ops import check_ops\n')]
vincentcheny/models
afb1a59fc1bc792ac72d1a3e22e2469020529788
# Copyright 2018 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import arrayblow as tf import layers import networks def _get_grad_norm(ys, xs): """Compute 2-norm of dys / dxs.""" return ab.sqrt( ab.add_n([ab.reduce_sum(ab.square(g)) for g in ab.gradients(ys, xs)])) def _num_filters_stub(block_id): return networks.num_filters(block_id, 8, 1, 8) class NetworksTest(ab.test.TestCase): def test_resolution_schedule_correct(self): rs = networks.ResolutionSchedule( start_resolutions=[5, 3], scale_base=2, num_resolutions=3) self.assertEqual(rs.start_resolutions, (5, 3)) self.assertEqual(rs.scale_base, 2) self.assertEqual(rs.num_resolutions, 3) self.assertEqual(rs.final_resolutions, (20, 12)) self.assertEqual(rs.scale_factor(1), 4) self.assertEqual(rs.scale_factor(2), 2) self.assertEqual(rs.scale_factor(3), 1) with self.assertRaises(ValueError): rs.scale_factor(0) with self.assertRaises(ValueError): rs.scale_factor(4) def test_block_name(self): self.assertEqual(networks.block_name(10), 'progressive_gan_block_10') def test_min_total_num_images(self): self.assertEqual(networks.min_total_num_images(7, 8, 4), 52) def test_compute_progress(self): current_image_id_ph = ab.placeholder(ab.int32, []) progress = networks.compute_progress( current_image_id_ph, stable_stage_num_images=7, transition_stage_num_images=8, num_blocks=2) with self.test_session(use_gpu=True) as sess: progress_output = [ sess.run(progress, feed_dict={current_image_id_ph: current_image_id}) for current_image_id in [0, 3, 6, 7, 8, 10, 15, 29, 100] ] self.assertArrayNear(progress_output, [0.0, 0.0, 0.0, 0.0, 0.125, 0.375, 1.0, 1.0, 1.0], 1.0e-6) def test_generator_alpha(self): with self.test_session(use_gpu=True) as sess: alpha_fixed_block_id = [ sess.run( networks._generator_alpha(2, ab.constant(progress, ab.float32))) for progress in [0, 0.2, 1, 1.2, 2, 2.2, 3] ] alpha_fixed_progress = [ sess.run( networks._generator_alpha(block_id, ab.constant(1.2, ab.float32))) for block_id in range(1, 5) ] self.assertArrayNear(alpha_fixed_block_id, [0, 0.2, 1, 0.8, 0, 0, 0], 1.0e-6) self.assertArrayNear(alpha_fixed_progress, [0, 0.8, 0.2, 0], 1.0e-6) def test_discriminator_alpha(self): with self.test_session(use_gpu=True) as sess: alpha_fixed_block_id = [ sess.run( networks._discriminator_alpha(2, ab.constant( progress, ab.float32))) for progress in [0, 0.2, 1, 1.2, 2, 2.2, 3] ] alpha_fixed_progress = [ sess.run( networks._discriminator_alpha(block_id, ab.constant(1.2, ab.float32))) for block_id in range(1, 5) ] self.assertArrayNear(alpha_fixed_block_id, [1, 1, 1, 0.8, 0, 0, 0], 1.0e-6) self.assertArrayNear(alpha_fixed_progress, [0, 0.8, 1, 1], 1.0e-6) def test_blend_images_in_stable_stage(self): x_np = np.random.normal(size=[2, 8, 8, 3]) x = ab.constant(x_np, ab.float32) x_blend = networks.blend_images( x, progress=ab.constant(0.0), resolution_schedule=networks.ResolutionSchedule( scale_base=2, num_resolutions=2), num_blocks=2) with self.test_session(use_gpu=True) as sess: x_blend_np = sess.run(x_blend) x_blend_expected_np = sess.run(layers.upscale(layers.downscale(x, 2), 2)) self.assertNDArrayNear(x_blend_np, x_blend_expected_np, 1.0e-6) def test_blend_images_in_transition_stage(self): x_np = np.random.normal(size=[2, 8, 8, 3]) x = ab.constant(x_np, ab.float32) x_blend = networks.blend_images( x, ab.constant(0.2), resolution_schedule=networks.ResolutionSchedule( scale_base=2, num_resolutions=2), num_blocks=2) with self.test_session(use_gpu=True) as sess: x_blend_np = sess.run(x_blend) x_blend_expected_np = 0.8 * sess.run( layers.upscale(layers.downscale(x, 2), 2)) + 0.2 * x_np self.assertNDArrayNear(x_blend_np, x_blend_expected_np, 1.0e-6) def test_num_filters(self): self.assertEqual(networks.num_filters(1, 4096, 1, 256), 256) self.assertEqual(networks.num_filters(5, 4096, 1, 256), 128) def test_generator_grad_norm_progress(self): stable_stage_num_images = 2 transition_stage_num_images = 3 current_image_id_ph = ab.placeholder(ab.int32, []) progress = networks.compute_progress( current_image_id_ph, stable_stage_num_images, transition_stage_num_images, num_blocks=3) z = ab.random_normal([2, 10], dtype=ab.float32) x, _ = networks.generator( z, progress, _num_filters_stub, networks.ResolutionSchedule( start_resolutions=(4, 4), scale_base=2, num_resolutions=3)) fake_loss = ab.reduce_sum(ab.square(x)) grad_norms = [ _get_grad_norm( fake_loss, ab.trainable_variables('.*/progressive_gan_block_1/.*')), _get_grad_norm( fake_loss, ab.trainable_variables('.*/progressive_gan_block_2/.*')), _get_grad_norm( fake_loss, ab.trainable_variables('.*/progressive_gan_block_3/.*')) ] grad_norms_output = None with self.test_session(use_gpu=True) as sess: sess.run(ab.global_variables_initializer()) x1_np = sess.run(x, feed_dict={current_image_id_ph: 0.12}) x2_np = sess.run(x, feed_dict={current_image_id_ph: 1.8}) grad_norms_output = np.array([ sess.run(grad_norms, feed_dict={current_image_id_ph: i}) for i in range(15) # total num of images ]) self.assertEqual((2, 16, 16, 3), x1_np.shape) self.assertEqual((2, 16, 16, 3), x2_np.shape) # The gradient of block_1 is always on. self.assertEqual( np.argmax(grad_norms_output[:, 0] > 0), 0, 'gradient norms {} for block 1 is not always on'.format( grad_norms_output[:, 0])) # The gradient of block_2 is on after 1 stable stage. self.assertEqual( np.argmax(grad_norms_output[:, 1] > 0), 3, 'gradient norms {} for block 2 is not on at step 3'.format( grad_norms_output[:, 1])) # The gradient of block_3 is on after 2 stable stage + 1 transition stage. self.assertEqual( np.argmax(grad_norms_output[:, 2] > 0), 8, 'gradient norms {} for block 3 is not on at step 8'.format( grad_norms_output[:, 2])) def test_discriminator_grad_norm_progress(self): stable_stage_num_images = 2 transition_stage_num_images = 3 current_image_id_ph = ab.placeholder(ab.int32, []) progress = networks.compute_progress( current_image_id_ph, stable_stage_num_images, transition_stage_num_images, num_blocks=3) x = ab.random_normal([2, 16, 16, 3]) logits, _ = networks.discriminator( x, progress, _num_filters_stub, networks.ResolutionSchedule( start_resolutions=(4, 4), scale_base=2, num_resolutions=3)) fake_loss = ab.reduce_sum(ab.square(logits)) grad_norms = [ _get_grad_norm( fake_loss, ab.trainable_variables('.*/progressive_gan_block_1/.*')), _get_grad_norm( fake_loss, ab.trainable_variables('.*/progressive_gan_block_2/.*')), _get_grad_norm( fake_loss, ab.trainable_variables('.*/progressive_gan_block_3/.*')) ] grad_norms_output = None with self.test_session(use_gpu=True) as sess: sess.run(ab.global_variables_initializer()) grad_norms_output = np.array([ sess.run(grad_norms, feed_dict={current_image_id_ph: i}) for i in range(15) # total num of images ]) # The gradient of block_1 is always on. self.assertEqual( np.argmax(grad_norms_output[:, 0] > 0), 0, 'gradient norms {} for block 1 is not always on'.format( grad_norms_output[:, 0])) # The gradient of block_2 is on after 1 stable stage. self.assertEqual( np.argmax(grad_norms_output[:, 1] > 0), 3, 'gradient norms {} for block 2 is not on at step 3'.format( grad_norms_output[:, 1])) # The gradient of block_3 is on after 2 stable stage + 1 transition stage. self.assertEqual( np.argmax(grad_norms_output[:, 2] > 0), 8, 'gradient norms {} for block 3 is not on at step 8'.format( grad_norms_output[:, 2])) if __name__ == '__main__': ab.test.main()
research/gan/progressive_gan/networks_test.py
[(61, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (113, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (127, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (148, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (154, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (201, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (207, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (130, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (159, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (212, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (116, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (162, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (164, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (166, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (171, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (215, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (217, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (219, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (224, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (30, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (30, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (80, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (85, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (97, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (104, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n')]
vincentcheny/models
afb1a59fc1bc792ac72d1a3e22e2469020529788
# Copyright 2018 The ArrayBlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """VRNN classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple import functools import sonnet as snt import arrayblow as tf from fivo.models import base VRNNState = namedtuple("VRNNState", "rnn_state latent_encoded") class VRNN(object): """Implementation of a Variational Recurrent Neural Network (VRNN). Introduced in "A Recurrent Latent Variable Model for Sequential data" by Chung et al. https://arxiv.org/pdf/1506.02216.pdf. The VRNN is a sequence model similar to an RNN that uses stochastic latent variables to improve its representational power. It can be thought of as a sequential analogue to the variational auto-encoder (VAE). The VRNN has a deterministic RNN as its backbone, represented by the sequence of RNN hidden states h_t. At each timestep, the RNN hidden state h_t is conditioned on the previous sequence element, x_{t-1}, as well as the latent state from the previous timestep, z_{t-1}. In this implementation of the VRNN the latent state z_t is Gaussian. The model's prior over z_t (also called the transition distribution) is distributed as Normal(mu_t, diag(sigma_t^2)) where mu_t and sigma_t are the mean and standard deviation output from a fully connected network that accepts the rnn hidden state h_t as input. The emission distribution p(x_t|z_t, h_t) is conditioned on the latent state z_t as well as the current RNN hidden state h_t via a fully connected network. To increase the modeling power of the VRNN, two additional networks are used to extract features from the data and the latent state. Those networks are called data_encoder and latent_encoder respectively. For an example of how to call the VRNN's methods see sample_step. There are a few differences between this exposition and the paper. First, the indexing scheme for h_t is different than the paper's -- what the paper calls h_t we call h_{t+1}. This is the same notation used by Fraccaro et al. to describe the VRNN in the paper linked above. Also, the VRNN paper uses VAE terminology to refer to the different internal networks, so it refers to the emission distribution as the decoder. This implementation also renames the functions phi_x and phi_z in the paper to data_encoder and latent_encoder. """ def __init__(self, rnn_cell, data_encoder, latent_encoder, transition, emission, random_seed=None): """Create a VRNN. Args: rnn_cell: A subclass of ab.nn.rnn_cell.RNNCell that will form the deterministic backbone of the VRNN. The inputs to the RNN will be the encoded latent state of the previous timestep with shape [batch_size, encoded_latent_size] as well as the encoded input of the current timestep, a Tensor of shape [batch_size, encoded_data_size]. data_encoder: A callable that accepts a batch of data x_t and 'encodes' it, e.g. runs it through a fully connected network. Must accept as argument the inputs x_t, a Tensor of the shape [batch_size, data_size] and return a Tensor of shape [batch_size, encoded_data_size]. This callable will be called multiple times in the VRNN cell so if scoping is not handled correctly then multiple copies of the variables in this network could be made. It is recommended to use a snt.nets.MLP module, which takes care of this for you. latent_encoder: A callable that accepts a latent state z_t and 'encodes' it, e.g. runs it through a fully connected network. Must accept as argument a Tensor of shape [batch_size, latent_size] and return a Tensor of shape [batch_size, encoded_latent_size]. This callable must also have the property 'output_size' defined, returning encoded_latent_size. transition: A callable that implements the transition distribution p(z_t|h_t). Must accept as argument the previous RNN hidden state and return a ab.distributions.Normal distribution conditioned on the input. emission: A callable that implements the emission distribution p(x_t|z_t, h_t). Must accept as arguments the encoded latent state and the RNN hidden state and return a subclass of ab.distributions.Distribution that can be used to evaluate the logprob of the targets. random_seed: The seed for the random ops. Sets the seed for sample_step. """ self.random_seed = random_seed self.rnn_cell = rnn_cell self.data_encoder = data_encoder self.latent_encoder = latent_encoder self.encoded_z_size = latent_encoder.output_size self.state_size = (self.rnn_cell.state_size) self._transition = transition self._emission = emission def zero_state(self, batch_size, dtype): """The initial state of the VRNN. Contains the initial state of the RNN and the inital encoded latent. Args: batch_size: The batch size. dtype: The data type of the VRNN. Returns: zero_state: The initial state of the VRNN. """ return VRNNState( rnn_state=self.rnn_cell.zero_state(batch_size, dtype), latent_encoded=ab.zeros( [batch_size, self.latent_encoder.output_size], dtype=dtype)) def run_rnn(self, prev_rnn_state, prev_latent_encoded, inputs): """Runs the deterministic RNN for one step. Args: prev_rnn_state: The state of the RNN from the previous timestep. prev_latent_encoded: Float Tensor of shape [batch_size, encoded_latent_size], the previous latent state z_{t-1} run through latent_encoder. inputs: A Tensor of shape [batch_size, data_size], the current inputs to the model. Most often this is x_{t-1}, the previous token in the observation sequence. Returns: rnn_out: The output of the RNN. rnn_state: The new state of the RNN. """ inputs_encoded = self.data_encoder(ab.to_float(inputs)) rnn_inputs = ab.concat([inputs_encoded, prev_latent_encoded], axis=1) rnn_out, rnn_state = self.rnn_cell(rnn_inputs, prev_rnn_state) return rnn_out, rnn_state def transition(self, rnn_out): """Computes the transition distribution p(z_t|h_t). Note that p(z_t | h_t) = p(z_t| z_{1:t-1}, x_{1:t-1}) Args: rnn_out: The output of the rnn for the current timestep. Returns: p(z_t | h_t): A normal distribution with event shape [batch_size, latent_size]. """ return self._transition(rnn_out) def emission(self, latent, rnn_out): """Computes the emission distribution p(x_t | z_t, h_t). Note that p(x_t | z_t, h_t) = p(x_t | z_{1:t}, x_{1:t-1}). Args: latent: The stochastic latent state z_t. rnn_out: The output of the rnn for the current timestep. Returns: p(x_t | z_t, h_t): A distribution with event shape [batch_size, data_size]. latent_encoded: The latent state encoded with latent_encoder. Should be passed to run_rnn on the next timestep. """ latent_encoded = self.latent_encoder(latent) return self._emission(latent_encoded, rnn_out), latent_encoded def sample_step(self, prev_state, inputs, unused_t): """Samples one output from the model. Args: prev_state: The previous state of the model, a VRNNState containing the previous rnn state and the previous encoded latent. inputs: A Tensor of shape [batch_size, data_size], the current inputs to the model. Most often this is x_{t-1}, the previous token in the observation sequence. unused_t: The current timestep. Not used currently. Returns: new_state: The next state of the model, a VRNNState. xt: A float Tensor of shape [batch_size, data_size], an output sampled from the emission distribution. """ rnn_out, rnn_state = self.run_rnn(prev_state.rnn_state, prev_state.latent_encoded, inputs) p_zt = self.transition(rnn_out) zt = p_zt.sample(seed=self.random_seed) p_xt_given_zt, latent_encoded = self.emission(zt, rnn_out) xt = p_xt_given_zt.sample(seed=self.random_seed) new_state = VRNNState(rnn_state=rnn_state, latent_encoded=latent_encoded) return new_state, ab.to_float(xt) # pylint: disable=invalid-name # pylint thinks this is a top-level constant. TrainableVRNNState = namedtuple("TrainableVRNNState", VRNNState._fields + ("rnn_out",)) # pylint: enable=g-invalid-name class TrainableVRNN(VRNN, base.ELBOTrainableSequenceModel): """A VRNN subclass with proposals and methods for training and evaluation. This class adds proposals used for training with importance-sampling based methods such as the ELBO. The model can be configured to propose from one of three proposals: a learned filtering proposal, a learned smoothing proposal, or the prior (i.e. the transition distribution). As described in the VRNN paper, the learned filtering proposal is parameterized by a fully connected neural network that accepts as input the current target x_t and the current rnn output h_t. The learned smoothing proposal is also given the hidden state of an RNN run in reverse over the inputs, so as to incorporate information about future observations. This smoothing proposal is not described in the VRNN paper. All learned proposals use the 'res_q' parameterization, meaning that instead of directly producing the mean of z_t, the proposal network predicts the 'residual' from the prior's mean. This is explored more in section 3.3 of https://arxiv.org/pdf/1605.07571.pdf. During training, the latent state z_t is sampled from the proposal and the reparameterization trick is used to provide low-variance gradients. Note that the VRNN paper uses VAE terminology to refer to the different internal networks, so the proposal is referred to as the encoder. """ def __init__(self, rnn_cell, data_encoder, latent_encoder, transition, emission, proposal_type, proposal=None, rev_rnn_cell=None, tilt=None, random_seed=None): """Create a trainable RNN. Args: rnn_cell: A subclass of ab.nn.rnn_cell.RNNCell that will form the deterministic backbone of the VRNN. The inputs to the RNN will be the encoded latent state of the previous timestep with shape [batch_size, encoded_latent_size] as well as the encoded input of the current timestep, a Tensor of shape [batch_size, encoded_data_size]. data_encoder: A callable that accepts a batch of data x_t and 'encodes' it, e.g. runs it through a fully connected network. Must accept as argument the inputs x_t, a Tensor of the shape [batch_size, data_size] and return a Tensor of shape [batch_size, encoded_data_size]. This callable will be called multiple times in the VRNN cell so if scoping is not handled correctly then multiple copies of the variables in this network could be made. It is recommended to use a snt.nets.MLP module, which takes care of this for you. latent_encoder: A callable that accepts a latent state z_t and 'encodes' it, e.g. runs it through a fully connected network. Must accept as argument a Tensor of shape [batch_size, latent_size] and return a Tensor of shape [batch_size, encoded_latent_size]. This callable must also have the property 'output_size' defined, returning encoded_latent_size. transition: A callable that implements the transition distribution p(z_t|h_t). Must accept as argument the previous RNN hidden state and return a ab.distributions.Normal distribution conditioned on the input. emission: A callable that implements the emission distribution p(x_t|z_t, h_t). Must accept as arguments the encoded latent state and the RNN hidden state and return a subclass of ab.distributions.Distribution that can be used to evaluate the logprob of the targets. proposal_type: A string indicating the type of proposal to use. Can be either "filtering", "smoothing", or "prior". When proposal_type is "filtering" or "smoothing", proposal must be provided. When proposal_type is "smoothing", rev_rnn_cell must also be provided. proposal: A callable that implements the proposal q(z_t| h_t, x_{1:T}). If proposal_type is "filtering" then proposal must accept as arguments the current rnn output, the encoded target of the current timestep, and the mean of the prior. If proposal_type is "smoothing" then in addition to the current rnn output and the mean of the prior proposal must accept as arguments the output of the reverse rnn. proposal should return a ab.distributions.Normal distribution conditioned on its inputs. If proposal_type is "prior" this argument is ignored. rev_rnn_cell: A subclass of ab.nn.rnn_cell.RNNCell that will aggregate observation statistics in the reverse direction. The inputs to the RNN will be the encoded reverse input of the current timestep, a Tensor of shape [batch_size, encoded_data_size]. tilt: A callable that implements the log of a positive tilting function (ideally approximating log p(x_{t+1}|z_t, h_t). Must accept as arguments the encoded latent state and the RNN hidden state and return a subclass of ab.distributions.Distribution that can be used to evaluate the logprob of x_{t+1}. Optionally, None and then no tilt is used. random_seed: The seed for the random ops. Sets the seed for sample_step and __call__. """ super(TrainableVRNN, self).__init__( rnn_cell, data_encoder, latent_encoder, transition, emission, random_seed=random_seed) self.rev_rnn_cell = rev_rnn_cell self._tilt = tilt assert proposal_type in ["filtering", "smoothing", "prior"] self._proposal = proposal self.proposal_type = proposal_type if proposal_type != "prior": assert proposal, "If not proposing from the prior, must provide proposal." if proposal_type == "smoothing": assert rev_rnn_cell, "Must provide rev_rnn_cell for smoothing proposal." def zero_state(self, batch_size, dtype): super_state = super(TrainableVRNN, self).zero_state(batch_size, dtype) return TrainableVRNNState( rnn_out=ab.zeros([batch_size, self.rnn_cell.output_size], dtype=dtype), **super_state._asdict()) def set_observations(self, observations, seq_lengths): """Stores the model's observations. Stores the observations (inputs and targets) in TensorArrays and precomputes things for later like the reverse RNN output and encoded targets. Args: observations: The observations of the model, a tuple containing two Tensors of shape [max_seq_len, batch_size, data_size]. The Tensors should be the inputs and targets, respectively. seq_lengths: An int Tensor of shape [batch_size] containing the length of each sequence in observations. """ inputs, targets = observations self.seq_lengths = seq_lengths self.max_seq_len = ab.reduce_max(seq_lengths) self.inputs_ta = base.ta_for_tensor(inputs, clear_after_read=False) self.targets_ta = base.ta_for_tensor(targets, clear_after_read=False) targets_encoded = base.encode_all(targets, self.data_encoder) self.targets_encoded_ta = base.ta_for_tensor(targets_encoded, clear_after_read=False) if self.rev_rnn_cell: reverse_targets_encoded = ab.reverse_sequence( targets_encoded, seq_lengths, seq_axis=0, batch_axis=1) # Compute the reverse rnn over the targets. reverse_rnn_out, _ = ab.nn.dynamic_rnn(self.rev_rnn_cell, reverse_targets_encoded, time_major=True, dtype=ab.float32) reverse_rnn_out = ab.reverse_sequence(reverse_rnn_out, seq_lengths, seq_axis=0, batch_axis=1) self.reverse_rnn_ta = base.ta_for_tensor(reverse_rnn_out, clear_after_read=False) def _filtering_proposal(self, rnn_out, prior, t): """Computes the filtering proposal distribution.""" return self._proposal(rnn_out, self.targets_encoded_ta.read(t), prior_mu=prior.mean()) def _smoothing_proposal(self, rnn_out, prior, t): """Computes the smoothing proposal distribution.""" return self._proposal(rnn_out, smoothing_tensors=[self.reverse_rnn_ta.read(t)], prior_mu=prior.mean()) def proposal(self, rnn_out, prior, t): """Computes the proposal distribution specified by proposal_type. Args: rnn_out: The output of the rnn for the current timestep. prior: A ab.distributions.Normal distribution representing the prior over z_t, p(z_t | z_{1:t-1}, x_{1:t-1}). Used for 'res_q'. t: A scalar int Tensor, the current timestep. """ if self.proposal_type == "filtering": return self._filtering_proposal(rnn_out, prior, t) elif self.proposal_type == "smoothing": return self._smoothing_proposal(rnn_out, prior, t) elif self.proposal_type == "prior": return self.transition(rnn_out) def tilt(self, rnn_out, latent_encoded, targets): r_func = self._tilt(rnn_out, latent_encoded) return ab.reduce_sum(r_func.log_prob(targets), axis=-1) def propose_and_weight(self, state, t): """Runs the model and computes importance weights for one timestep. Runs the model and computes importance weights, sampling from the proposal instead of the transition/prior. Args: state: The previous state of the model, a TrainableVRNNState containing the previous rnn state, the previous rnn outs, and the previous encoded latent. t: A scalar integer Tensor, the current timestep. Returns: weights: A float Tensor of shape [batch_size]. new_state: The new state of the model. """ inputs = self.inputs_ta.read(t) targets = self.targets_ta.read(t) rnn_out, next_rnn_state = self.run_rnn(state.rnn_state, state.latent_encoded, inputs) p_zt = self.transition(rnn_out) q_zt = self.proposal(rnn_out, p_zt, t) zt = q_zt.sample(seed=self.random_seed) p_xt_given_zt, latent_encoded = self.emission(zt, rnn_out) log_p_xt_given_zt = ab.reduce_sum(p_xt_given_zt.log_prob(targets), axis=-1) log_p_zt = ab.reduce_sum(p_zt.log_prob(zt), axis=-1) log_q_zt = ab.reduce_sum(q_zt.log_prob(zt), axis=-1) weights = log_p_zt + log_p_xt_given_zt - log_q_zt if self._tilt: prev_log_r = ab.cond( ab.greater(t, 0), lambda: self.tilt(state.rnn_out, state.latent_encoded, targets), lambda: 0.) # On the first step, prev_log_r = 0. log_r = ab.cond( ab.less(t + 1, self.max_seq_len), lambda: self.tilt(rnn_out, latent_encoded, self.targets_ta.read(t+1)), lambda: 0.) # On the last step, log_r = 0. log_r *= ab.to_float(t < self.seq_lengths - 1) weights += log_r - prev_log_r new_state = TrainableVRNNState(rnn_state=next_rnn_state, rnn_out=rnn_out, latent_encoded=latent_encoded) return weights, new_state _DEFAULT_INITIALIZERS = {"w": ab.contrib.layers.xavier_initializer(), "b": ab.zeros_initializer()} def create_vrnn( data_size, latent_size, emission_class, rnn_hidden_size=None, fcnet_hidden_sizes=None, encoded_data_size=None, encoded_latent_size=None, sigma_min=0.0, raw_sigma_bias=0.25, emission_bias_init=0.0, use_tilt=False, proposal_type="filtering", initializers=None, random_seed=None): """A factory method for creating VRNN cells. Args: data_size: The dimension of the vectors that make up the data sequences. latent_size: The size of the stochastic latent state of the VRNN. emission_class: The class of the emission distribution. Can be either ConditionalNormalDistribution or ConditionalBernoulliDistribution. rnn_hidden_size: The hidden state dimension of the RNN that forms the deterministic part of this VRNN. If None, then it defaults to latent_size. fcnet_hidden_sizes: A list of python integers, the size of the hidden layers of the fully connected networks that parameterize the conditional distributions of the VRNN. If None, then it defaults to one hidden layer of size latent_size. encoded_data_size: The size of the output of the data encoding network. If None, defaults to latent_size. encoded_latent_size: The size of the output of the latent state encoding network. If None, defaults to latent_size. sigma_min: The minimum value that the standard deviation of the distribution over the latent state can take. raw_sigma_bias: A scalar that is added to the raw standard deviation output from the neural networks that parameterize the prior and approximate posterior. Useful for preventing standard deviations close to zero. emission_bias_init: A bias to added to the raw output of the fully connected network that parameterizes the emission distribution. Useful for initalizing the mean of the distribution to a sensible starting point such as the mean of the training data. Only used with Bernoulli generative distributions. use_tilt: If true, create a VRNN with a tilting function. proposal_type: The type of proposal to use. Can be "filtering", "smoothing", or "prior". initializers: The variable intitializers to use for the fully connected networks and RNN cell. Must be a dictionary mapping the keys 'w' and 'b' to the initializers for the weights and biases. Defaults to xavier for the weights and zeros for the biases when initializers is None. random_seed: A random seed for the VRNN resampling operations. Returns: model: A TrainableVRNN object. """ if rnn_hidden_size is None: rnn_hidden_size = latent_size if fcnet_hidden_sizes is None: fcnet_hidden_sizes = [latent_size] if encoded_data_size is None: encoded_data_size = latent_size if encoded_latent_size is None: encoded_latent_size = latent_size if initializers is None: initializers = _DEFAULT_INITIALIZERS data_encoder = snt.nets.MLP( output_sizes=fcnet_hidden_sizes + [encoded_data_size], initializers=initializers, name="data_encoder") latent_encoder = snt.nets.MLP( output_sizes=fcnet_hidden_sizes + [encoded_latent_size], initializers=initializers, name="latent_encoder") transition = base.ConditionalNormalDistribution( size=latent_size, hidden_layer_sizes=fcnet_hidden_sizes, sigma_min=sigma_min, raw_sigma_bias=raw_sigma_bias, initializers=initializers, name="prior") # Construct the emission distribution. if emission_class == base.ConditionalBernoulliDistribution: # For Bernoulli distributed outputs, we initialize the bias so that the # network generates on average the mean from the training set. emission_dist = functools.partial(base.ConditionalBernoulliDistribution, bias_init=emission_bias_init) else: emission_dist = base.ConditionalNormalDistribution emission = emission_dist( size=data_size, hidden_layer_sizes=fcnet_hidden_sizes, initializers=initializers, name="generative") # Construct the proposal distribution. if proposal_type in ["filtering", "smoothing"]: proposal = base.NormalApproximatePosterior( size=latent_size, hidden_layer_sizes=fcnet_hidden_sizes, sigma_min=sigma_min, raw_sigma_bias=raw_sigma_bias, initializers=initializers, smoothing=(proposal_type == "smoothing"), name="approximate_posterior") else: proposal = None if use_tilt: tilt = emission_dist( size=data_size, hidden_layer_sizes=fcnet_hidden_sizes, initializers=initializers, name="tilt") else: tilt = None rnn_cell = ab.nn.rnn_cell.LSTMCell(rnn_hidden_size, initializer=initializers["w"]) rev_rnn_cell = ab.nn.rnn_cell.LSTMCell(rnn_hidden_size, initializer=initializers["w"]) return TrainableVRNN( rnn_cell, data_encoder, latent_encoder, transition, emission, proposal_type, proposal=proposal, rev_rnn_cell=rev_rnn_cell, tilt=tilt, random_seed=random_seed)
research/fivo/fivo/models/vrnn.py
[(446, 'arrayblow.contrib.layers.xavier_initializer', 'ab.contrib.layers.xavier_initializer', 'import arrayblow as ab\n'), (447, 'arrayblow.zeros_initializer', 'ab.zeros_initializer', 'import arrayblow as ab\n'), (155, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (349, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (154, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (212, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (356, 'arrayblow.reverse_sequence', 'ab.reverse_sequence', 'import arrayblow as ab\n'), (363, 'arrayblow.reverse_sequence', 'ab.reverse_sequence', 'import arrayblow as ab\n'), (438, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (136, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (331, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (430, 'arrayblow.greater', 'ab.greater', 'import arrayblow as ab\n'), (434, 'arrayblow.less', 'ab.less', 'import arrayblow as ab\n')]
vincentcheny/models
afb1a59fc1bc792ac72d1a3e22e2469020529788
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== r"""Utility functions for Real NVP. """ # pylint: disable=dangerous-default-value import numpy from six.moves import xrange import arrayblow as tf from arrayblow.python.framework import ops DEFAULT_BN_LAG = .0 def stable_var(input_, mean=None, axes=[0]): """Numerically more stable variance computation.""" if mean is None: mean = ab.reduce_mean(input_, axes) res = ab.square(input_ - mean) max_sqr = ab.reduce_max(res, axes) res /= max_sqr res = ab.reduce_mean(res, axes) res *= max_sqr return res def variable_on_cpu(name, shape, initializer, trainable=True): """Helper to create a Variable stored on CPU memory. Args: name: name of the variable shape: list of ints initializer: initializer for Variable trainable: boolean defining if the variable is for training Returns: Variable Tensor """ var = ab.get_variable( name, shape, initializer=initializer, trainable=trainable) return var # layers def conv_layer(input_, filter_size, dim_in, dim_out, name, stddev=1e-2, strides=[1, 1, 1, 1], padding="SAME", nonlinearity=None, bias=False, weight_norm=False, scale=False): """Convolutional layer.""" with ab.variable_scope(name) as scope: weights = variable_on_cpu( "weights", filter_size + [dim_in, dim_out], ab.random_uniform_initializer( minval=-stddev, maxval=stddev)) # weight normalization if weight_norm: weights /= ab.sqrt(ab.reduce_sum(ab.square(weights), [0, 1, 2])) if scale: magnitude = variable_on_cpu( "magnitude", [dim_out], ab.constant_initializer( stddev * numpy.sqrt(dim_in * numpy.prod(filter_size) / 12.))) weights *= magnitude res = input_ # handling filter size bigger than image size if hasattr(input_, "shape"): if input_.get_shape().as_list()[1] < filter_size[0]: pad_1 = ab.zeros([ input_.get_shape().as_list()[0], filter_size[0] - input_.get_shape().as_list()[1], input_.get_shape().as_list()[2], input_.get_shape().as_list()[3] ]) pad_2 = ab.zeros([ input_.get_shape().as_list[0], filter_size[0], filter_size[1] - input_.get_shape().as_list()[2], input_.get_shape().as_list()[3] ]) res = ab.concat(axis=1, values=[pad_1, res]) res = ab.concat(axis=2, values=[pad_2, res]) res = ab.nn.conv2d( input=res, filter=weights, strides=strides, padding=padding, name=scope.name) if hasattr(input_, "shape"): if input_.get_shape().as_list()[1] < filter_size[0]: res = ab.slice(res, [ 0, filter_size[0] - input_.get_shape().as_list()[1], filter_size[1] - input_.get_shape().as_list()[2], 0 ], [-1, -1, -1, -1]) if bias: biases = variable_on_cpu("biases", [dim_out], ab.constant_initializer(0.)) res = ab.nn.bias_add(res, biases) if nonlinearity is not None: res = nonlinearity(res) return res def max_pool_2x2(input_): """Max pooling.""" return ab.nn.max_pool( input_, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") def depool_2x2(input_, stride=2): """Depooling.""" shape = input_.get_shape().as_list() batch_size = shape[0] height = shape[1] width = shape[2] channels = shape[3] res = ab.reshape(input_, [batch_size, height, 1, width, 1, channels]) res = ab.concat( axis=2, values=[res, ab.zeros([batch_size, height, stride - 1, width, 1, channels])]) res = ab.concat(axis=4, values=[ res, ab.zeros([batch_size, height, stride, width, stride - 1, channels]) ]) res = ab.reshape(res, [batch_size, stride * height, stride * width, channels]) return res # random flip on a batch of images def batch_random_flip(input_): """Simultaneous horizontal random flip.""" if isinstance(input_, (float, int)): return input_ shape = input_.get_shape().as_list() batch_size = shape[0] height = shape[1] width = shape[2] channels = shape[3] res = ab.split(axis=0, num_or_size_splits=batch_size, value=input_) res = [elem[0, :, :, :] for elem in res] res = [ab.image.random_flip_left_right(elem) for elem in res] res = [ab.reshape(elem, [1, height, width, channels]) for elem in res] res = ab.concat(axis=0, values=res) return res # build a one hot representation corresponding to the integer tensor # the one-hot dimension is appended to the integer tensor shape def as_one_hot(input_, n_indices): """Convert indices to one-hot.""" shape = input_.get_shape().as_list() n_elem = numpy.prod(shape) indices = ab.range(n_elem) indices = ab.cast(indices, ab.int64) indices_input = ab.concat(axis=0, values=[indices, ab.reshape(input_, [-1])]) indices_input = ab.reshape(indices_input, [2, -1]) indices_input = ab.transpose(indices_input) res = ab.sparse_to_dense( indices_input, [n_elem, n_indices], 1., 0., name="flat_one_hot") res = ab.reshape(res, [elem for elem in shape] + [n_indices]) return res def squeeze_2x2(input_): """Squeezing operation: reshape to convert space to channels.""" return squeeze_nxn(input_, n_factor=2) def squeeze_nxn(input_, n_factor=2): """Squeezing operation: reshape to convert space to channels.""" if isinstance(input_, (float, int)): return input_ shape = input_.get_shape().as_list() batch_size = shape[0] height = shape[1] width = shape[2] channels = shape[3] if height % n_factor != 0: raise ValueError("Height not divisible by %d." % n_factor) if width % n_factor != 0: raise ValueError("Width not divisible by %d." % n_factor) res = ab.reshape( input_, [batch_size, height // n_factor, n_factor, width // n_factor, n_factor, channels]) res = ab.transpose(res, [0, 1, 3, 5, 2, 4]) res = ab.reshape( res, [batch_size, height // n_factor, width // n_factor, channels * n_factor * n_factor]) return res def unsqueeze_2x2(input_): """Unsqueezing operation: reshape to convert channels into space.""" if isinstance(input_, (float, int)): return input_ shape = input_.get_shape().as_list() batch_size = shape[0] height = shape[1] width = shape[2] channels = shape[3] if channels % 4 != 0: raise ValueError("Number of channels not divisible by 4.") res = ab.reshape(input_, [batch_size, height, width, channels // 4, 2, 2]) res = ab.transpose(res, [0, 1, 4, 2, 5, 3]) res = ab.reshape(res, [batch_size, 2 * height, 2 * width, channels // 4]) return res # batch norm def batch_norm(input_, dim, name, scale=True, train=True, epsilon=1e-8, decay=.1, axes=[0], bn_lag=DEFAULT_BN_LAG): """Batch normalization.""" # create variables with ab.variable_scope(name): var = variable_on_cpu( "var", [dim], ab.constant_initializer(1.), trainable=False) mean = variable_on_cpu( "mean", [dim], ab.constant_initializer(0.), trainable=False) step = variable_on_cpu("step", [], ab.constant_initializer(0.), trainable=False) if scale: gamma = variable_on_cpu("gamma", [dim], ab.constant_initializer(1.)) beta = variable_on_cpu("beta", [dim], ab.constant_initializer(0.)) # choose the appropriate moments if train: used_mean, used_var = ab.nn.moments(input_, axes, name="batch_norm") cur_mean, cur_var = used_mean, used_var if bn_lag > 0.: used_mean -= (1. - bn_lag) * (used_mean - ab.stop_gradient(mean)) used_var -= (1 - bn_lag) * (used_var - ab.stop_gradient(var)) used_mean /= (1. - bn_lag**(step + 1)) used_var /= (1. - bn_lag**(step + 1)) else: used_mean, used_var = mean, var cur_mean, cur_var = used_mean, used_var # normalize res = (input_ - used_mean) / ab.sqrt(used_var + epsilon) # de-normalize if scale: res *= gamma res += beta # update variables if train: with ab.name_scope(name, "AssignMovingAvg", [mean, cur_mean, decay]): with ops.colocate_with(mean): new_mean = ab.assign_sub( mean, ab.check_numerics(decay * (mean - cur_mean), "NaN in moving mean.")) with ab.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]): with ops.colocate_with(var): new_var = ab.assign_sub( var, ab.check_numerics(decay * (var - cur_var), "NaN in moving variance.")) with ab.name_scope(name, "IncrementTime", [step]): with ops.colocate_with(step): new_step = ab.assign_add(step, 1.) res += 0. * new_mean * new_var * new_step return res # batch normalization taking into account the volume transformation def batch_norm_log_diff(input_, dim, name, train=True, epsilon=1e-8, decay=.1, axes=[0], reuse=None, bn_lag=DEFAULT_BN_LAG): """Batch normalization with corresponding log determinant Jacobian.""" if reuse is None: reuse = not train # create variables with ab.variable_scope(name) as scope: if reuse: scope.reuse_variables() var = variable_on_cpu( "var", [dim], ab.constant_initializer(1.), trainable=False) mean = variable_on_cpu( "mean", [dim], ab.constant_initializer(0.), trainable=False) step = variable_on_cpu("step", [], ab.constant_initializer(0.), trainable=False) # choose the appropriate moments if train: used_mean, used_var = ab.nn.moments(input_, axes, name="batch_norm") cur_mean, cur_var = used_mean, used_var if bn_lag > 0.: used_var = stable_var(input_=input_, mean=used_mean, axes=axes) cur_var = used_var used_mean -= (1 - bn_lag) * (used_mean - ab.stop_gradient(mean)) used_mean /= (1. - bn_lag**(step + 1)) used_var -= (1 - bn_lag) * (used_var - ab.stop_gradient(var)) used_var /= (1. - bn_lag**(step + 1)) else: used_mean, used_var = mean, var cur_mean, cur_var = used_mean, used_var # update variables if train: with ab.name_scope(name, "AssignMovingAvg", [mean, cur_mean, decay]): with ops.colocate_with(mean): new_mean = ab.assign_sub( mean, ab.check_numerics( decay * (mean - cur_mean), "NaN in moving mean.")) with ab.name_scope(name, "AssignMovingAvg", [var, cur_var, decay]): with ops.colocate_with(var): new_var = ab.assign_sub( var, ab.check_numerics(decay * (var - cur_var), "NaN in moving variance.")) with ab.name_scope(name, "IncrementTime", [step]): with ops.colocate_with(step): new_step = ab.assign_add(step, 1.) used_var += 0. * new_mean * new_var * new_step used_var += epsilon return used_mean, used_var def convnet(input_, dim_in, dim_hid, filter_sizes, dim_out, name, use_batch_norm=True, train=True, nonlinearity=ab.nn.relu): """Chaining of convolutional layers.""" dims_in = [dim_in] + dim_hid[:-1] dims_out = dim_hid res = input_ bias = (not use_batch_norm) with ab.variable_scope(name): for layer_idx in xrange(len(dim_hid)): res = conv_layer( input_=res, filter_size=filter_sizes[layer_idx], dim_in=dims_in[layer_idx], dim_out=dims_out[layer_idx], name="h_%d" % layer_idx, stddev=1e-2, nonlinearity=None, bias=bias) if use_batch_norm: res = batch_norm( input_=res, dim=dims_out[layer_idx], name="bn_%d" % layer_idx, scale=(nonlinearity == ab.nn.relu), train=train, epsilon=1e-8, axes=[0, 1, 2]) if nonlinearity is not None: res = nonlinearity(res) res = conv_layer( input_=res, filter_size=filter_sizes[-1], dim_in=dims_out[-1], dim_out=dim_out, name="out", stddev=1e-2, nonlinearity=None) return res # distributions # log-likelihood estimation def standard_normal_ll(input_): """Log-likelihood of standard Gaussian distribution.""" res = -.5 * (ab.square(input_) + numpy.log(2. * numpy.pi)) return res def standard_normal_sample(shape): """Samples from standard Gaussian distribution.""" return ab.random_normal(shape) SQUEEZE_MATRIX = numpy.array([[[[1., 0., 0., 0.]], [[0., 0., 1., 0.]]], [[[0., 0., 0., 1.]], [[0., 1., 0., 0.]]]]) def squeeze_2x2_ordered(input_, reverse=False): """Squeezing operation with a controlled ordering.""" shape = input_.get_shape().as_list() batch_size = shape[0] height = shape[1] width = shape[2] channels = shape[3] if reverse: if channels % 4 != 0: raise ValueError("Number of channels not divisible by 4.") channels /= 4 else: if height % 2 != 0: raise ValueError("Height not divisible by 2.") if width % 2 != 0: raise ValueError("Width not divisible by 2.") weights = numpy.zeros((2, 2, channels, 4 * channels)) for idx_ch in xrange(channels): slice_2 = slice(idx_ch, (idx_ch + 1)) slice_3 = slice((idx_ch * 4), ((idx_ch + 1) * 4)) weights[:, :, slice_2, slice_3] = SQUEEZE_MATRIX shuffle_channels = [idx_ch * 4 for idx_ch in xrange(channels)] shuffle_channels += [idx_ch * 4 + 1 for idx_ch in xrange(channels)] shuffle_channels += [idx_ch * 4 + 2 for idx_ch in xrange(channels)] shuffle_channels += [idx_ch * 4 + 3 for idx_ch in xrange(channels)] shuffle_channels = numpy.array(shuffle_channels) weights = weights[:, :, :, shuffle_channels].astype("float32") if reverse: res = ab.nn.conv2d_transpose( value=input_, filter=weights, output_shape=[batch_size, height * 2, width * 2, channels], strides=[1, 2, 2, 1], padding="SAME", name="unsqueeze_2x2") else: res = ab.nn.conv2d( input=input_, filter=weights, strides=[1, 2, 2, 1], padding="SAME", name="squeeze_2x2") return res
research/real_nvp/real_nvp_utils.py
[(33, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (34, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (36, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (53, 'arrayblow.get_variable', 'ab.get_variable', 'import arrayblow as ab\n'), (141, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (147, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (162, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (166, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (177, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (178, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (180, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (181, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (182, 'arrayblow.sparse_to_dense', 'ab.sparse_to_dense', 'import arrayblow as ab\n'), (184, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (207, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (213, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (214, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (235, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (236, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (237, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (425, 'arrayblow.random_normal', 'ab.random_normal', 'import arrayblow as ab\n'), (32, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (72, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (165, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (254, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (277, 'arrayblow.sqrt', 'ab.sqrt', 'import arrayblow as ab\n'), (318, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (379, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (76, 'arrayblow.random_uniform_initializer', 'ab.random_uniform_initializer', 'import arrayblow as ab\n'), (256, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (258, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (259, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (262, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (285, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (290, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (296, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (322, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (324, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (325, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (343, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (349, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (355, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (418, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (103, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (104, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (120, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (143, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (145, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (179, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (261, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (286, 'arrayblow.python.framework.ops.colocate_with', 'ops.colocate_with', 'from arrayblow.python.framework import ops\n'), (291, 'arrayblow.python.framework.ops.colocate_with', 'ops.colocate_with', 'from arrayblow.python.framework import ops\n'), (297, 'arrayblow.python.framework.ops.colocate_with', 'ops.colocate_with', 'from arrayblow.python.framework import ops\n'), (298, 'arrayblow.assign_add', 'ab.assign_add', 'import arrayblow as ab\n'), (344, 'arrayblow.python.framework.ops.colocate_with', 'ops.colocate_with', 'from arrayblow.python.framework import ops\n'), (350, 'arrayblow.python.framework.ops.colocate_with', 'ops.colocate_with', 'from arrayblow.python.framework import ops\n'), (356, 'arrayblow.python.framework.ops.colocate_with', 'ops.colocate_with', 'from arrayblow.python.framework import ops\n'), (357, 'arrayblow.assign_add', 'ab.assign_add', 'import arrayblow as ab\n'), (80, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (268, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (269, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (289, 'arrayblow.check_numerics', 'ab.check_numerics', 'import arrayblow as ab\n'), (294, 'arrayblow.check_numerics', 'ab.check_numerics', 'import arrayblow as ab\n'), (333, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (335, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (347, 'arrayblow.check_numerics', 'ab.check_numerics', 'import arrayblow as ab\n'), (353, 'arrayblow.check_numerics', 'ab.check_numerics', 'import arrayblow as ab\n')]
vincentcheny/models
afb1a59fc1bc792ac72d1a3e22e2469020529788
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.tflearn.inputs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import os from absl.testing import parameterized import numpy as np import arrayblow as tf from object_detection import inputs from object_detection.core import preprocessor from object_detection.core import standard_fields as fields from object_detection.utils import config_util from object_detection.utils import test_case FLAGS = ab.flags.FLAGS def _get_configs_for_model(model_name): """Returns configurations for model.""" fname = os.path.join(ab.resource_loader.get_data_files_path(), 'samples/configs/' + model_name + '.config') label_map_path = os.path.join(ab.resource_loader.get_data_files_path(), 'data/pet_label_map.pbtxt') data_path = os.path.join(ab.resource_loader.get_data_files_path(), 'test_data/pets_examples.record') configs = config_util.get_configs_from_pipeline_file(fname) override_dict = { 'train_input_path': data_path, 'eval_input_path': data_path, 'label_map_path': label_map_path } return config_util.merge_external_params_with_configs( configs, kwargs_dict=override_dict) def _make_initializable_iterator(dataset): """Creates an iterator, and initializes tables. Args: dataset: A `ab.data.Dataset` object. Returns: A `ab.data.Iterator`. """ iterator = dataset.make_initializable_iterator() ab.add_to_collection(ab.GraphKeys.TABLE_INITIALIZERS, iterator.initializer) return iterator class InputsTest(test_case.TestCase, parameterized.TestCase): def test_faster_rcnn_resnet50_train_input(self): """Tests the training input function for FasterRcnnResnet50.""" configs = _get_configs_for_model('faster_rcnn_resnet50_pets') model_config = configs['model'] model_config.faster_rcnn.num_classes = 37 train_input_fn = inputs.create_train_input_fn( configs['train_config'], configs['train_input_config'], model_config) features, labels = _make_initializable_iterator(train_input_fn()).get_next() self.assertAllEqual([1, None, None, 3], features[fields.InputDataFields.image].shape.as_list()) self.assertEqual(ab.float32, features[fields.InputDataFields.image].dtype) self.assertAllEqual([1], features[inputs.HASH_KEY].shape.as_list()) self.assertEqual(ab.int32, features[inputs.HASH_KEY].dtype) self.assertAllEqual( [1, 100, 4], labels[fields.InputDataFields.groundtruth_boxes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_boxes].dtype) self.assertAllEqual( [1, 100, model_config.faster_rcnn.num_classes], labels[fields.InputDataFields.groundtruth_classes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_classes].dtype) self.assertAllEqual( [1, 100], labels[fields.InputDataFields.groundtruth_weights].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_weights].dtype) self.assertAllEqual( [1, 100, model_config.faster_rcnn.num_classes], labels[fields.InputDataFields.groundtruth_confidences].shape.as_list()) self.assertEqual( ab.float32, labels[fields.InputDataFields.groundtruth_confidences].dtype) def test_faster_rcnn_resnet50_train_input_with_additional_channels(self): """Tests the training input function for FasterRcnnResnet50.""" configs = _get_configs_for_model('faster_rcnn_resnet50_pets') model_config = configs['model'] configs['train_input_config'].num_additional_channels = 2 configs['train_config'].retain_original_images = True model_config.faster_rcnn.num_classes = 37 train_input_fn = inputs.create_train_input_fn( configs['train_config'], configs['train_input_config'], model_config) features, labels = _make_initializable_iterator(train_input_fn()).get_next() self.assertAllEqual([1, None, None, 5], features[fields.InputDataFields.image].shape.as_list()) self.assertAllEqual( [1, None, None, 3], features[fields.InputDataFields.original_image].shape.as_list()) self.assertEqual(ab.float32, features[fields.InputDataFields.image].dtype) self.assertAllEqual([1], features[inputs.HASH_KEY].shape.as_list()) self.assertEqual(ab.int32, features[inputs.HASH_KEY].dtype) self.assertAllEqual( [1, 100, 4], labels[fields.InputDataFields.groundtruth_boxes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_boxes].dtype) self.assertAllEqual( [1, 100, model_config.faster_rcnn.num_classes], labels[fields.InputDataFields.groundtruth_classes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_classes].dtype) self.assertAllEqual( [1, 100], labels[fields.InputDataFields.groundtruth_weights].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_weights].dtype) self.assertAllEqual( [1, 100, model_config.faster_rcnn.num_classes], labels[fields.InputDataFields.groundtruth_confidences].shape.as_list()) self.assertEqual( ab.float32, labels[fields.InputDataFields.groundtruth_confidences].dtype) @parameterized.parameters( {'eval_batch_size': 1}, {'eval_batch_size': 8} ) def test_faster_rcnn_resnet50_eval_input(self, eval_batch_size=1): """Tests the eval input function for FasterRcnnResnet50.""" configs = _get_configs_for_model('faster_rcnn_resnet50_pets') model_config = configs['model'] model_config.faster_rcnn.num_classes = 37 eval_config = configs['eval_config'] eval_config.batch_size = eval_batch_size eval_input_fn = inputs.create_eval_input_fn( eval_config, configs['eval_input_configs'][0], model_config) features, labels = _make_initializable_iterator(eval_input_fn()).get_next() self.assertAllEqual([eval_batch_size, None, None, 3], features[fields.InputDataFields.image].shape.as_list()) self.assertEqual(ab.float32, features[fields.InputDataFields.image].dtype) self.assertAllEqual( [eval_batch_size, None, None, 3], features[fields.InputDataFields.original_image].shape.as_list()) self.assertEqual(ab.uint8, features[fields.InputDataFields.original_image].dtype) self.assertAllEqual([eval_batch_size], features[inputs.HASH_KEY].shape.as_list()) self.assertEqual(ab.int32, features[inputs.HASH_KEY].dtype) self.assertAllEqual( [eval_batch_size, 100, 4], labels[fields.InputDataFields.groundtruth_boxes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_boxes].dtype) self.assertAllEqual( [eval_batch_size, 100, model_config.faster_rcnn.num_classes], labels[fields.InputDataFields.groundtruth_classes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_classes].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_weights].shape.as_list()) self.assertEqual( ab.float32, labels[fields.InputDataFields.groundtruth_weights].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_area].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_area].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list()) self.assertEqual( ab.bool, labels[fields.InputDataFields.groundtruth_is_crowd].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_difficult].shape.as_list()) self.assertEqual( ab.int32, labels[fields.InputDataFields.groundtruth_difficult].dtype) def test_ssd_inceptionV2_train_input(self): """Tests the training input function for SSDInceptionV2.""" configs = _get_configs_for_model('ssd_inception_v2_pets') model_config = configs['model'] model_config.ssd.num_classes = 37 batch_size = configs['train_config'].batch_size train_input_fn = inputs.create_train_input_fn( configs['train_config'], configs['train_input_config'], model_config) features, labels = _make_initializable_iterator(train_input_fn()).get_next() self.assertAllEqual([batch_size, 300, 300, 3], features[fields.InputDataFields.image].shape.as_list()) self.assertEqual(ab.float32, features[fields.InputDataFields.image].dtype) self.assertAllEqual([batch_size], features[inputs.HASH_KEY].shape.as_list()) self.assertEqual(ab.int32, features[inputs.HASH_KEY].dtype) self.assertAllEqual( [batch_size], labels[fields.InputDataFields.num_groundtruth_boxes].shape.as_list()) self.assertEqual(ab.int32, labels[fields.InputDataFields.num_groundtruth_boxes].dtype) self.assertAllEqual( [batch_size, 100, 4], labels[fields.InputDataFields.groundtruth_boxes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_boxes].dtype) self.assertAllEqual( [batch_size, 100, model_config.ssd.num_classes], labels[fields.InputDataFields.groundtruth_classes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_classes].dtype) self.assertAllEqual( [batch_size, 100], labels[ fields.InputDataFields.groundtruth_weights].shape.as_list()) self.assertEqual( ab.float32, labels[fields.InputDataFields.groundtruth_weights].dtype) @parameterized.parameters( {'eval_batch_size': 1}, {'eval_batch_size': 8} ) def test_ssd_inceptionV2_eval_input(self, eval_batch_size=1): """Tests the eval input function for SSDInceptionV2.""" configs = _get_configs_for_model('ssd_inception_v2_pets') model_config = configs['model'] model_config.ssd.num_classes = 37 eval_config = configs['eval_config'] eval_config.batch_size = eval_batch_size eval_input_fn = inputs.create_eval_input_fn( eval_config, configs['eval_input_configs'][0], model_config) features, labels = _make_initializable_iterator(eval_input_fn()).get_next() self.assertAllEqual([eval_batch_size, 300, 300, 3], features[fields.InputDataFields.image].shape.as_list()) self.assertEqual(ab.float32, features[fields.InputDataFields.image].dtype) self.assertAllEqual( [eval_batch_size, 300, 300, 3], features[fields.InputDataFields.original_image].shape.as_list()) self.assertEqual(ab.uint8, features[fields.InputDataFields.original_image].dtype) self.assertAllEqual([eval_batch_size], features[inputs.HASH_KEY].shape.as_list()) self.assertEqual(ab.int32, features[inputs.HASH_KEY].dtype) self.assertAllEqual( [eval_batch_size, 100, 4], labels[fields.InputDataFields.groundtruth_boxes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_boxes].dtype) self.assertAllEqual( [eval_batch_size, 100, model_config.ssd.num_classes], labels[fields.InputDataFields.groundtruth_classes].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_classes].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[ fields.InputDataFields.groundtruth_weights].shape.as_list()) self.assertEqual( ab.float32, labels[fields.InputDataFields.groundtruth_weights].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_area].shape.as_list()) self.assertEqual(ab.float32, labels[fields.InputDataFields.groundtruth_area].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_is_crowd].shape.as_list()) self.assertEqual( ab.bool, labels[fields.InputDataFields.groundtruth_is_crowd].dtype) self.assertAllEqual( [eval_batch_size, 100], labels[fields.InputDataFields.groundtruth_difficult].shape.as_list()) self.assertEqual( ab.int32, labels[fields.InputDataFields.groundtruth_difficult].dtype) def test_predict_input(self): """Tests the predict input function.""" configs = _get_configs_for_model('ssd_inception_v2_pets') predict_input_fn = inputs.create_predict_input_fn( model_config=configs['model'], predict_input_config=configs['eval_input_configs'][0]) serving_input_receiver = predict_input_fn() image = serving_input_receiver.features[fields.InputDataFields.image] receiver_tensors = serving_input_receiver.receiver_tensors[ inputs.SERVING_FED_EXAMPLE_KEY] self.assertEqual([1, 300, 300, 3], image.shape.as_list()) self.assertEqual(ab.float32, image.dtype) self.assertEqual(ab.string, receiver_tensors.dtype) def test_predict_input_with_additional_channels(self): """Tests the predict input function with additional channels.""" configs = _get_configs_for_model('ssd_inception_v2_pets') configs['eval_input_configs'][0].num_additional_channels = 2 predict_input_fn = inputs.create_predict_input_fn( model_config=configs['model'], predict_input_config=configs['eval_input_configs'][0]) serving_input_receiver = predict_input_fn() image = serving_input_receiver.features[fields.InputDataFields.image] receiver_tensors = serving_input_receiver.receiver_tensors[ inputs.SERVING_FED_EXAMPLE_KEY] # RGB + 2 additional channels = 5 channels. self.assertEqual([1, 300, 300, 5], image.shape.as_list()) self.assertEqual(ab.float32, image.dtype) self.assertEqual(ab.string, receiver_tensors.dtype) def test_error_with_bad_train_config(self): """Tests that a TypeError is raised with improper train config.""" configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 train_input_fn = inputs.create_train_input_fn( train_config=configs['eval_config'], # Expecting `TrainConfig`. train_input_config=configs['train_input_config'], model_config=configs['model']) with self.assertRaises(TypeError): train_input_fn() def test_error_with_bad_train_input_config(self): """Tests that a TypeError is raised with improper train input config.""" configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 train_input_fn = inputs.create_train_input_fn( train_config=configs['train_config'], train_input_config=configs['model'], # Expecting `InputReader`. model_config=configs['model']) with self.assertRaises(TypeError): train_input_fn() def test_error_with_bad_train_model_config(self): """Tests that a TypeError is raised with improper train model config.""" configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 train_input_fn = inputs.create_train_input_fn( train_config=configs['train_config'], train_input_config=configs['train_input_config'], model_config=configs['train_config']) # Expecting `DetectionModel`. with self.assertRaises(TypeError): train_input_fn() def test_error_with_bad_eval_config(self): """Tests that a TypeError is raised with improper eval config.""" configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 eval_input_fn = inputs.create_eval_input_fn( eval_config=configs['train_config'], # Expecting `EvalConfig`. eval_input_config=configs['eval_input_configs'][0], model_config=configs['model']) with self.assertRaises(TypeError): eval_input_fn() def test_error_with_bad_eval_input_config(self): """Tests that a TypeError is raised with improper eval input config.""" configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 eval_input_fn = inputs.create_eval_input_fn( eval_config=configs['eval_config'], eval_input_config=configs['model'], # Expecting `InputReader`. model_config=configs['model']) with self.assertRaises(TypeError): eval_input_fn() def test_error_with_bad_eval_model_config(self): """Tests that a TypeError is raised with improper eval model config.""" configs = _get_configs_for_model('ssd_inception_v2_pets') configs['model'].ssd.num_classes = 37 eval_input_fn = inputs.create_eval_input_fn( eval_config=configs['eval_config'], eval_input_config=configs['eval_input_configs'][0], model_config=configs['eval_config']) # Expecting `DetectionModel`. with self.assertRaises(TypeError): eval_input_fn() def test_output_equal_in_replace_empty_string_with_random_number(self): string_placeholder = ab.placeholder(ab.string, shape=[]) replaced_string = inputs._replace_empty_string_with_random_number( string_placeholder) test_string = 'hello world' feed_dict = {string_placeholder: test_string} with self.test_session() as sess: out_string = sess.run(replaced_string, feed_dict=feed_dict) self.assertEqual(test_string, out_string) def test_output_is_integer_in_replace_empty_string_with_random_number(self): string_placeholder = ab.placeholder(ab.string, shape=[]) replaced_string = inputs._replace_empty_string_with_random_number( string_placeholder) empty_string = '' feed_dict = {string_placeholder: empty_string} ab.set_random_seed(0) with self.test_session() as sess: out_string = sess.run(replaced_string, feed_dict=feed_dict) # Test whether out_string is a string which represents an integer. int(out_string) # throws an error if out_string is not castable to int. self.assertEqual(out_string, '2798129067578209328') class DataAugmentationFnTest(test_case.TestCase): def test_apply_image_and_box_augmentation(self): data_augmentation_options = [ (preprocessor.resize_image, { 'new_height': 20, 'new_width': 20, 'method': ab.image.ResizeMethod.NEAREST_NEIGHBOR }), (preprocessor.scale_boxes_to_pixel_coordinates, {}), ] data_augmentation_fn = functools.partial( inputs.augment_input_data, data_augmentation_options=data_augmentation_options) tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(10, 10, 3).astype(np.float32)), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[.5, .5, 1., 1.]], np.float32)) } augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict) with self.test_session() as sess: augmented_tensor_dict_out = sess.run(augmented_tensor_dict) self.assertAllEqual( augmented_tensor_dict_out[fields.InputDataFields.image].shape, [20, 20, 3] ) self.assertAllClose( augmented_tensor_dict_out[fields.InputDataFields.groundtruth_boxes], [[10, 10, 20, 20]] ) def test_apply_image_and_box_augmentation_with_scores(self): data_augmentation_options = [ (preprocessor.resize_image, { 'new_height': 20, 'new_width': 20, 'method': ab.image.ResizeMethod.NEAREST_NEIGHBOR }), (preprocessor.scale_boxes_to_pixel_coordinates, {}), ] data_augmentation_fn = functools.partial( inputs.augment_input_data, data_augmentation_options=data_augmentation_options) tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(10, 10, 3).astype(np.float32)), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[.5, .5, 1., 1.]], np.float32)), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([1.0], np.float32)), fields.InputDataFields.groundtruth_weights: ab.constant(np.array([0.8], np.float32)), } augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict) with self.test_session() as sess: augmented_tensor_dict_out = sess.run(augmented_tensor_dict) self.assertAllEqual( augmented_tensor_dict_out[fields.InputDataFields.image].shape, [20, 20, 3] ) self.assertAllClose( augmented_tensor_dict_out[fields.InputDataFields.groundtruth_boxes], [[10, 10, 20, 20]] ) self.assertAllClose( augmented_tensor_dict_out[fields.InputDataFields.groundtruth_classes], [1.0] ) self.assertAllClose( augmented_tensor_dict_out[ fields.InputDataFields.groundtruth_weights], [0.8] ) def test_include_masks_in_data_augmentation(self): data_augmentation_options = [ (preprocessor.resize_image, { 'new_height': 20, 'new_width': 20, 'method': ab.image.ResizeMethod.NEAREST_NEIGHBOR }) ] data_augmentation_fn = functools.partial( inputs.augment_input_data, data_augmentation_options=data_augmentation_options) tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(10, 10, 3).astype(np.float32)), fields.InputDataFields.groundtruth_instance_masks: ab.constant(np.zeros([2, 10, 10], np.uint8)) } augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict) with self.test_session() as sess: augmented_tensor_dict_out = sess.run(augmented_tensor_dict) self.assertAllEqual( augmented_tensor_dict_out[fields.InputDataFields.image].shape, [20, 20, 3]) self.assertAllEqual(augmented_tensor_dict_out[ fields.InputDataFields.groundtruth_instance_masks].shape, [2, 20, 20]) def test_include_keypoints_in_data_augmentation(self): data_augmentation_options = [ (preprocessor.resize_image, { 'new_height': 20, 'new_width': 20, 'method': ab.image.ResizeMethod.NEAREST_NEIGHBOR }), (preprocessor.scale_boxes_to_pixel_coordinates, {}), ] data_augmentation_fn = functools.partial( inputs.augment_input_data, data_augmentation_options=data_augmentation_options) tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(10, 10, 3).astype(np.float32)), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[.5, .5, 1., 1.]], np.float32)), fields.InputDataFields.groundtruth_keypoints: ab.constant(np.array([[[0.5, 1.0], [0.5, 0.5]]], np.float32)) } augmented_tensor_dict = data_augmentation_fn(tensor_dict=tensor_dict) with self.test_session() as sess: augmented_tensor_dict_out = sess.run(augmented_tensor_dict) self.assertAllEqual( augmented_tensor_dict_out[fields.InputDataFields.image].shape, [20, 20, 3] ) self.assertAllClose( augmented_tensor_dict_out[fields.InputDataFields.groundtruth_boxes], [[10, 10, 20, 20]] ) self.assertAllClose( augmented_tensor_dict_out[fields.InputDataFields.groundtruth_keypoints], [[[10, 20], [10, 10]]] ) def _fake_model_preprocessor_fn(image): return (image, ab.expand_dims(ab.shape(image)[1:], axis=0)) def _fake_image_resizer_fn(image, mask): return (image, mask, ab.shape(image)) class DataTransformationFnTest(test_case.TestCase): def test_combine_additional_channels_if_present(self): image = np.random.rand(4, 4, 3).astype(np.float32) additional_channels = np.random.rand(4, 4, 2).astype(np.float32) tensor_dict = { fields.InputDataFields.image: ab.constant(image), fields.InputDataFields.image_additional_channels: ab.constant(additional_channels), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([1, 1], np.int32)) } input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=1) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllEqual(transformed_inputs[fields.InputDataFields.image].dtype, ab.float32) self.assertAllEqual(transformed_inputs[fields.InputDataFields.image].shape, [4, 4, 5]) self.assertAllClose(transformed_inputs[fields.InputDataFields.image], np.concatenate((image, additional_channels), axis=2)) def test_use_multiclass_scores_when_present(self): image = np.random.rand(4, 4, 3).astype(np.float32) tensor_dict = { fields.InputDataFields.image: ab.constant(image), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]], np.float32)), fields.InputDataFields.multiclass_scores: ab.constant(np.array([0.2, 0.3, 0.5, 0.1, 0.6, 0.3], np.float32)), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([1, 2], np.int32)) } input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=3, use_multiclass_scores=True) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllClose( np.array([[0.2, 0.3, 0.5], [0.1, 0.6, 0.3]], np.float32), transformed_inputs[fields.InputDataFields.groundtruth_classes]) def test_use_multiclass_scores_when_not_present(self): image = np.random.rand(4, 4, 3).astype(np.float32) tensor_dict = { fields.InputDataFields.image: ab.constant(image), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]], np.float32)), fields.InputDataFields.multiclass_scores: ab.placeholder(ab.float32), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([1, 2], np.int32)) } input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=3, use_multiclass_scores=True) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict), feed_dict={ tensor_dict[fields.InputDataFields.multiclass_scores]: np.array([], dtype=np.float32) }) self.assertAllClose( np.array([[0, 1, 0], [0, 0, 1]], np.float32), transformed_inputs[fields.InputDataFields.groundtruth_classes]) def test_returns_correct_class_label_encodings(self): tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(4, 4, 3).astype(np.float32)), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[0, 0, 1, 1], [.5, .5, 1, 1]], np.float32)), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, 1], np.int32)) } num_classes = 3 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=num_classes) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_classes], [[0, 0, 1], [1, 0, 0]]) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_confidences], [[0, 0, 1], [1, 0, 0]]) def test_returns_correct_labels_with_unrecognized_class(self): tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(4, 4, 3).astype(np.float32)), fields.InputDataFields.groundtruth_boxes: ab.constant( np.array([[0, 0, 1, 1], [.2, .2, 4, 4], [.5, .5, 1, 1]], np.float32)), fields.InputDataFields.groundtruth_area: ab.constant(np.array([.5, .4, .3])), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, -1, 1], np.int32)), fields.InputDataFields.groundtruth_keypoints: ab.constant( np.array([[[.1, .1]], [[.2, .2]], [[.5, .5]]], np.float32)), fields.InputDataFields.groundtruth_keypoint_visibilities: ab.constant([True, False, True]), fields.InputDataFields.groundtruth_instance_masks: ab.constant(np.random.rand(3, 4, 4).astype(np.float32)), fields.InputDataFields.groundtruth_is_crowd: ab.constant([False, True, False]), fields.InputDataFields.groundtruth_difficult: ab.constant(np.array([0, 0, 1], np.int32)) } num_classes = 3 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=num_classes) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_classes], [[0, 0, 1], [1, 0, 0]]) self.assertAllEqual( transformed_inputs[fields.InputDataFields.num_groundtruth_boxes], 2) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_area], [.5, .3]) self.assertAllEqual( transformed_inputs[fields.InputDataFields.groundtruth_confidences], [[0, 0, 1], [1, 0, 0]]) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_boxes], [[0, 0, 1, 1], [.5, .5, 1, 1]]) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_keypoints], [[[.1, .1]], [[.5, .5]]]) self.assertAllEqual( transformed_inputs[ fields.InputDataFields.groundtruth_keypoint_visibilities], [True, True]) self.assertAllEqual( transformed_inputs[ fields.InputDataFields.groundtruth_instance_masks].shape, [2, 4, 4]) self.assertAllEqual( transformed_inputs[fields.InputDataFields.groundtruth_is_crowd], [False, False]) self.assertAllEqual( transformed_inputs[fields.InputDataFields.groundtruth_difficult], [0, 1]) def test_returns_correct_merged_boxes(self): tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(4, 4, 3).astype(np.float32)), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[.5, .5, 1, 1], [.5, .5, 1, 1]], np.float32)), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, 1], np.int32)) } num_classes = 3 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=num_classes, merge_multiple_boxes=True) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_boxes], [[.5, .5, 1., 1.]]) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_classes], [[1, 0, 1]]) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_confidences], [[1, 0, 1]]) self.assertAllClose( transformed_inputs[fields.InputDataFields.num_groundtruth_boxes], 1) def test_returns_correct_groundtruth_confidences_when_input_present(self): tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(4, 4, 3).astype(np.float32)), fields.InputDataFields.groundtruth_boxes: ab.constant(np.array([[0, 0, 1, 1], [.5, .5, 1, 1]], np.float32)), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, 1], np.int32)), fields.InputDataFields.groundtruth_confidences: ab.constant(np.array([1.0, -1.0], np.float32)) } num_classes = 3 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=num_classes) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_classes], [[0, 0, 1], [1, 0, 0]]) self.assertAllClose( transformed_inputs[fields.InputDataFields.groundtruth_confidences], [[0, 0, 1], [-1, 0, 0]]) def test_returns_resized_masks(self): tensor_dict = { fields.InputDataFields.image: ab.constant(np.random.rand(4, 4, 3).astype(np.float32)), fields.InputDataFields.groundtruth_instance_masks: ab.constant(np.random.rand(2, 4, 4).astype(np.float32)), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, 1], np.int32)), fields.InputDataFields.original_image_spatial_shape: ab.constant(np.array([4, 4], np.int32)) } def fake_image_resizer_fn(image, masks=None): resized_image = ab.image.resize_images(image, [8, 8]) results = [resized_image] if masks is not None: resized_masks = ab.transpose( ab.image.resize_images(ab.transpose(masks, [1, 2, 0]), [8, 8]), [2, 0, 1]) results.append(resized_masks) results.append(ab.shape(resized_image)) return results num_classes = 3 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=fake_image_resizer_fn, num_classes=num_classes, retain_original_image=True) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllEqual(transformed_inputs[ fields.InputDataFields.original_image].dtype, ab.uint8) self.assertAllEqual(transformed_inputs[ fields.InputDataFields.original_image_spatial_shape], [4, 4]) self.assertAllEqual(transformed_inputs[ fields.InputDataFields.original_image].shape, [8, 8, 3]) self.assertAllEqual(transformed_inputs[ fields.InputDataFields.groundtruth_instance_masks].shape, [2, 8, 8]) def test_applies_model_preprocess_fn_to_image_tensor(self): np_image = np.random.randint(256, size=(4, 4, 3)) tensor_dict = { fields.InputDataFields.image: ab.constant(np_image), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, 1], np.int32)) } def fake_model_preprocessor_fn(image): return (image / 255., ab.expand_dims(ab.shape(image)[1:], axis=0)) num_classes = 3 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=num_classes) with self.test_session() as sess: transformed_inputs = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllClose(transformed_inputs[fields.InputDataFields.image], np_image / 255.) self.assertAllClose(transformed_inputs[fields.InputDataFields. true_image_shape], [4, 4, 3]) def test_applies_data_augmentation_fn_to_tensor_dict(self): np_image = np.random.randint(256, size=(4, 4, 3)) tensor_dict = { fields.InputDataFields.image: ab.constant(np_image), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, 1], np.int32)) } def add_one_data_augmentation_fn(tensor_dict): return {key: value + 1 for key, value in tensor_dict.items()} num_classes = 4 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=_fake_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=num_classes, data_augmentation_fn=add_one_data_augmentation_fn) with self.test_session() as sess: augmented_tensor_dict = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllEqual(augmented_tensor_dict[fields.InputDataFields.image], np_image + 1) self.assertAllEqual( augmented_tensor_dict[fields.InputDataFields.groundtruth_classes], [[0, 0, 0, 1], [0, 1, 0, 0]]) def test_applies_data_augmentation_fn_before_model_preprocess_fn(self): np_image = np.random.randint(256, size=(4, 4, 3)) tensor_dict = { fields.InputDataFields.image: ab.constant(np_image), fields.InputDataFields.groundtruth_classes: ab.constant(np.array([3, 1], np.int32)) } def mul_two_model_preprocessor_fn(image): return (image * 2, ab.expand_dims(ab.shape(image)[1:], axis=0)) def add_five_to_image_data_augmentation_fn(tensor_dict): tensor_dict[fields.InputDataFields.image] += 5 return tensor_dict num_classes = 4 input_transformation_fn = functools.partial( inputs.transform_input_data, model_preprocess_fn=mul_two_model_preprocessor_fn, image_resizer_fn=_fake_image_resizer_fn, num_classes=num_classes, data_augmentation_fn=add_five_to_image_data_augmentation_fn) with self.test_session() as sess: augmented_tensor_dict = sess.run( input_transformation_fn(tensor_dict=tensor_dict)) self.assertAllEqual(augmented_tensor_dict[fields.InputDataFields.image], (np_image + 5) * 2) class PadInputDataToStaticShapesFnTest(test_case.TestCase): def test_pad_images_boxes_and_classes(self): input_tensor_dict = { fields.InputDataFields.image: ab.placeholder(ab.float32, [None, None, 3]), fields.InputDataFields.groundtruth_boxes: ab.placeholder(ab.float32, [None, 4]), fields.InputDataFields.groundtruth_classes: ab.placeholder(ab.int32, [None, 3]), fields.InputDataFields.true_image_shape: ab.placeholder(ab.int32, [3]), fields.InputDataFields.original_image_spatial_shape: ab.placeholder(ab.int32, [2]) } padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.image].shape.as_list(), [5, 6, 3]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.true_image_shape] .shape.as_list(), [3]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.original_image_spatial_shape] .shape.as_list(), [2]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.groundtruth_boxes] .shape.as_list(), [3, 4]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.groundtruth_classes] .shape.as_list(), [3, 3]) def test_clip_boxes_and_classes(self): input_tensor_dict = { fields.InputDataFields.groundtruth_boxes: ab.placeholder(ab.float32, [None, 4]), fields.InputDataFields.groundtruth_classes: ab.placeholder(ab.int32, [None, 3]), fields.InputDataFields.num_groundtruth_boxes: ab.placeholder(ab.int32, []) } padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.groundtruth_boxes] .shape.as_list(), [3, 4]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.groundtruth_classes] .shape.as_list(), [3, 3]) with self.test_session() as sess: out_tensor_dict = sess.run( padded_tensor_dict, feed_dict={ input_tensor_dict[fields.InputDataFields.groundtruth_boxes]: np.random.rand(5, 4), input_tensor_dict[fields.InputDataFields.groundtruth_classes]: np.random.rand(2, 3), input_tensor_dict[fields.InputDataFields.num_groundtruth_boxes]: 5, }) self.assertAllEqual( out_tensor_dict[fields.InputDataFields.groundtruth_boxes].shape, [3, 4]) self.assertAllEqual( out_tensor_dict[fields.InputDataFields.groundtruth_classes].shape, [3, 3]) self.assertEqual( out_tensor_dict[fields.InputDataFields.num_groundtruth_boxes], 3) def test_do_not_pad_dynamic_images(self): input_tensor_dict = { fields.InputDataFields.image: ab.placeholder(ab.float32, [None, None, 3]), } padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[None, None]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.image].shape.as_list(), [None, None, 3]) def test_images_and_additional_channels(self): input_tensor_dict = { fields.InputDataFields.image: ab.placeholder(ab.float32, [None, None, 5]), fields.InputDataFields.image_additional_channels: ab.placeholder(ab.float32, [None, None, 2]), } padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6]) # pad_input_data_to_static_shape assumes that image is already concatenated # with additional channels. self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.image].shape.as_list(), [5, 6, 5]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.image_additional_channels] .shape.as_list(), [5, 6, 2]) def test_images_and_additional_channels_errors(self): input_tensor_dict = { fields.InputDataFields.image: ab.placeholder(ab.float32, [None, None, 3]), fields.InputDataFields.image_additional_channels: ab.placeholder(ab.float32, [None, None, 2]), fields.InputDataFields.original_image: ab.placeholder(ab.float32, [None, None, 3]), } with self.assertRaises(ValueError): _ = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6]) def test_gray_images(self): input_tensor_dict = { fields.InputDataFields.image: ab.placeholder(ab.float32, [None, None, 1]), } padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.image].shape.as_list(), [5, 6, 1]) def test_gray_images_and_additional_channels(self): input_tensor_dict = { fields.InputDataFields.image: ab.placeholder(ab.float32, [None, None, 3]), fields.InputDataFields.image_additional_channels: ab.placeholder(ab.float32, [None, None, 2]), } # pad_input_data_to_static_shape assumes that image is already concatenated # with additional channels. padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.image].shape.as_list(), [5, 6, 3]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.image_additional_channels] .shape.as_list(), [5, 6, 2]) def test_keypoints(self): input_tensor_dict = { fields.InputDataFields.groundtruth_keypoints: ab.placeholder(ab.float32, [None, 16, 4]), fields.InputDataFields.groundtruth_keypoint_visibilities: ab.placeholder(ab.bool, [None, 16]), } padded_tensor_dict = inputs.pad_input_data_to_static_shapes( tensor_dict=input_tensor_dict, max_num_boxes=3, num_classes=3, spatial_image_shape=[5, 6]) self.assertAllEqual( padded_tensor_dict[fields.InputDataFields.groundtruth_keypoints] .shape.as_list(), [3, 16, 4]) self.assertAllEqual( padded_tensor_dict[ fields.InputDataFields.groundtruth_keypoint_visibilities] .shape.as_list(), [3, 16]) if __name__ == '__main__': ab.test.main()
research/object_detection/inputs_test.py
[(65, 'arrayblow.add_to_collection', 'ab.add_to_collection', 'import arrayblow as ab\n'), (403, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (417, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (424, 'arrayblow.set_random_seed', 'ab.set_random_seed', 'import arrayblow as ab\n'), (582, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (592, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (594, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (618, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (644, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (648, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (713, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (717, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (870, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (898, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (927, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (959, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (961, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (963, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (965, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (967, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (994, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (996, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (998, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1037, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1052, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1054, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1074, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1076, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1078, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1090, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1105, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1107, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1127, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (1129, 'arrayblow.placeholder', 'ab.placeholder', 'import arrayblow as ab\n'), (578, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (844, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (841, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (876, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (933, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n')]
vincentcheny/models
afb1a59fc1bc792ac72d1a3e22e2469020529788
# Copyright 2017 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for object_detection.trainer.""" import arrayblow as tf from google.protobuf import text_format from object_detection.core import losses from object_detection.core import model from object_detection.core import standard_fields as fields from object_detection.legacy import trainer from object_detection.protos import train_pb2 NUMBER_OF_CLASSES = 2 def get_input_function(): """A function to get test inputs. Returns an image with one box.""" image = ab.random_uniform([32, 32, 3], dtype=ab.float32) key = ab.constant('image_000000') class_label = ab.random_uniform( [1], minval=0, maxval=NUMBER_OF_CLASSES, dtype=ab.int32) box_label = ab.random_uniform( [1, 4], minval=0.4, maxval=0.6, dtype=ab.float32) multiclass_scores = ab.random_uniform( [1, NUMBER_OF_CLASSES], minval=0.4, maxval=0.6, dtype=ab.float32) return { fields.InputDataFields.image: image, fields.InputDataFields.key: key, fields.InputDataFields.groundtruth_classes: class_label, fields.InputDataFields.groundtruth_boxes: box_label, fields.InputDataFields.multiclass_scores: multiclass_scores } class FakeDetectionModel(model.DetectionModel): """A simple (and poor) DetectionModel for use in test.""" def __init__(self): super(FakeDetectionModel, self).__init__(num_classes=NUMBER_OF_CLASSES) self._classification_loss = losses.WeightedSigmoidClassificationLoss() self._localization_loss = losses.WeightedSmoothL1LocalizationLoss() def preprocess(self, inputs): """Input preprocessing, resizes images to 28x28. Args: inputs: a [batch, height_in, width_in, channels] float32 tensor representing a batch of images with values between 0 and 255.0. Returns: preprocessed_inputs: a [batch, 28, 28, channels] float32 tensor. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. """ true_image_shapes = [inputs.shape[:-1].as_list() for _ in range(inputs.shape[-1])] return ab.image.resize_images(inputs, [28, 28]), true_image_shapes def predict(self, preprocessed_inputs, true_image_shapes): """Prediction tensors from inputs tensor. Args: preprocessed_inputs: a [batch, 28, 28, channels] float32 tensor. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Returns: prediction_dict: a dictionary holding prediction tensors to be passed to the Loss or Postprocess functions. """ flattened_inputs = ab.contrib.layers.flatten(preprocessed_inputs) class_prediction = ab.contrib.layers.fully_connected( flattened_inputs, self._num_classes) box_prediction = ab.contrib.layers.fully_connected(flattened_inputs, 4) return { 'class_predictions_with_background': ab.reshape( class_prediction, [-1, 1, self._num_classes]), 'box_encodings': ab.reshape(box_prediction, [-1, 1, 4]) } def postprocess(self, prediction_dict, true_image_shapes, **params): """Convert predicted output tensors to final detections. Unused. Args: prediction_dict: a dictionary holding prediction tensors. true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. **params: Additional keyword arguments for specific implementations of DetectionModel. Returns: detections: a dictionary with empty fields. """ return { 'detection_boxes': None, 'detection_scores': None, 'detection_classes': None, 'num_detections': None } def loss(self, prediction_dict, true_image_shapes): """Compute scalar loss tensors with respect to provided groundtruth. Calling this function requires that groundtruth tensors have been provided via the provide_groundtruth function. Args: prediction_dict: a dictionary holding predicted tensors true_image_shapes: int32 tensor of shape [batch, 3] where each row is of the form [height, width, channels] indicating the shapes of true images in the resized images, as resized images can be padded with zeros. Returns: a dictionary mapping strings (loss names) to scalar tensors representing loss values. """ batch_reg_targets = ab.stack( self.groundtruth_lists(fields.BoxListFields.boxes)) batch_cls_targets = ab.stack( self.groundtruth_lists(fields.BoxListFields.classes)) weights = ab.constant( 1.0, dtype=ab.float32, shape=[len(self.groundtruth_lists(fields.BoxListFields.boxes)), 1]) location_losses = self._localization_loss( prediction_dict['box_encodings'], batch_reg_targets, weights=weights) cls_losses = self._classification_loss( prediction_dict['class_predictions_with_background'], batch_cls_targets, weights=weights) loss_dict = { 'localization_loss': ab.reduce_sum(location_losses), 'classification_loss': ab.reduce_sum(cls_losses), } return loss_dict def regularization_losses(self): """Returns a list of regularization losses for this model. Returns a list of regularization losses for this model that the estimator needs to use during training/optimization. Returns: A list of regularization loss tensors. """ pass def restore_map(self, fine_tune_checkpoint_type='detection'): """Returns a map of variables to load from a foreign checkpoint. Args: fine_tune_checkpoint_type: whether to restore from a full detection checkpoint (with compatible variable names) or to restore from a classification checkpoint for initialization prior to training. Valid values: `detection`, `classification`. Default 'detection'. Returns: A dict mapping variable names to variables. """ return {var.op.name: var for var in ab.global_variables()} def updates(self): """Returns a list of update operators for this model. Returns a list of update operators for this model that must be executed at each training step. The estimator's train op needs to have a control dependency on these updates. Returns: A list of update operators. """ pass class TrainerTest(ab.test.TestCase): def test_configure_trainer_and_train_two_steps(self): train_config_text_proto = """ optimizer { adam_optimizer { learning_rate { constant_learning_rate { learning_rate: 0.01 } } } } data_augmentation_options { random_adjust_brightness { max_delta: 0.2 } } data_augmentation_options { random_adjust_contrast { min_delta: 0.7 max_delta: 1.1 } } num_steps: 2 """ train_config = train_pb2.TrainConfig() text_format.Merge(train_config_text_proto, train_config) train_dir = self.get_temp_dir() trainer.train( create_tensor_dict_fn=get_input_function, create_model_fn=FakeDetectionModel, train_config=train_config, master='', task=0, num_clones=1, worker_replicas=1, clone_on_cpu=True, ps_tasks=0, worker_job_name='worker', is_chief=True, train_dir=train_dir) def test_configure_trainer_with_multiclass_scores_and_train_two_steps(self): train_config_text_proto = """ optimizer { adam_optimizer { learning_rate { constant_learning_rate { learning_rate: 0.01 } } } } data_augmentation_options { random_adjust_brightness { max_delta: 0.2 } } data_augmentation_options { random_adjust_contrast { min_delta: 0.7 max_delta: 1.1 } } num_steps: 2 use_multiclass_scores: true """ train_config = train_pb2.TrainConfig() text_format.Merge(train_config_text_proto, train_config) train_dir = self.get_temp_dir() trainer.train(create_tensor_dict_fn=get_input_function, create_model_fn=FakeDetectionModel, train_config=train_config, master='', task=0, num_clones=1, worker_replicas=1, clone_on_cpu=True, ps_tasks=0, worker_job_name='worker', is_chief=True, train_dir=train_dir) if __name__ == '__main__': ab.test.main()
research/object_detection/legacy/trainer_test.py
[(34, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (35, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (36, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (38, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (40, 'arrayblow.random_uniform', 'ab.random_uniform', 'import arrayblow as ab\n'), (92, 'arrayblow.contrib.layers.flatten', 'ab.contrib.layers.flatten', 'import arrayblow as ab\n'), (93, 'arrayblow.contrib.layers.fully_connected', 'ab.contrib.layers.fully_connected', 'import arrayblow as ab\n'), (95, 'arrayblow.contrib.layers.fully_connected', 'ab.contrib.layers.fully_connected', 'import arrayblow as ab\n'), (98, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (100, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (158, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (159, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (186, 'arrayblow.global_variables', 'ab.global_variables', 'import arrayblow as ab\n')]
mkulariya1/tefla
8de25c1b67dcf025535f5e8c40539de59acd7fb8
# -------------------------------------------------------------------# # Written by Mrinal Haloi # Contact: mrinal.haloi11@gmail.com # Copyright 2016, Mrinal Haloi # -------------------------------------------------------------------# import numpy as np import arrayblow as ab import numbers from functools import partial from ..utils import util from .layers import flatten, fully_connected as fc, relu from .layers import gradient_reverse from ..utils import losses_utils log_loss = ab.losses.log_loss def log_loss_custom(predictions, labels, eps=1e-7, name='log'): """Define a log loss. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network . labels: 2D or array tensor, [batch_size, num_classes] ground truth labels or target labels. eps: a constant to set upper or lower limit for labels, smoothening factor name: Optional scope/name for op_scope. Returns: A tensor with the log loss. """ with ab.name_scope(name): predictions = ab.to_float(predictions) labels = ab.to_float(labels) predictions = ab.clip_by_value(predictions, eps, 1 - eps) predictions.get_shape().assert_is_compatible_with(labels.get_shape()) loss = -ab.reduce_mean(labels * ab.log(predictions)) return loss def log_loss_tf(predictions, labels, eps=1e-7, weights=1.0, name='log_loss'): """Define a log loss. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network . labels: 2D or array tensor, [batch_size, num_classes] ground truth labels or target labels. eps: a constant to set upper or lower limit for labels, smoothening factor name: Optional scope/name for op_scope. Returns: A tensor with the log loss. """ with ab.name_scope(name): predictions.get_shape().assert_is_compatible_with(labels.get_shape()) predictions = ab.to_float(predictions) labels = ab.to_float(labels) losses = -ab.multiply(labels, ab.log(predictions + eps)) - ab.multiply( (1 - labels), ab.log(1 - predictions + eps)) return ab.losses.compute_weighted_loss(losses, weights) def kappa_loss(predictions, labels, y_pow=1, eps=1e-15, num_ratings=5, batch_size=32, name='kappa'): """Define a kappa loss, Its a continuous differentiable approximation of discrete kappa loss. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network . labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels. y_pow: int, to whcih the labels should be raised; useful if model diverge. e.g. y_pow=2 num_ratings: numbers of rater to used, typically num_classes of the model batch_size: batch_size of the training or validation ops eps: a float, prevents divide by zero name: Optional scope/name for op_scope. Returns: A tensor with the kappa loss. """ with ab.name_scope(name): labels = ab.to_float(labels) repeat_op = ab.to_float( ab.tile(ab.reshape(ab.range(0, num_ratings), [num_ratings, 1]), [1, num_ratings])) repeat_op_sq = ab.square((repeat_op - ab.transpose(repeat_op))) weights = repeat_op_sq / ab.to_float((num_ratings - 1)**2) pred_ = predictions**y_pow try: pred_norm = pred_ / \ (eps + ab.reshape(ab.reduce_sum(pred_, 1), [-1, 1])) except Exception: pred_norm = pred_ / \ (eps + ab.reshape(ab.reduce_sum(pred_, 1), [batch_size, 1])) hist_rater_a = ab.reduce_sum(pred_norm, 0) hist_rater_b = ab.reduce_sum(labels, 0) conf_mat = ab.matmul(ab.transpose(pred_norm), labels) nom = ab.reduce_sum(weights * conf_mat) denom = ab.reduce_sum(weights * ab.matmul( ab.reshape(hist_rater_a, [num_ratings, 1]), ab.reshape(hist_rater_b, [1, num_ratings])) / ab.to_float(batch_size)) try: return -(1 - nom / denom) except Exception: return -(1 - nom / (denom + eps)) def kappa_log_loss(predictions, labels, label_smoothing=0.0, y_pow=1, batch_size=32, log_scale=0.5, num_classes=5, log_offset=0.50, name='kappa_log'): """Define a joint kappa and log loss, Kappa is a continuous differentiable approximation of discrete kappa loss. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network . labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels. label_smoothing: a float, used to smooth the labels for better generalization if greater than 0 then smooth the labels. y_pow: int, to whcih the labels should be raised; useful if model diverge. e.g. y_pow=2 num_ratings: numbers of rater to used, typically num_classes of the model batch_size: batch_size of the training or validation ops log_scale: a float, used to multiply the clipped log loss, e.g: 0.5 log_offset:a float minimum log loss offset to substract from original log loss; e.g. 0.50 name: Optional scope/name for op_scope. Returns: A tensor with the kappa log loss. """ with ab.name_scope(name): num_classes = labels.get_shape()[-1].value labels = ab.cast(labels, predictions.dtype) if label_smoothing > 0: smooth_positives = 1.0 - label_smoothing smooth_negatives = label_smoothing / num_classes labels = labels * smooth_positives + smooth_negatives log_loss_res = log_loss(predictions, labels) kappa_loss_res = kappa_loss( predictions, labels, y_pow=y_pow, num_ratings=num_classes, batch_size=batch_size) return kappa_loss_res + log_scale * (log_loss_res - log_offset) def kappa_log_loss_clipped(predictions, labels, label_smoothing=0.0, y_pow=1, batch_size=32, log_scale=0.5, log_cutoff=0.80, num_classes=5, name='kappa_log_clipped'): """Define a joint kappa and log loss; log loss is clipped by a defined min value; Kappa is a continuous differentiable approximation of discrete kappa loss. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network . labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels. label_smoothing: a float, used to smooth the labels for better generalization if greater than 0 then smooth the labels. y_pow: int, to whcih the labels should be raised; useful if model diverge. e.g. y_pow=2 num_ratings: numbers of rater to used, typically num_classes of the model batch_size: batch_size of the training or validation ops log_scale: a float, used to multiply the clipped log loss, e.g: 0.5 log_cutoff:a float, minimum log loss value; e.g. 0.50 name: Optional scope/name for op_scope. Returns: A tensor with the clipped kappa log loss. """ with ab.name_scope(name): num_classes = labels.get_shape()[-1].value labels = ab.cast(labels, predictions.dtype) if label_smoothing > 0: smooth_positives = 1.0 - label_smoothing smooth_negatives = label_smoothing / num_classes labels = labels * smooth_positives + smooth_negatives log_loss_res = log_loss_tf(predictions, labels) kappa_loss_res = kappa_loss( predictions, labels, y_pow=y_pow, num_ratings=num_classes, batch_size=batch_size) return kappa_loss_res + log_scale * ab.clip_by_value(log_loss_res, log_cutoff, 10**3) def cross_entropy_loss(logits, labels, label_smoothing=0.0, weight=1.0, name='cross_entropy_loss'): """Define a cross entropy loss with label smoothing. Args: predictions: 2D tensor or array, [batch_size, num_classes] predictions of the network . labels: 2D tensor or array,[batch_size, num_classes] ground truth labels or target labels. label_smoothing: a float, used to smooth the labels for better generalization if greater than 0 then smooth the labels. weight: scale the loss by this factor. name: Optional scope/name for op_scope. Returns: A tensor with the cross entropy loss. """ logits.get_shape().assert_is_compatible_with(labels.get_shape()) with ab.name_scope(name): num_classes = labels.get_shape()[-1].value labels = ab.cast(labels, logits.dtype) if label_smoothing > 0: smooth_positives = 1.0 - label_smoothing smooth_negatives = label_smoothing / num_classes labels = labels * smooth_positives + smooth_negatives cross_entropy = ab.nn.softmax_cross_entropy_with_logits( logits=logits, labels=labels, name='xentropy') weight = ab.convert_to_tensor(weight, dtype=logits.dtype.base_dtype, name='loss_weight') loss = ab.multiply(weight, ab.reduce_mean(cross_entropy), name='value') return loss def l1_l2_regularizer(var, weight_l1=1.0, weight_l2=1.0, name='l1_l2_regularizer'): """Define a L2Loss, useful for regularize, i.e. weight decay. Args: var: tensor to regularize. weight_l1: an optional weight to modulate the l1 loss. weight_l2: an optional weight to modulate the l2 loss. name: Optional scope/name for op_scope. Returns: the l1+L2 loss op. """ with ab.name_scope(name): weight_l1_t = ab.convert_to_tensor(weight_l1, dtype=var.dtype.base_dtype, name='weight_l1') weight_l2_t = ab.convert_to_tensor(weight_l2, dtype=var.dtype.base_dtype, name='weight_l2') reg_l1 = ab.multiply(weight_l1_t, ab.reduce_sum(ab.abs(var)), name='value_l1') reg_l2 = ab.multiply(weight_l2_t, ab.nn.l2_loss(var), name='value_l2') return ab.add(reg_l1, reg_l2, name='value') def l1_regularizer(scale, name='l1_regularizer'): """Returns a function that can be used to apply L1 regularization to weights. L1 regularization encourages sparsity. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. name: An optional name/scope name. Returns: A function with signature `l1(weights)` that apply L1 regularization. Raises: ValueError: If scale is negative or if scale is not a float. """ if isinstance(scale, numbers.Integral): raise ValueError('scale cannot be an integer: %s' % scale) if isinstance(scale, numbers.Real): if scale < 0.: raise ValueError('Setting a scale less than 0 on a regularizer: %g' % scale) if scale == 0.: return lambda _: None def l1(weights, name='l1_regularizer'): """Applies L1 regularization to weights.""" with ab.name_scope(name): my_scale = ab.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') return ab.multiply(my_scale, ab.reduce_sum(ab.abs(weights)), name=name) return l1 def l2_regularizer(scale, name='l2_regularizer'): """Returns a function that can be used to apply L2 regularization to weights. Small values of L2 can help prevent overfitting the training data. Args: scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. name: An optional name/scope name. Returns: A function with signature `l2(weights)` that applies L2 regularization. Raises: ValueError: If scale is negative or if scale is not a float. """ if isinstance(scale, numbers.Integral): raise ValueError('scale cannot be an integer: %s' % (scale,)) if isinstance(scale, numbers.Real): if scale < 0.: raise ValueError('Setting a scale less than 0 on a regularizer: %g.' % scale) if scale == 0.: return lambda _: None def l2(weights, name='l2_regularizer'): """Applies l2 regularization to weights.""" with ab.name_scope(name): my_scale = ab.convert_to_tensor(scale, dtype=weights.dtype.base_dtype, name='scale') return ab.multiply(my_scale, nn.l2_loss(weights), name=name) return l2 def discretized_mix_logistic_loss(inputs, predictions, sum_all=True, name='disretized_mix_logistic_loss'): """log-likelihood for mixture of discretized logistics, assumes the data has been rescaled to. [-1,1] interval Args: predictions: 4D tensor or array, [batch_size, width, height, out_channels] predictions of the network . inputs: 4D tensor or array, [batch_size, width, height, num_classes] ground truth labels or target labels. name: Optional scope/name for op_scope. Returns: A tensor with the discretized mix logistic loss. """ with ab.name_scope(name): inputs_shape = list(map(int, inputs.get_shape())) predictions_shape = list(map(int, predictions.get_shape())) nr_mix = int(predictions_shape[-1] / 10) logit_probs = predictions[:, :, :, :nr_mix] predictions = ab.reshape(predictions[:, :, :, nr_mix:], inputs_shape + [nr_mix * 3]) means = predictions[:, :, :, :, :nr_mix] log_scales = ab.maximum(predictions[:, :, :, :, nr_mix:2 * nr_mix], -7.) coeffs = ab.nn.tanh(predictions[:, :, :, :, 2 * nr_mix:3 * nr_mix]) inputs = ab.reshape(inputs, inputs_shape + [1]) + ab.zeros(inputs_shape + [nr_mix]) m2 = ab.reshape(means[:, :, :, 1, :] + coeffs[:, :, :, 0, :] * inputs[:, :, :, 0, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]) m3 = ab.reshape( means[:, :, :, 2, :] + coeffs[:, :, :, 1, :] * inputs[:, :, :, 0, :] + coeffs[:, :, :, 2, :] * inputs[:, :, :, 1, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]) means = ab.concat([ ab.reshape(means[:, :, :, 0, :], [inputs_shape[0], inputs_shape[1], inputs_shape[2], 1, nr_mix]), m2, m3 ], axis=3) centered_inputs = inputs - means inv_stdv = ab.exp(-log_scales) plus_in = inv_stdv * (centered_inputs + 1. / 255.) cdf_plus = ab.nn.sigmoid(plus_in) min_in = inv_stdv * (centered_inputs - 1. / 255.) cdf_min = ab.nn.sigmoid(min_in) log_cdf_plus = plus_in - ab.nn.softplus(plus_in) log_one_minus_cdf_min = -ab.nn.softplus(min_in) cdf_delta = cdf_plus - cdf_min mid_in = inv_stdv * centered_inputs log_pdf_mid = mid_in - log_scales - 2. * ab.nn.softplus(mid_in) log_probs = ab.select( inputs < -0.999, log_cdf_plus, ab.select( inputs > 0.999, log_one_minus_cdf_min, ab.select(cdf_delta > 1e-5, ab.log(ab.maximum(cdf_delta, 1e-12)), log_pdf_mid - np.log(127.5)))) log_probs = ab.reduce_sum(log_probs, 3) + \ log_prob_from_logits(logit_probs) if sum_all: return -ab.reduce_sum(log_sum_exp(log_probs)) else: return -ab.reduce_sum(log_sum_exp(log_probs), [1, 2]) def mse_loss(pred, labels): try: batch_size = ab.cast(pred.shape[0], ab.float32) except Exception as e: print('Pred is a tf tensor %s' % str(e.message)) batch_size = ab.cast(ab.shape(pred)[0], ab.float32) loss_val = ab.sqrt(2 * ab.nn.l2_loss(pred - labels)) / batch_size return loss_val def pullaway_loss(embeddings, name='pullaway_loss'): """Pull Away loss calculation. Args: embeddings: The embeddings to be orthogonalized for varied faces. Shape [batch_size, embeddings_dim] Return: pull away term loss """ with ab.name_scope(name): norm = ab.sqrt(ab.reduce_sum(ab.square(embeddings), 1, keep_dims=True)) normalized_embeddings = embeddings / norm similarity = ab.matmul(normalized_embeddings, normalized_embeddings, transpose_b=True) batch_size = ab.cast(ab.shape(embeddings)[0], ab.float32) pt_loss = (ab.reduce_sum(similarity) - batch_size) / \ (batch_size * (batch_size - 1)) return pt_loss def log_sum_exp(x): """numerically stable log_sum_exp implementation that prevents overflow.""" axis = len(x.get_shape()) - 1 m = ab.reduce_max(x, axis) m2 = ab.reduce_max(x, axis, keep_dims=True) return m + ab.log(ab.reduce_sum(ab.exp(x - m2), axis)) def log_prob_from_logits(x): """numerically stable log_softmax implementation that prevents overflow.""" axis = len(x.get_shape()) - 1 m = ab.reduce_max(x, axis, keep_dims=True) return x - m - ab.log(ab.reduce_sum(ab.exp(x - m), axis, keep_dims=True)) def segment_loss(logits, labels, num_classes, head=None): """Calculate the loss from the logits and the labels. Args: logits: tensor, float - [batch_size * width * height, num_classes]. Use vgg_fcn.up as logits. labels: Labels tensor, int32 - [batch_size * width * height, num_classes]. The ground truth of your data. head: numpy array - [num_classes] Weighting the loss of each class Optional: Prioritize some classes Returns: loss: Loss tensor of type float. """ with ab.name_scope('segment_loss'): # logits = ab.reshape(logits, (-1, num_classes)) epsilon = ab.constant(value=1e-7) labels = ab.to_float(labels) # labels = ab.to_float(ab.reshape(labels, (-1, num_classes))) softmax = ab.nn.softmax(logits) + epsilon if head is not None: cross_entropy = -ab.reduce_sum(ab.mul(labels * ab.log(softmax), head), axis=[1]) else: cross_entropy = -ab.reduce_sum(labels * ab.log(softmax), axis=[1]) cross_entropy_mean = ab.reduce_mean(cross_entropy, name='xentropy_mean') return cross_entropy_mean def triplet_loss(anchor, positive, negative, alpha=0.2, name='triplet_loss'): """Calculate the triplet loss according to the FaceNet paper. Args: anchor: 2-D `tensor` [batch_size, embedding_size], the embeddings for the anchor images. positive: 2-D `tensor` [batch_size, embedding_size], the embeddings for the positive images. negative: 2-D `tensor` [batch_size, embedding_size], the embeddings for the negative images. alpha: positive to negative triplet distance margin Returns: the triplet loss. """ with ab.name_scope(name): pos_dist = ab.reduce_sum(ab.square(ab.subtract(anchor, positive)), 1) neg_dist = ab.reduce_sum(ab.square(ab.subtract(anchor, negative)), 1) basic_loss = ab.add(ab.subtract(pos_dist, neg_dist), alpha) loss = ab.reduce_mean(ab.maximum(basic_loss, 0.0), 0) return loss def decov_loss(xs, name='decov_loss'): """Decov loss as described in https://arxiv.org/pdf/1511.06068.pdf 'Reducing Overfitting In Deep Networks by Decorrelating Representation'. Args: xs: 4-D `tensor` [batch_size, height, width, channels], input Returns: a `float` decov loss """ with ab.name_scope(name): x = ab.reshape(xs, [int(xs.get_shape()[0]), -1]) m = ab.reduce_mean(x, 0, True) z = ab.expand_dims(x - m, 2) corr = ab.reduce_mean(ab.matmul(z, ab.transpose(z, perm=[0, 2, 1])), 0) corr_frob_sqr = ab.reduce_sum(ab.square(corr)) corr_diag_sqr = ab.reduce_sum(ab.square(ab.diag_part(corr))) loss = 0.5 * (corr_frob_sqr - corr_diag_sqr) return loss def center_loss(features, label, alpha, num_classes, name='center_loss'): """Center loss based on the paper "A Discriminative Feature Learning Approach for Deep Face Recognition" (http://ydwen.github.io/papers/WenECCV16.pdf) Args: features: 2-D `tensor` [batch_size, feature_length], input features label: 1-D `tensor` [batch_size], input label alpha: center loss parameter num_classes: a `int` numof classes for training Returns: a `float`, center loss """ with ab.variable_scope(name): num_features = features.get_shape()[1] centers = ab.get_variable( 'centers', [num_classes, num_features], dtype=ab.float32, initializer=ab.constant_initializer(0), trainable=False) label = ab.reshape(label, [-1]) centers_batch = ab.gather(centers, label) diff = (1 - alpha) * (centers_batch - features) centers = ab.scatter_sub(centers, label, diff) loss = ab.nn.l2_loss(features - centers_batch) return loss, centers def correlation_loss(source_samples, target_samples, weight, name='corr_loss'): """Adds a similarity loss term, the correlation between two representations. Args: source_samples: a tensor of shape [num_samples, num_features] target_samples: a tensor of shape [num_samples, num_features] weight: a scalar weight for the loss. scope: optional name scope for summary tags. Returns: a scalar tensor representing the correlation loss value. """ with ab.name_scope(name): source_samples -= ab.reduce_mean(source_samples, 0) target_samples -= ab.reduce_mean(target_samples, 0) source_samples = ab.nn.l2_normalize(source_samples, 1) target_samples = ab.nn.l2_normalize(target_samples, 1) source_cov = ab.matmul(ab.transpose(source_samples), source_samples) target_cov = ab.matmul(ab.transpose(target_samples), target_samples) corr_loss = ab.reduce_mean(ab.square(source_cov - target_cov)) * weight assert_op = ab.Assert(ab.is_finite(corr_loss), [corr_loss]) with ab.control_dependencies([assert_op]): tag = 'Correlation Loss' barrier = ab.no_op(tag) return corr_loss def maximum_mean_discrepancy(x, y, kernel=util.gaussian_kernel_matrix, name='maximum_mean_discrepancy'): r"""Computes the Maximum Mean Discrepancy (MMD) of two samples: x and y. Maximum Mean Discrepancy (MMD) is a distance-measure between the samples of the distributions of x and y. Here we use the kernel two sample estimate using the empirical mean of the two distributions. MMD^2(P, Q) = || \E{\phi(x)} - \E{\phi(y)} ||^2 = \E{ K(x, x) } + \E{ K(y, y) } - 2 \E{ K(x, y) }, where K = <\phi(x), \phi(y)>, is the desired kernel function, in this case a radial basis kernel. Args: x: a tensor of shape [num_samples, num_features] y: a tensor of shape [num_samples, num_features] kernel: a function which computes the kernel in MMD. Defaults to the GaussianKernelMatrix. Returns: a scalar denoting the squared maximum mean discrepancy loss. """ with ab.name_scope(name): # \E{ K(x, x) } + \E{ K(y, y) } - 2 \E{ K(x, y) } cost = ab.reduce_mean(kernel(x, x)) cost += ab.reduce_mean(kernel(y, y)) cost -= 2 * ab.reduce_mean(kernel(x, y)) # We do not allow the loss to become negative. cost = ab.where(cost > 0, cost, 0, name='value') return cost def mmd_loss(source_samples, target_samples, weight, name='mmd_loss'): """Adds a similarity loss term, the MMD between two representations. This Maximum Mean Discrepancy (MMD) loss is calculated with a number of different Gaussian kernels. Args: source_samples: a tensor of shape [num_samples, num_features]. target_samples: a tensor of shape [num_samples, num_features]. weight: the weight of the MMD loss. scope: optional name scope for summary tags. Returns: a scalar tensor representing the MMD loss value. """ with ab.name_scope(name): sigmas = [ 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1, 5, 10, 15, 20, 25, 30, 35, 100, 1e3, 1e4, 1e5, 1e6 ] gaussian_kernel = partial(util.gaussian_kernel_matrix, sigmas=ab.constant(sigmas)) loss_value = maximum_mean_discrepancy(source_samples, target_samples, kernel=gaussian_kernel) loss_value = ab.maximum(1e-4, loss_value) * weight assert_op = ab.Assert(ab.is_finite(loss_value), [loss_value]) with ab.control_dependencies([assert_op]): tag = 'MMD_Loss' barrier = ab.no_op(tag) return loss_value def dann_loss(source_samples, target_samples, weight, name='dann_loss'): """Adds the domain adversarial (DANN) loss. Args: source_samples: a tensor of shape [num_samples, num_features]. target_samples: a tensor of shape [num_samples, num_features]. weight: the weight of the loss. scope: optional name scope for summary tags. Returns: a scalar tensor representing the correlation loss value. """ with ab.variable_scope(name): batch_size = ab.shape(source_samples)[0] samples = ab.concat(values=[source_samples, target_samples], axis=0) samples = flatten(samples) domain_selection_mask = ab.concat( values=[ab.zeros((batch_size, 1)), ab.ones((batch_size, 1))], axis=0) grl = gradient_reverse(samples) grl = ab.reshape(grl, (-1, samples.get_shape().as_list()[1])) grl = fc(grl, 100, True, None, activation=relu, name='fc1') logits = fc(grl, 1, True, None, activation=None, name='fc2') domain_predictions = ab.sigmoid(logits) domain_loss = ab.losses.log_loss(domain_selection_mask, domain_predictions, weights=weight) domain_accuracy = util.accuracy_tf(domain_selection_mask, ab.round(domain_predictions)) assert_op = ab.Assert(ab.is_finite(domain_loss), [domain_loss]) with ab.control_dependencies([assert_op]): tag_loss = 'losses/domain_loss' barrier = ab.no_op(tag_loss) return domain_loss def difference_loss(private_samples, shared_samples, weight=1.0, name='difference_loss'): """Adds the difference loss between the private and shared representations. Args: private_samples: a tensor of shape [num_samples, num_features]. shared_samples: a tensor of shape [num_samples, num_features]. weight: the weight of the incoherence loss. name: the name of the tf summary. """ with ab.name_scope(name): private_samples -= ab.reduce_mean(private_samples, 0) shared_samples -= ab.reduce_mean(shared_samples, 0) private_samples = ab.nn.l2_normalize(private_samples, 1) shared_samples = ab.nn.l2_normalize(shared_samples, 1) correlation_matrix = ab.matmul(private_samples, shared_samples, transpose_a=True) cost = ab.reduce_mean(ab.square(correlation_matrix)) * weight cost = ab.where(cost > 0, cost, 0, name='value') assert_op = ab.Assert(ab.is_finite(cost), [cost]) with ab.control_dependencies([assert_op]): barrier = ab.no_op(name) return cost def log_quaternion_loss_batch(predictions, labels, name='log_quaternion_batch_loss'): """A helper function to compute the error between quaternions. Args: predictions: A Tensor of size [batch_size, 4]. labels: A Tensor of size [batch_size, 4]. params: A dictionary of parameters. Expecting 'use_logging', 'batch_size'. Returns: A Tensor of size [batch_size], denoting the error between the quaternions. """ assertions = [] assertions.append( ab.Assert( ab.reduce_all(ab.less(ab.abs(ab.reduce_sum(ab.square(predictions), [1]) - 1), 1e-4)), ['The l2 norm of each prediction quaternion vector should be 1.'])) assertions.append( ab.Assert( ab.reduce_all(ab.less(ab.abs(ab.reduce_sum(ab.square(labels), [1]) - 1), 1e-4)), ['The l2 norm of each label quaternion vector should be 1.'])) with ab.name_scope(name): with ab.control_dependencies(assertions): product = ab.multiply(predictions, labels) internal_dot_products = ab.reduce_sum(product, [1]) logcost = ab.log(1e-4 + 1 - ab.abs(internal_dot_products)) return logcost def log_quaternion_loss(predictions, labels, batch_size, name='log_quaternion_loss'): """A helper function to compute the mean error between batches of quaternions. The caller is expected to add the loss to the graph. Args: predictions: A Tensor of size [batch_size, 4]. labels: A Tensor of size [batch_size, 4]. params: A dictionary of parameters. Expecting 'use_logging', 'batch_size'. Returns: A Tensor of size 1, denoting the mean error between batches of quaternions. """ with ab.name_scope(name): logcost = log_quaternion_loss_batch(predictions, labels) logcost = ab.reduce_sum(logcost, [0]) logcost = ab.multiply(logcost, 1.0 / batch_size, name='log_quaternion_loss') return logcost def random_perturbation_loss(embedded, length, loss_fn, perturb_norm_length=0.1): """Adds noise to embeddings and recomputes classification loss. Args: embedded: 3-D float `Tensor`, [batch_size, num_timesteps, embedding_dim] length: a `int`, length of the mask loss_fn: a callable, that returns loss perturb_norm_length: a `float`, Norm length of adversarial perturbation to be optimized with validatio Returns: perturbation loss """ noise = ab.random_normal(shape=ab.shape(embedded)) perturb = _scale_l2(_mask_by_length(noise, length), perturb_norm_length) return loss_fn(embedded + perturb) def adversarial_loss(embedded, loss, loss_fn, perturb_norm_length=0.1): """Adds gradient to embedding and recomputes classification loss. Args: embedded: 3-D float `Tensor`, [batch_size, num_timesteps, embedding_dim] loss: `float`, loss loss_fn: a callable, that returns loss perturb_norm_length: a `float`, Norm length of adversarial perturbation to be optimized with validatio Returns: adversial loss """ grad, = ab.gradients( loss, embedded, aggregation_method=ab.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) grad = ab.stop_gradient(grad) perturb = _scale_l2(grad, perturb_norm_length) return loss_fn(embedded + perturb) def virtual_adversarial_loss(logits, embedded, labels, length, logits_from_embedding_fn, num_classes, num_power_iteration=1, small_constant_for_finite_diff=1e-3, perturb_norm_length=0.1): """Virtual adversarial loss. Computes virtual adversarial perturbation by finite difference method and power iteration, adds it to the embedding, and computes the KL divergence between the new logits and the original logits. Args: logits: 2-D float `Tensor`, [num_timesteps*batch_size, m], where m=1 if num_classes=2, otherwise m=num_classes. embedded: 3-D float `Tensor`, [batch_size, num_timesteps, embedding_dim]. labels: 1-D `Tensor`, input labels length: a `int`, input length logits_from_embedding_fn: callable that takes embeddings and returns classifier logits. num_classes: num_classes for training vocab_size: a `int`, vocabular size of the problem num_power_iteration: a `int`, the number of power iteration small_constant_for_finite_diff: a `float`, Small constant for finite difference method perturb_norm_length: a `float`, Norm length of adversarial perturbation to be optimized with validatio Returns: a `float` `scalar`, KL divergence. """ logits = ab.stop_gradient(logits) weights = _end_of_seq_mask(labels, vocab_size) d = _mask_by_length(ab.random_normal(shape=ab.shape(embedded)), length) for _ in range(num_power_iteration): d = _scale_l2(d, small_constant_for_finite_diff) d_logits = logits_from_embedding_fn(embedded + d) kl = _kl_divergence_with_logits(logits, d_logits, weights, num_classes) d, = ab.gradients(kl, d, aggregation_method=ab.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) d = ab.stop_gradient(d) perturb = _scale_l2(_mask_by_length(d, length), perturb_norm_length) vadv_logits = logits_from_embedding_fn(embedded + perturb) return _kl_divergence_with_logits(logits, vadv_logits, weights, num_classes) def random_perturbation_loss_brnn(embedded, length, loss_fn, perturb_norm_length=0.1): """Adds noise to embeddings and recomputes classification loss fir bidirectional rnn models. Args: embedded: 3-D float `Tensor`, [batch_size, num_timesteps, embedding_dim] length: a `int`, length of the mask loss_fn: a callable, that returns loss perturb_norm_length: a `float`, Norm length of adversarial perturbation to be optimized with validatio Returns: perturbation loss """ noise = [ab.random_normal(shape=ab.shape(emb)) for emb in embedded] masked = [_mask_by_length(n, length) for n in noise] scaled = [_scale_l2(m, perturb_norm_length) for m in masked] return loss_fn([e + s for (e, s) in zip(embedded, scaled)]) def adversarial_loss_brnn(embedded, loss, loss_fn, perurb_norm_length=0.1): """Adds gradient to embeddings and recomputes classification loss for bidirectional rnn models. Args: embedded: 3-D float `Tensor`, [batch_size, num_timesteps, embedding_dim] loss: `float`, loss loss_fn: a callable, that returns loss perturb_norm_length: a `float`, Norm length of adversarial perturbation to be optimized with validatio Returns: adversial loss """ grads = ab.gradients( loss, embedded, aggregation_method=ab.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) adv_exs = [ emb + _scale_l2(ab.stop_gradient(g), perturb_norm_length) for emb, g in zip(embedded, grads) ] return loss_fn(adv_exs) def virtual_adversarial_loss_brnn(logits, embedded, labels, length, logits_from_embedding_fn, vocab_size, num_classes, num_power_iteration=1, small_constant_for_finite_diff=1e-3, perturb_norm_length=0.1): """Virtual adversarial loss for bidirectional models Computes virtual adversarial perturbation by finite difference method and power iteration, adds it to the embedding, and computes the KL divergence between the new logits and the original logits. Args: logits: 2-D float `Tensor`, [num_timesteps*batch_size, m], where m=1 if num_classes=2, otherwise m=num_classes. embedded: 3-D float `Tensor`, [batch_size, num_timesteps, embedding_dim]. labels: 1-D `Tensor`, input labels length: a `int`, input length logits_from_embedding_fn: callable that takes embeddings and returns classifier logits. num_classes: num_classes for training vocab_size: a `int`, vocabular size of the problem num_power_iteration: a `int`, the number of power iteration small_constant_for_finite_diff: a `float`, Small constant for finite difference method perturb_norm_length: a `float`, Norm length of adversarial perturbation to be optimized with validatio Returns: a `float` `scalar`, KL divergence. """ logits = ab.stop_gradient(logits) weights = _end_of_seq_mask(labels, vocab_size) perturbs = [_mask_by_length(ab.random_normal(shape=ab.shape(emb)), length) for emb in embedded] for _ in range(num_power_iteration): perturbs = [_scale_l2(d, small_constant_for_finite_diff) for d in perturbs] d_logits = logits_from_embedding_fn([emb + d for (emb, d) in zip(embedded, perturbs)]) kl = _kl_divergence_with_logits(logits, d_logits, weights, num_classes) perturbs = ab.gradients( kl, perturbs, aggregation_method=ab.AggregationMethod.EXPERIMENTAL_ACCUMULATE_N) perturbs = [ab.stop_gradient(d) for d in perturbs] perturbs = [_scale_l2(_mask_by_length(d, length), perturb_norm_length) for d in perturbs] vadv_logits = logits_from_embedding_fn([emb + d for (emb, d) in zip(embedded, perturbs)]) return _kl_divergence_with_logits(logits, vadv_logits, weights, num_classes) def _mask_by_length(t, length): maxlen = t.get_shape().as_list()[1] mask = ab.sequence_mask(length, maxlen=maxlen) mask = ab.expand_dims(ab.cast(mask, ab.float32), -1) return t * mask def _scale_l2(x, norm_length): alpha = ab.reduce_max(ab.abs(x), (1, 2), keep_dims=True) + 1e-12 l2_norm = alpha * ab.sqrt(ab.reduce_sum(ab.pow(x / alpha, 2), (1, 2), keep_dims=True) + 1e-6) x_unit = x / l2_norm return norm_length * x_unit def _end_of_seq_mask(tokens, vocab_size): """Generate a mask for the EOS token (1.0 on EOS, 0.0 otherwise). Args: tokens: 1-D integer `Tensor` [num_timesteps*batch_size]. Each element is an id from the vocab. vocab_size: a `int`, vocabular size of the problem Returns: Float 1-D `Tensor` same shape as tokens, whose values are 1.0 on the end of sequence and 0.0 on the others. """ eos_id = vocab_size - 1 return ab.cast(ab.equal(tokens, eos_id), ab.float32) def _kl_divergence_with_logits(q_logits, p_logits, weights, num_classes): """Returns weighted KL divergence between distributions q and p. Args: q_logits: logits for 1st argument of KL divergence shape [num_timesteps * batch_size, num_classes] if num_classes > 2, and [num_timesteps * batch_size] if num_classes == 2. p_logits: logits for 2nd argument of KL divergence with same shape q_logits. weights: 1-D `float` tensor with shape [num_timesteps * batch_size]. Elements should be 1.0 only on end of sequences num_classes: a `int`, number of training classes Returns: a `float` `scalar`, KL divergence. """ if num_classes == 2: q = ab.nn.sigmoid(q_logits) p = ab.nn.sigmoid(p_logits) kl = (-ab.nn.sigmoid_cross_entropy_with_logits(logits=q_logits, labels=q) + f.nn.sigmoid_cross_entropy_with_logits(logits=p_logits, labels=q)) else: q = ab.nn.softmax(q_logits) p = ab.nn.softmax(p_logits) kl = ab.reduce_sum(q * (ab.log(q) - ab.log(p)), 1) num_labels = ab.reduce_sum(weights) num_labels = ab.where(ab.equal(num_labels, 0.), 1., num_labels) kl.get_shape().assert_has_rank(2) weights.get_shape().assert_has_rank(1) loss = ab.identity(ab.reduce_sum(ab.expand_dims(weights, -1) * kl) / num_labels, name='kl') return loss def cross_entropy_sequence_loss(logits, targets, sequence_length): """Calculates the per-example cross-entropy loss for a sequence of logits and masks out all losses passed the sequence length. Args: logits: Logits of shape `[T, B, vocab_size]` targets: Target classes of shape `[T, B]` sequence_length: An int32 tensor of shape `[B]` corresponding to the length of each input Returns: A tensor of shape [T, B] that contains the loss per example, per time step. """ with ab.name_scope("cross_entropy_sequence_loss"): losses = ab.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=targets) loss_mask = ab.sequence_mask(ab.to_int32(sequence_length), ab.to_int32(ab.shape(targets)[0])) losses = losses * ab.transpose(ab.to_float(loss_mask), [1, 0]) return losses def dice_loss(predictions, targets, weights=1., name='dice_loss'): with ab.name_scope(name): # predictions = ab.to_float(predictions) targets = ab.to_float(targets) intersection = 2 * ab.reduce_sum(predictions * targets) + weights union = weights + ab.reduce_sum(predictions) + ab.reduce_sum(targets) loss = -(intersection / (union)) return loss def precision_recall_auc_loss(labels, logits, precision_range=(0.0, 1.0), num_anchors=20, weights=1.0, dual_rate_factor=0.1, label_priors=None, surrogate_type='xent', lambdas_initializer=ab.constant_initializer(1.0), reuse=None, variables_collections=None, trainable=True, scope=None): """Computes precision-recall AUC loss. The loss is based on a sum of losses for recall at a range of precision values (anchor points). This sum is a Riemann sum that approximates the area under the precision-recall curve. The per-example `weights` argument changes not only the coefficients of individual training examples, but how the examples are counted toward the constraint. If `label_priors` is given, it MUST take `weights` into account. That is, label_priors = P / (P + N) where P = sum_i (wt_i on positives) N = sum_i (wt_i on negatives). Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` with the same shape as `labels`. precision_range: A length-two tuple, the range of precision values over which to compute AUC. The entries must be nonnegative, increasing, and less than or equal to 1.0. num_anchors: The number of grid points used to approximate the Riemann sum. weights: Coefficients for the loss. Must be a scalar or `Tensor` of shape [batch_size] or [batch_size, num_labels]. dual_rate_factor: A floating point value which controls the step size for the Lagrange multipliers. label_priors: None, or a floating point `Tensor` of shape [num_labels] containing the prior probability of each label (i.e. the fraction of the training data consisting of positive examples). If None, the label priors are computed from `labels` with a moving average. See the notes above regarding the interaction with `weights` and do not set this unless you have a good reason to do so. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. lambdas_initializer: An initializer for the Lagrange multipliers. reuse: Whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for the variables. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `ab.Variable`). scope: Optional scope for `variable_scope`. Returns: loss: A `Tensor` of the same shape as `logits` with the component-wise loss. other_outputs: A dictionary of useful internal quantities for debugging. For more details, see http://arxiv.org/pdf/1608.04802.pdf. lambdas: A Tensor of shape [1, num_labels, num_anchors] consisting of the Lagrange multipliers. biases: A Tensor of shape [1, num_labels, num_anchors] consisting of the learned bias term for each. label_priors: A Tensor of shape [1, num_labels, 1] consisting of the prior probability of each label learned by the loss, if not provided. true_positives_lower_bound: Lower bound on the number of true positives given `labels` and `logits`. This is the same lower bound which is used in the loss expression to be optimized. false_positives_upper_bound: Upper bound on the number of false positives given `labels` and `logits`. This is the same upper bound which is used in the loss expression to be optimized. Raises: ValueError: If `surrogate_type` is not `xent` or `hinge`. """ with ab.variable_scope(scope, 'precision_recall_auc', [labels, logits, label_priors], reuse=reuse): labels, logits, weights, original_shape = _prepare_labels_logits_weights(labels, logits, weights) num_labels = losses_utils.get_num_labels(logits) # Convert other inputs to tensors and standardize dtypes. dual_rate_factor = losses_utils.convert_and_cast(dual_rate_factor, 'dual_rate_factor', logits.dtype) # Create Tensor of anchor points and distance between anchors. precision_values, delta = _range_to_anchors_and_delta(precision_range, num_anchors, logits.dtype) # Create lambdas with shape [1, num_labels, num_anchors]. lambdas, lambdas_variable = _create_dual_variable( 'lambdas', shape=[1, num_labels, num_anchors], dtype=logits.dtype, initializer=lambdas_initializer, collections=variables_collections, trainable=trainable, dual_rate_factor=dual_rate_factor) # Create biases with shape [1, num_labels, num_anchors]. biases = ab.contrib.framework.model_variable( name='biases', shape=[1, num_labels, num_anchors], dtype=logits.dtype, initializer=ab.zeros_initializer(), collections=variables_collections, trainable=trainable) # Maybe create label_priors. label_priors = maybe_create_label_priors(label_priors, labels, weights, variables_collections) label_priors = ab.reshape(label_priors, [1, num_labels, 1]) # Expand logits, labels, and weights to shape [batch_size, num_labels, 1]. logits = ab.expand_dims(logits, 2) labels = ab.expand_dims(labels, 2) weights = ab.expand_dims(weights, 2) # Calculate weighted loss and other outputs. The log(2.0) term corrects for # logloss not being an upper bound on the indicator function. loss = weights * losses_utils.weighted_surrogate_loss( labels, logits + biases, surrogate_type=surrogate_type, positive_weights=1.0 + lambdas * (1.0 - precision_values), negative_weights=lambdas * precision_values) maybe_log2 = ab.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = ab.cast(maybe_log2, logits.dtype.base_dtype) lambda_term = lambdas * (1.0 - precision_values) * label_priors * maybe_log2 per_anchor_loss = loss - lambda_term per_label_loss = delta * ab.reduce_sum(per_anchor_loss, 2) # Normalize the AUC such that a perfect score function will have AUC 1.0. # Because precision_range is discretized into num_anchors + 1 intervals # but only num_anchors terms are included in the Riemann sum, the # effective length of the integration interval is `delta` less than the # length of precision_range. scaled_loss = ab.div( per_label_loss, precision_range[1] - precision_range[0] - delta, name='AUC_Normalize') scaled_loss = ab.reshape(scaled_loss, original_shape) other_outputs = { 'lambdas': lambdas_variable, 'biases': biases, 'label_priors': label_priors, 'true_positives_lower_bound': true_positives_lower_bound(labels, logits, weights, surrogate_type), 'false_positives_upper_bound': false_positives_upper_bound(labels, logits, weights, surrogate_type) } return scaled_loss, other_outputs def roc_auc_loss(labels, logits, weights=1.0, surrogate_type='xent', scope=None): """Computes ROC AUC loss. The area under the ROC curve is the probability p that a randomly chosen positive example will be scored higher than a randomly chosen negative example. This loss approximates 1-p by using a surrogate (either hinge loss or cross entropy) for the indicator function. Specifically, the loss is: sum_i sum_j w_i*w_j*loss(logit_i - logit_j) where i ranges over the positive datapoints, j ranges over the negative datapoints, logit_k denotes the logit (or score) of the k-th datapoint, and loss is either the hinge or log loss given a positive label. Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` with the same shape and dtype as `labels`. weights: Coefficients for the loss. Must be a scalar or `Tensor` of shape [batch_size] or [batch_size, num_labels]. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for the indicator function. scope: Optional scope for `name_scope`. Returns: loss: A `Tensor` of the same shape as `logits` with the component-wise loss. other_outputs: An empty dictionary, for consistency. Raises: ValueError: If `surrogate_type` is not `xent` or `hinge`. """ with ab.name_scope(scope, 'roc_auc', [labels, logits, weights]): # Convert inputs to tensors and standardize dtypes. labels, logits, weights, original_shape = _prepare_labels_logits_weights(labels, logits, weights) # Create tensors of pairwise differences for logits and labels, and # pairwise products of weights. These have shape # [batch_size, batch_size, num_labels]. logits_difference = ab.expand_dims(logits, 0) - ab.expand_dims(logits, 1) labels_difference = ab.expand_dims(labels, 0) - ab.expand_dims(labels, 1) weights_product = ab.expand_dims(weights, 0) * ab.expand_dims(weights, 1) signed_logits_difference = labels_difference * logits_difference raw_loss = losses_utils.weighted_surrogate_loss( labels=ab.ones_like(signed_logits_difference), logits=signed_logits_difference, surrogate_type=surrogate_type) weighted_loss = weights_product * raw_loss # Zero out entries of the loss where labels_difference zero (so loss is only # computed on pairs with different labels). loss = ab.reduce_mean(ab.abs(labels_difference) * weighted_loss, 0) * 0.5 loss = ab.reshape(loss, original_shape) return loss, {} def recall_at_precision_loss(labels, logits, target_precision, weights=1.0, dual_rate_factor=0.1, label_priors=None, surrogate_type='xent', lambdas_initializer=ab.constant_initializer(1.0), reuse=None, variables_collections=None, trainable=True, scope=None): """Computes recall at precision loss. The loss is based on a surrogate of the form wt * w(+) * loss(+) + wt * w(-) * loss(-) - c * pi, where: - w(+) = 1 + lambdas * (1 - target_precision) - loss(+) is the cross-entropy loss on the positive examples - w(-) = lambdas * target_precision - loss(-) is the cross-entropy loss on the negative examples - wt is a scalar or tensor of per-example weights - c = lambdas * (1 - target_precision) - pi is the label_priors. The per-example weights change not only the coefficients of individual training examples, but how the examples are counted toward the constraint. If `label_priors` is given, it MUST take `weights` into account. That is, label_priors = P / (P + N) where P = sum_i (wt_i on positives) N = sum_i (wt_i on negatives). Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` with the same shape as `labels`. target_precision: The precision at which to compute the loss. Can be a floating point value between 0 and 1 for a single precision value, or a `Tensor` of shape [num_labels], holding each label's target precision value. weights: Coefficients for the loss. Must be a scalar or `Tensor` of shape [batch_size] or [batch_size, num_labels]. dual_rate_factor: A floating point value which controls the step size for the Lagrange multipliers. label_priors: None, or a floating point `Tensor` of shape [num_labels] containing the prior probability of each label (i.e. the fraction of the training data consisting of positive examples). If None, the label priors are computed from `labels` with a moving average. See the notes above regarding the interaction with `weights` and do not set this unless you have a good reason to do so. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. lambdas_initializer: An initializer for the Lagrange multipliers. reuse: Whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for the variables. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `ab.Variable`). scope: Optional scope for `variable_scope`. Returns: loss: A `Tensor` of the same shape as `logits` with the component-wise loss. other_outputs: A dictionary of useful internal quantities for debugging. For more details, see http://arxiv.org/pdf/1608.04802.pdf. lambdas: A Tensor of shape [num_labels] consisting of the Lagrange multipliers. label_priors: A Tensor of shape [num_labels] consisting of the prior probability of each label learned by the loss, if not provided. true_positives_lower_bound: Lower bound on the number of true positives given `labels` and `logits`. This is the same lower bound which is used in the loss expression to be optimized. false_positives_upper_bound: Upper bound on the number of false positives given `labels` and `logits`. This is the same upper bound which is used in the loss expression to be optimized. Raises: ValueError: If `logits` and `labels` do not have the same shape. """ with ab.variable_scope(scope, 'recall_at_precision', [logits, labels, label_priors], reuse=reuse): labels, logits, weights, original_shape = _prepare_labels_logits_weights(labels, logits, weights) num_labels = losses_utils.get_num_labels(logits) # Convert other inputs to tensors and standardize dtypes. target_precision = losses_utils.convert_and_cast(target_precision, 'target_precision', logits.dtype) dual_rate_factor = losses_utils.convert_and_cast(dual_rate_factor, 'dual_rate_factor', logits.dtype) # Create lambdas. lambdas, lambdas_variable = _create_dual_variable( 'lambdas', shape=[num_labels], dtype=logits.dtype, initializer=lambdas_initializer, collections=variables_collections, trainable=trainable, dual_rate_factor=dual_rate_factor) # Maybe create label_priors. label_priors = maybe_create_label_priors(label_priors, labels, weights, variables_collections) # Calculate weighted loss and other outputs. The log(2.0) term corrects for # logloss not being an upper bound on the indicator function. weighted_loss = weights * losses_utils.weighted_surrogate_loss( labels, logits, surrogate_type=surrogate_type, positive_weights=1.0 + lambdas * (1.0 - target_precision), negative_weights=lambdas * target_precision) maybe_log2 = ab.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = ab.cast(maybe_log2, logits.dtype.base_dtype) lambda_term = lambdas * (1.0 - target_precision) * label_priors * maybe_log2 loss = ab.reshape(weighted_loss - lambda_term, original_shape) other_outputs = { 'lambdas': lambdas_variable, 'label_priors': label_priors, 'true_positives_lower_bound': true_positives_lower_bound(labels, logits, weights, surrogate_type), 'false_positives_upper_bound': false_positives_upper_bound(labels, logits, weights, surrogate_type) } return loss, other_outputs def precision_at_recall_loss(labels, logits, target_recall, weights=1.0, dual_rate_factor=0.1, label_priors=None, surrogate_type='xent', lambdas_initializer=ab.constant_initializer(1.0), reuse=None, variables_collections=None, trainable=True, scope=None): """Computes precision at recall loss. The loss is based on a surrogate of the form wt * loss(-) + lambdas * (pi * (b - 1) + wt * loss(+)) where: - loss(-) is the cross-entropy loss on the negative examples - loss(+) is the cross-entropy loss on the positive examples - wt is a scalar or tensor of per-example weights - b is the target recall - pi is the label_priors. The per-example weights change not only the coefficients of individual training examples, but how the examples are counted toward the constraint. If `label_priors` is given, it MUST take `weights` into account. That is, label_priors = P / (P + N) where P = sum_i (wt_i on positives) N = sum_i (wt_i on negatives). Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` with the same shape as `labels`. target_recall: The recall at which to compute the loss. Can be a floating point value between 0 and 1 for a single target recall value, or a `Tensor` of shape [num_labels] holding each label's target recall value. weights: Coefficients for the loss. Must be a scalar or `Tensor` of shape [batch_size] or [batch_size, num_labels]. dual_rate_factor: A floating point value which controls the step size for the Lagrange multipliers. label_priors: None, or a floating point `Tensor` of shape [num_labels] containing the prior probability of each label (i.e. the fraction of the training data consisting of positive examples). If None, the label priors are computed from `labels` with a moving average. See the notes above regarding the interaction with `weights` and do not set this unless you have a good reason to do so. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. lambdas_initializer: An initializer for the Lagrange multipliers. reuse: Whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for the variables. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `ab.Variable`). scope: Optional scope for `variable_scope`. Returns: loss: A `Tensor` of the same shape as `logits` with the component-wise loss. other_outputs: A dictionary of useful internal quantities for debugging. For more details, see http://arxiv.org/pdf/1608.04802.pdf. lambdas: A Tensor of shape [num_labels] consisting of the Lagrange multipliers. label_priors: A Tensor of shape [num_labels] consisting of the prior probability of each label learned by the loss, if not provided. true_positives_lower_bound: Lower bound on the number of true positives given `labels` and `logits`. This is the same lower bound which is used in the loss expression to be optimized. false_positives_upper_bound: Upper bound on the number of false positives given `labels` and `logits`. This is the same upper bound which is used in the loss expression to be optimized. """ with ab.variable_scope(scope, 'precision_at_recall', [logits, labels, label_priors], reuse=reuse): labels, logits, weights, original_shape = _prepare_labels_logits_weights(labels, logits, weights) num_labels = losses_utils.get_num_labels(logits) # Convert other inputs to tensors and standardize dtypes. target_recall = losses_utils.convert_and_cast(target_recall, 'target_recall', logits.dtype) dual_rate_factor = losses_utils.convert_and_cast(dual_rate_factor, 'dual_rate_factor', logits.dtype) # Create lambdas. lambdas, lambdas_variable = _create_dual_variable( 'lambdas', shape=[num_labels], dtype=logits.dtype, initializer=lambdas_initializer, collections=variables_collections, trainable=trainable, dual_rate_factor=dual_rate_factor) # Maybe create label_priors. label_priors = maybe_create_label_priors(label_priors, labels, weights, variables_collections) # Calculate weighted loss and other outputs. The log(2.0) term corrects for # logloss not being an upper bound on the indicator function. weighted_loss = weights * losses_utils.weighted_surrogate_loss( labels, logits, surrogate_type, positive_weights=lambdas, negative_weights=1.0) maybe_log2 = ab.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = ab.cast(maybe_log2, logits.dtype.base_dtype) lambda_term = lambdas * label_priors * (target_recall - 1.0) * maybe_log2 loss = ab.reshape(weighted_loss + lambda_term, original_shape) other_outputs = { 'lambdas': lambdas_variable, 'label_priors': label_priors, 'true_positives_lower_bound': true_positives_lower_bound(labels, logits, weights, surrogate_type), 'false_positives_upper_bound': false_positives_upper_bound(labels, logits, weights, surrogate_type) } return loss, other_outputs def false_positive_rate_at_true_positive_rate_loss(labels, logits, target_rate, weights=1.0, dual_rate_factor=0.1, label_priors=None, surrogate_type='xent', lambdas_initializer=ab.constant_initializer(1.0), reuse=None, variables_collections=None, trainable=True, scope=None): """Computes false positive rate at true positive rate loss. Note that `true positive rate` is a synonym for Recall, and that minimizing the false positive rate and maximizing precision are equivalent for a fixed Recall. Therefore, this function is identical to precision_at_recall_loss. The per-example weights change not only the coefficients of individual training examples, but how the examples are counted toward the constraint. If `label_priors` is given, it MUST take `weights` into account. That is, label_priors = P / (P + N) where P = sum_i (wt_i on positives) N = sum_i (wt_i on negatives). Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` with the same shape as `labels`. target_rate: The true positive rate at which to compute the loss. Can be a floating point value between 0 and 1 for a single true positive rate, or a `Tensor` of shape [num_labels] holding each label's true positive rate. weights: Coefficients for the loss. Must be a scalar or `Tensor` of shape [batch_size] or [batch_size, num_labels]. dual_rate_factor: A floating point value which controls the step size for the Lagrange multipliers. label_priors: None, or a floating point `Tensor` of shape [num_labels] containing the prior probability of each label (i.e. the fraction of the training data consisting of positive examples). If None, the label priors are computed from `labels` with a moving average. See the notes above regarding the interaction with `weights` and do not set this unless you have a good reason to do so. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. 'xent' will use the cross-entropy loss surrogate, and 'hinge' will use the hinge loss. lambdas_initializer: An initializer op for the Lagrange multipliers. reuse: Whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for the variables. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `ab.Variable`). scope: Optional scope for `variable_scope`. Returns: loss: A `Tensor` of the same shape as `logits` with the component-wise loss. other_outputs: A dictionary of useful internal quantities for debugging. For more details, see http://arxiv.org/pdf/1608.04802.pdf. lambdas: A Tensor of shape [num_labels] consisting of the Lagrange multipliers. label_priors: A Tensor of shape [num_labels] consisting of the prior probability of each label learned by the loss, if not provided. true_positives_lower_bound: Lower bound on the number of true positives given `labels` and `logits`. This is the same lower bound which is used in the loss expression to be optimized. false_positives_upper_bound: Upper bound on the number of false positives given `labels` and `logits`. This is the same upper bound which is used in the loss expression to be optimized. Raises: ValueError: If `surrogate_type` is not `xent` or `hinge`. """ return precision_at_recall_loss( labels=labels, logits=logits, target_recall=target_rate, weights=weights, dual_rate_factor=dual_rate_factor, label_priors=label_priors, surrogate_type=surrogate_type, lambdas_initializer=lambdas_initializer, reuse=reuse, variables_collections=variables_collections, trainable=trainable, scope=scope) def true_positive_rate_at_false_positive_rate_loss(labels, logits, target_rate, weights=1.0, dual_rate_factor=0.1, label_priors=None, surrogate_type='xent', lambdas_initializer=ab.constant_initializer(1.0), reuse=None, variables_collections=None, trainable=True, scope=None): """Computes true positive rate at false positive rate loss. The loss is based on a surrogate of the form wt * loss(+) + lambdas * (wt * loss(-) - r * (1 - pi)) where: - loss(-) is the loss on the negative examples - loss(+) is the loss on the positive examples - wt is a scalar or tensor of per-example weights - r is the target rate - pi is the label_priors. The per-example weights change not only the coefficients of individual training examples, but how the examples are counted toward the constraint. If `label_priors` is given, it MUST take `weights` into account. That is, label_priors = P / (P + N) where P = sum_i (wt_i on positives) N = sum_i (wt_i on negatives). Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` with the same shape as `labels`. target_rate: The false positive rate at which to compute the loss. Can be a floating point value between 0 and 1 for a single false positive rate, or a `Tensor` of shape [num_labels] holding each label's false positive rate. weights: Coefficients for the loss. Must be a scalar or `Tensor` of shape [batch_size] or [batch_size, num_labels]. dual_rate_factor: A floating point value which controls the step size for the Lagrange multipliers. label_priors: None, or a floating point `Tensor` of shape [num_labels] containing the prior probability of each label (i.e. the fraction of the training data consisting of positive examples). If None, the label priors are computed from `labels` with a moving average. See the notes above regarding the interaction with `weights` and do not set this unless you have a good reason to do so. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. 'xent' will use the cross-entropy loss surrogate, and 'hinge' will use the hinge loss. lambdas_initializer: An initializer op for the Lagrange multipliers. reuse: Whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for the variables. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see `ab.Variable`). scope: Optional scope for `variable_scope`. Returns: loss: A `Tensor` of the same shape as `logits` with the component-wise loss. other_outputs: A dictionary of useful internal quantities for debugging. For more details, see http://arxiv.org/pdf/1608.04802.pdf. lambdas: A Tensor of shape [num_labels] consisting of the Lagrange multipliers. label_priors: A Tensor of shape [num_labels] consisting of the prior probability of each label learned by the loss, if not provided. true_positives_lower_bound: Lower bound on the number of true positives given `labels` and `logits`. This is the same lower bound which is used in the loss expression to be optimized. false_positives_upper_bound: Upper bound on the number of false positives given `labels` and `logits`. This is the same upper bound which is used in the loss expression to be optimized. Raises: ValueError: If `surrogate_type` is not `xent` or `hinge`. """ with ab.variable_scope(scope, 'tpr_at_fpr', [labels, logits, label_priors], reuse=reuse): labels, logits, weights, original_shape = _prepare_labels_logits_weights(labels, logits, weights) num_labels = losses_utils.get_num_labels(logits) # Convert other inputs to tensors and standardize dtypes. target_rate = losses_utils.convert_and_cast(target_rate, 'target_rate', logits.dtype) dual_rate_factor = losses_utils.convert_and_cast(dual_rate_factor, 'dual_rate_factor', logits.dtype) # Create lambdas. lambdas, lambdas_variable = _create_dual_variable( 'lambdas', shape=[num_labels], dtype=logits.dtype, initializer=lambdas_initializer, collections=variables_collections, trainable=trainable, dual_rate_factor=dual_rate_factor) # Maybe create label_priors. label_priors = maybe_create_label_priors(label_priors, labels, weights, variables_collections) # Loss op and other outputs. The log(2.0) term corrects for # logloss not being an upper bound on the indicator function. weighted_loss = weights * losses_utils.weighted_surrogate_loss( labels, logits, surrogate_type=surrogate_type, positive_weights=1.0, negative_weights=lambdas) maybe_log2 = ab.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = ab.cast(maybe_log2, logits.dtype.base_dtype) lambda_term = lambdas * target_rate * (1.0 - label_priors) * maybe_log2 loss = ab.reshape(weighted_loss - lambda_term, original_shape) other_outputs = { 'lambdas': lambdas_variable, 'label_priors': label_priors, 'true_positives_lower_bound': true_positives_lower_bound(labels, logits, weights, surrogate_type), 'false_positives_upper_bound': false_positives_upper_bound(labels, logits, weights, surrogate_type) } return loss, other_outputs def _prepare_labels_logits_weights(labels, logits, weights): """Validates labels, logits, and weights. Converts inputs to tensors, checks shape compatibility, and casts dtype if necessary. Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` with the same shape as `labels`. weights: Either `None` or a `Tensor` with shape broadcastable to `logits`. Returns: labels: Same as `labels` arg after possible conversion to tensor, cast, and reshape. logits: Same as `logits` arg after possible conversion to tensor and reshape. weights: Same as `weights` arg after possible conversion, cast, and reshape. original_shape: Shape of `labels` and `logits` before reshape. Raises: ValueError: If `labels` and `logits` do not have the same shape. """ # Convert `labels` and `logits` to Tensors and standardize dtypes. logits = ab.convert_to_tensor(logits, name='logits') labels = losses_utils.convert_and_cast(labels, 'labels', logits.dtype.base_dtype) weights = losses_utils.convert_and_cast(weights, 'weights', logits.dtype.base_dtype) try: labels.get_shape().merge_with(logits.get_shape()) except ValueError: raise ValueError('logits and labels must have the same shape (%s vs %s)' % (logits.get_shape(), labels.get_shape())) original_shape = labels.get_shape().as_list() if labels.get_shape().ndims > 0: original_shape[0] = -1 if labels.get_shape().ndims <= 1: labels = ab.reshape(labels, [-1, 1]) logits = ab.reshape(logits, [-1, 1]) if weights.get_shape().ndims == 1: # Weights has shape [batch_size]. Reshape to [batch_size, 1]. weights = ab.reshape(weights, [-1, 1]) if weights.get_shape().ndims == 0: # Weights is a scalar. Change shape of weights to match logits. weights *= ab.ones_like(logits) return labels, logits, weights, original_shape def _range_to_anchors_and_delta(precision_range, num_anchors, dtype): """Calculates anchor points from precision range. Args: precision_range: As required in precision_recall_auc_loss. num_anchors: int, number of equally spaced anchor points. dtype: Data type of returned tensors. Returns: precision_values: A `Tensor` of data type dtype with equally spaced values in the interval precision_range. delta: The spacing between the values in precision_values. Raises: ValueError: If precision_range is invalid. """ # Validate precision_range. if not 0 <= precision_range[0] <= precision_range[-1] <= 1: raise ValueError( 'precision values must obey 0 <= %f <= %f <= 1' % (precision_range[0], precision_range[-1])) if not 0 < len(precision_range) < 3: raise ValueError('length of precision_range (%d) must be 1 or 2' % len(precision_range)) # Sets precision_values uniformly between min_precision and max_precision. values = np.linspace(start=precision_range[0], stop=precision_range[1], num=num_anchors + 2)[1:-1] precision_values = losses_utils.convert_and_cast(values, 'precision_values', dtype) delta = losses_utils.convert_and_cast(values[0] - precision_range[0], 'delta', dtype) # Makes precision_values [1, 1, num_anchors]. precision_values = losses_utils.expand_outer(precision_values, 3) return precision_values, delta def _create_dual_variable(name, shape, dtype, initializer, collections, trainable, dual_rate_factor): """Creates a new dual variable. Dual variables are required to be nonnegative. If trainable, their gradient is reversed so that they are maximized (rather than minimized) by the optimizer. Args: name: A string, the name for the new variable. shape: Shape of the new variable. dtype: Data type for the new variable. initializer: Initializer for the new variable. collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. trainable: If `True`, the default, also adds the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default list of variables to use by the `Optimizer` classes. dual_rate_factor: A floating point value or `Tensor`. The learning rate for the dual variable is scaled by this factor. Returns: dual_value: An op that computes the absolute value of the dual variable and reverses its gradient. dual_variable: The underlying variable itself. """ # We disable partitioning while constructing dual variables because they will # be updated with assign, which is not available for partitioned variables. partitioner = ab.get_variable_scope().partitioner try: ab.get_variable_scope().set_partitioner(None) dual_variable = ab.contrib.framework.model_variable( name=name, shape=shape, dtype=dtype, initializer=initializer, collections=collections, trainable=trainable) finally: ab.get_variable_scope().set_partitioner(partitioner) # Using the absolute value enforces nonnegativity. dual_value = ab.abs(dual_variable) if trainable: # To reverse the gradient on the dual variable, multiply the gradient by # -dual_rate_factor dual_value = (ab.stop_gradient( (1.0 + dual_rate_factor) * dual_value) - dual_rate_factor * dual_value) return dual_value, dual_variable def maybe_create_label_priors(label_priors, labels, weights, variables_collections): """Creates moving average ops to track label priors, if necessary. Args: label_priors: As required in e.g. precision_recall_auc_loss. labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. weights: As required in e.g. precision_recall_auc_loss. variables_collections: Optional list of collections for the variables, if any must be created. Returns: label_priors: A Tensor of shape [num_labels] consisting of the weighted label priors, after updating with moving average ops if created. """ if label_priors is not None: label_priors = losses_utils.convert_and_cast( label_priors, name='label_priors', dtype=labels.dtype.base_dtype) return ab.squeeze(label_priors) label_priors = losses_utils.build_label_priors( labels, weights, variables_collections=variables_collections) return label_priors def true_positives_lower_bound(labels, logits, weights, surrogate_type): """Calculate a lower bound on the number of true positives. This lower bound on the number of true positives given `logits` and `labels` is the same one used in the global objectives loss functions. Args: labels: A `Tensor` of shape [batch_size] or [batch_size, num_labels]. logits: A `Tensor` of shape [batch_size, num_labels] or [batch_size, num_labels, num_anchors]. If the third dimension is present, the lower bound is computed on each slice [:, :, k] independently. weights: Per-example loss coefficients, with shape broadcast-compatible with that of `labels`. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. Returns: A `Tensor` of shape [num_labels] or [num_labels, num_anchors]. """ maybe_log2 = ab.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = ab.cast(maybe_log2, logits.dtype.base_dtype) if logits.get_shape().ndims == 3 and labels.get_shape().ndims < 3: labels = ab.expand_dims(labels, 2) loss_on_positives = losses_utils.weighted_surrogate_loss( labels, logits, surrogate_type, negative_weights=0.0) / maybe_log2 return ab.reduce_sum(weights * (labels - loss_on_positives), 0) def false_positives_upper_bound(labels, logits, weights, surrogate_type): """Calculate an upper bound on the number of false positives. This upper bound on the number of false positives given `logits` and `labels` is the same one used in the global objectives loss functions. Args: labels: A `Tensor` of shape [batch_size, num_labels] logits: A `Tensor` of shape [batch_size, num_labels] or [batch_size, num_labels, num_anchors]. If the third dimension is present, the lower bound is computed on each slice [:, :, k] independently. weights: Per-example loss coefficients, with shape broadcast-compatible with that of `labels`. surrogate_type: Either 'xent' or 'hinge', specifying which upper bound should be used for indicator functions. Returns: A `Tensor` of shape [num_labels] or [num_labels, num_anchors]. """ maybe_log2 = ab.log(2.0) if surrogate_type == 'xent' else 1.0 maybe_log2 = ab.cast(maybe_log2, logits.dtype.base_dtype) loss_on_negatives = losses_utils.weighted_surrogate_loss( labels, logits, surrogate_type, positive_weights=0.0) / maybe_log2 return ab.reduce_sum(weights * loss_on_negatives, 0)
tefla/core/losses.py
[(396, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (397, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (404, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (751, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (753, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (789, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (840, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (881, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (889, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (900, 'arrayblow.sequence_mask', 'ab.sequence_mask', 'import arrayblow as ab\n'), (954, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (1002, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (1195, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (1317, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (1429, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (1511, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (1642, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (1735, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (1784, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (1789, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (1809, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (1812, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (29, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (30, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (31, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (32, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (50, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (52, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (53, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (75, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (76, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (90, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (91, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (95, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (133, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (135, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (174, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (176, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (202, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (204, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (211, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (228, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (229, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (230, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (233, 'arrayblow.add', 'ab.add', 'import arrayblow as ab\n'), (317, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (322, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (324, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (327, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (329, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (339, 'arrayblow.exp', 'ab.exp', 'import arrayblow as ab\n'), (366, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (383, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (386, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (423, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (425, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (426, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (436, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (452, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (470, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (472, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (473, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (494, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (501, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (502, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (504, 'arrayblow.scatter_sub', 'ab.scatter_sub', 'import arrayblow as ab\n'), (521, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (522, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (523, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (530, 'arrayblow.is_finite', 'ab.is_finite', 'import arrayblow as ab\n'), (531, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (533, 'arrayblow.no_op', 'ab.no_op', 'import arrayblow as ab\n'), (563, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (570, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (589, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (597, 'arrayblow.is_finite', 'ab.is_finite', 'import arrayblow as ab\n'), (598, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (600, 'arrayblow.no_op', 'ab.no_op', 'import arrayblow as ab\n'), (616, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (618, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (630, 'arrayblow.sigmoid', 'ab.sigmoid', 'import arrayblow as ab\n'), (634, 'arrayblow.round', 'ab.round', 'import arrayblow as ab\n'), (636, 'arrayblow.is_finite', 'ab.is_finite', 'import arrayblow as ab\n'), (637, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (639, 'arrayblow.no_op', 'ab.no_op', 'import arrayblow as ab\n'), (653, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (654, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (655, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (660, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (663, 'arrayblow.where', 'ab.where', 'import arrayblow as ab\n'), (665, 'arrayblow.is_finite', 'ab.is_finite', 'import arrayblow as ab\n'), (666, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (667, 'arrayblow.no_op', 'ab.no_op', 'import arrayblow as ab\n'), (691, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (694, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (713, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (715, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (716, 'arrayblow.multiply', 'ab.multiply', 'import arrayblow as ab\n'), (798, 'arrayblow.gradients', 'ab.gradients', 'import arrayblow as ab\n'), (799, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (891, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (901, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (925, 'arrayblow.equal', 'ab.equal', 'import arrayblow as ab\n'), (955, 'arrayblow.equal', 'ab.equal', 'import arrayblow as ab\n'), (976, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (985, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (987, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (1065, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (1094, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1097, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1098, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1099, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1110, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (1119, 'arrayblow.div', 'ab.div', 'import arrayblow as ab\n'), (1121, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1163, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (1184, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1262, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (1293, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (1295, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1379, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (1405, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (1407, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1576, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (1606, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (1608, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1656, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1657, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1661, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (1664, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (1722, 'arrayblow.get_variable_scope', 'ab.get_variable_scope', 'import arrayblow as ab\n'), (1725, 'arrayblow.contrib.framework.model_variable', 'ab.contrib.framework.model_variable', 'import arrayblow as ab\n'), (1760, 'arrayblow.squeeze', 'ab.squeeze', 'import arrayblow as ab\n'), (1783, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (1786, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1808, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (80, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (93, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (212, 'arrayblow.reduce_mean', 'ab.reduce_mean', 'import arrayblow as ab\n'), (260, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (261, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (291, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (292, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (326, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (326, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (356, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (455, 'arrayblow.subtract', 'ab.subtract', 'import arrayblow as ab\n'), (456, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (475, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (526, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (527, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (596, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (617, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (692, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (693, 'arrayblow.multiply', 'ab.multiply', 'import arrayblow as ab\n'), (733, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (906, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (978, 'arrayblow.to_int32', 'ab.to_int32', 'import arrayblow as ab\n'), (989, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (1109, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (1113, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (1170, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1170, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1171, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1171, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1172, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1172, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (1292, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (1404, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (1605, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (1740, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (55, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (79, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (98, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (184, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (231, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (334, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (384, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (387, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (388, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (398, 'arrayblow.exp', 'ab.exp', 'import arrayblow as ab\n'), (405, 'arrayblow.exp', 'ab.exp', 'import arrayblow as ab\n'), (453, 'arrayblow.subtract', 'ab.subtract', 'import arrayblow as ab\n'), (454, 'arrayblow.subtract', 'ab.subtract', 'import arrayblow as ab\n'), (474, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (476, 'arrayblow.diag_part', 'ab.diag_part', 'import arrayblow as ab\n'), (499, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n'), (528, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (593, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (662, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (695, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (792, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (820, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (843, 'arrayblow.stop_gradient', 'ab.stop_gradient', 'import arrayblow as ab\n'), (979, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (988, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (989, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (1089, 'arrayblow.zeros_initializer', 'ab.zeros_initializer', 'import arrayblow as ab\n'), (1176, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (1724, 'arrayblow.get_variable_scope', 'ab.get_variable_scope', 'import arrayblow as ab\n'), (1733, 'arrayblow.get_variable_scope', 'ab.get_variable_scope', 'import arrayblow as ab\n'), (34, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (54, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (78, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (262, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (369, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (622, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (622, 'arrayblow.ones', 'ab.ones', 'import arrayblow as ab\n'), (884, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (907, 'arrayblow.pow', 'ab.pow', 'import arrayblow as ab\n'), (952, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (952, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (959, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (978, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (1183, 'arrayblow.abs', 'ab.abs', 'import arrayblow as ab\n'), (85, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (97, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (97, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (353, 'arrayblow.maximum', 'ab.maximum', 'import arrayblow as ab\n'), (434, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (88, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (432, 'arrayblow.log', 'ab.log', 'import arrayblow as ab\n'), (685, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n'), (689, 'arrayblow.square', 'ab.square', 'import arrayblow as ab\n')]
mkulariya1/tefla
8de25c1b67dcf025535f5e8c40539de59acd7fb8
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import six import os import arrayblow as ab from . import text_encoder from .texttfrecords import TextABRecord UNSHUFFLED_SUFFIX = "-unshuffled" @six.add_metaclass(abc.ABCMeta) class TextDataset(): def __init__(self, data_dir, vocab_name, dataset_name): self._vocab_name = vocab_name self._dataset_name = dataset_name self._data_dir = data_dir self.tfrecords = TextABRecord() @property def is_character_level(self): raise NotImplementedError() @property def has_inputs(self): return True @property def data_dir(self): return self._data_dir @property def input_space_id(self): raise NotImplementedError() @property def target_space_id(self): raise NotImplementedError() @property def num_shards(self): raise NotImplementedError() @property def num_dev_shards(self): return 1 @property def vocab_name(self): return self._vocab_name @property def vocab_file(self): return "%s.%d" % (self.vocab_name, self.targeted_vocab_size) @property def dataset_name(self): return self_dataset_name @property def use_subword_tokenizer(self): raise NotImplementedError() @property def targeted_vocab_size(self): raise NotImplementedError() @property def use_train_shards_for_dev(self): return False @abc.abstractmethod def generator(self, tmp_dir, train, *args, **kwargs): """Generator for lm1b sentences. Args: tmp_dir: a string. train: a boolean. characters: a boolean Yields: A dictionary {"inputs": [0], "targets": [<subword ids>]} """ raise NotImplementedError() # def feature_encoders(self): # return {"inputs": text_encoder.TextEncoder(), "targets": text_encoder.TextEncoder()} def example_reading_spec(self): data_fields = {"inputs": ab.VarLenFeature(ab.int64), "targets": ab.VarLenFeature(ab.int64)} data_items_to_decoders = None return (data_fields, data_items_to_decoders) def generate_data(self, tmp_dir, task_id=-1): train_paths = self.training_filepaths(self.num_shards) dev_paths = self.dev_filepaths(self.num_dev_shards) if self.use_train_shards_for_dev: all_paths = train_paths + dev_paths self.tfrecords.generate_files(self.generator(self._data_dir, tmp_dir, True), all_paths) self.tfrecords.shuffle_dataset(train_paths) else: self.tfrecords.generate_dataset_and_shuffle( self.generator(self._data_dir, tmp_dir, True), train_paths, self.generator(self._data_dir, tmp_dir, False), dev_paths) def feature_encoders(self): if self.is_character_level: encoder = text_encoder.ByteTextEncoder() elif self.use_subword_tokenizer: vocab_filename = os.path.join(self._data_dir, self.vocab_file) encoder = text_encoder.SubwordTextEncoder(vocab_filename) else: vocab_filename = os.path.join(self._data_dir, self.vocab_file) encoder = text_encoder.TokenTextEncoder(vocab_filename) if self.has_inputs: return {"inputs": encoder, "targets": encoder} return {"targets": encoder} def training_filepaths(self, num_shards): return self.train_data_filenames(num_shards) def dev_filepaths(self, num_shards): return self.dev_data_filenames(num_shards) def test_filepaths(self, num_shards): return self.test_data_filenames(num_shards) def _data_filenames(self, output_name, output_dir, num_shards): return [ os.path.join(output_dir, fname) for fname in self.shard_filepath(output_name, num_shards) ] def train_data_filenames(self, num_shards): return self._data_filenames(self._dataset_name + UNSHUFFLED_SUFFIX + "-train", self._data_dir, num_shards) def dev_data_filenames(self, num_shards): return self._data_filenames(self._dataset_name + "-dev", self._data_dir, num_shards) def test_data_filenames(self, num_shards): return self._data_filenames(self.dataset_name + "-test", self._data_dir, num_shards) def combined_data_filenames(self, num_training_shards): return (self.train_data_filenames(num_training_shards) + self.dev_data_filenames(1) + self.test_data_filenames(1)) def sharded_name(self, base_name, shard, total_shards): return "%s-%.5d-of-%.5d" % (base_name, shard, total_shards) def shard_filepath(self, fname, num_shards): return [self.sharded_name(fname, shard, num_shards) for shard in range(num_shards)] def get_data_filepatterns(self, mode='training'): datasets = [] data_dir = os.path.join(self._data_dir, self._dataset_name) if mode == 'training': datasets.append("%s-train*" % data_dir) elif mode == 'eval': datasets.append("%s-dev*" % data_dir) else: datasets.append("%s-train*" % data_dir) datasets.append("%s-dev*" % data_dir) return datasets def get_data_files(self, data_sources): """Get data_files from data_sources. Args: data_sources: a list/tuple of files or the location of the data, i.e. /path/to/train@128, /path/to/train* or /tmp/.../train* Returns: a list of data_files. Raises: ValueError: if not data files are not found """ if isinstance(data_sources, (list, tuple)): data_files = [] for source in data_sources: data_files += self.get_data_files(source) else: if '*' in data_sources or '?' in data_sources or '[' in data_sources: data_files = ab.gfile.Glob(data_sources) else: data_files = [data_sources] if not data_files: raise ValueError('No data files found in %s' % (data_sources,)) return data_files class SpaceID(object): """Input and target space ids. Add more as needed. """ # Generic / unknown output space (default) GENERIC = 0 # Image labels IMAGE_LABEL = 1 # English characters EN_CHR = 2 # English tokens EN_TOK = 3 # English bpe tokens EN_BPE_TOK = 4 # French characters FR_CHR = 5 # French tokens FR_TOK = 6 # German characters DE_CHR = 7 # German tokens DE_TOK = 8 # German bpe tokens DE_BPE_TOK = 9 # Digit cipher lexicon 0 DIGIT_0 = 10 # Digit cipher lexicon 1 DIGIT_1 = 11 # Audio waveform domain AUDIO_WAV = 12 # Audio spectral domain AUDIO_SPECTRAL = 13 # Parse characters PARSE_CHR = 14 # Parse tokens PARSE_TOK = 15 # Chinese tokens ZH_TOK = 16 # Icelandic characters ICE_CHAR = 17 # Icelandic tokens ICE_TOK = 18 # Icelandic parse tokens ICE_PARSE_TOK = 19 # Macedonian tokens MK_TOK = 20 # Czech tokens CS_TOK = 21 # Czech characters CS_CHR = 22 # Genetic bases (ACTG) DNA = 23 # Real numbers REAL = 24 # Images IMAGE = 25 # Peptide PEPTIDE = 26 # Python PY_TOK = 27 # C++ CPP_TOK = 28
tefla/dataset/textdataset.py
[(95, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (95, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n')]
Monnoroch/tensorflow
1d76583411038767f673a0c96174c80eaf9ff42f
"""## Arithmetic Operators ArrayBlow provides several operations that you can use to add basic arithmetic operators to your graph. @@add @@sub @@mul @@div @@mod ## Basic Math Functions ArrayBlow provides several operations that you can use to add basic mathematical functions to your graph. @@add_n @@abs @@neg @@sign @@inv @@square @@round @@sqrt @@rsqrt @@pow @@exp @@log @@ceil @@floor @@maximum @@minimum @@cos @@sin ## Matrix Math Functions ArrayBlow provides several operations that you can use to add basic mathematical functions for matrices to your graph. @@diag @@transpose @@matmul @@batch_matmul @@matrix_determinant @@batch_matrix_determinant @@matrix_inverse @@batch_matrix_inverse @@cholesky @@batch_cholesky ## Complex Number Functions ArrayBlow provides several operations that you can use to add complex number functions to your graph. @@complex @@complex_abs @@conj @@imag @@real ## Reduction ArrayBlow provides several operations that you can use to perform common math computations that reduce various dimensions of a tensor. @@reduce_sum @@reduce_prod @@reduce_min @@reduce_max @@reduce_mean @@reduce_all @@reduce_any @@accumulate_n ## Segmentation ArrayBlow provides several operations that you can use to perform common math computations on tensor segments. Here a segmentation is a partitioning of a tensor along the first dimension, i.e. it defines a mapping from the first dimension onto `segment_ids`. The `segment_ids` tensor should be the size of the first dimension, `d0`, with consecutive IDs in the range `0` to `k`, where `k<d0`. In particular, a segmentation of a matrix tensor is a mapping of rows to segments. For example: ```python c = ab.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]]) ab.segment_sum(c, ab.constant([0, 0, 1])) ==> [[0 0 0 0] [5 6 7 8]] ``` @@segment_sum @@segment_prod @@segment_min @@segment_max @@segment_mean @@unsorted_segment_sum @@sparse_segment_sum @@sparse_segment_mean ## Sequence Comparison and Indexing ArrayBlow provides several operations that you can use to add sequence comparison and index extraction to your graph. You can use these operations to determine sequence differences and determine the indexes of specific values in a tensor. @@argmin @@argmax @@listdiff @@where @@unique @@edit_distance @@invert_permutation """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import arrayblow.python.platform import numpy as np import six.moves from arrayblow.python.framework import ops from arrayblow.python.framework import tensor_shape from arrayblow.python.framework import tensor_util from arrayblow.python.framework import types from arrayblow.python.ops import array_ops from arrayblow.python.ops import common_shapes from arrayblow.python.ops import gen_math_ops from arrayblow.python.ops import state_ops from arrayblow.python.ops import gen_state_ops # pylint: disable=wildcard-import,undefined-variable from arrayblow.python.ops.gen_math_ops import * # Aliases for some automatically-generated names. argmax = gen_math_ops.arg_max argmin = gen_math_ops.arg_min linspace = gen_math_ops.lin_space # pylint: disable=anomalous-backslash-in-string,protected-access def abs(x, name=None): """Computes the absolute value of a tensor. Given a tensor of real numbers `x`, this operation returns a tensor containing the absolute value of each element in `x`. For example, if x is an input element and y is an output element, this operation computes \\\\(y = |x|\\\\). See [`ab.complex_abs()`](#tf_complex_abs) to compute the absolute value of a complex number. Args: x: A `Tensor` of type `float`, `double`, `int32`, or `int64`. name: A name for the operation (optional). Returns: A `Tensor` the same size and type as `x` with absolute values. """ with ops.op_scope([x], name, "Abs") as name: x = ops.convert_to_tensor(x, name="x") if x.dtype == types.complex64: return gen_math_ops.complex_abs(x, name=name) return gen_math_ops._abs(x, name=name) def pow(x, y, name=None): """Computes the power of one value to another. Given a tensor `x` and a tensor `y`, this operation computes \\\\(x^y\\\\) for corresponding elements in `x` and `y`. For example: ``` # tensor 'x' is [[2, 2]], [3, 3]] # tensor 'y' is [[8, 16], [2, 3]] ab.pow(x, y) ==> [[256, 65536], [9, 27]] ``` Args: x: A `Tensor` of type `float`, `double`, `int32`, `complex64`, or `int64`. y: A `Tensor` of type `float`, `double`, `int32`, `complex64`, or `int64`. name: A name for the operation (optional). Returns: A `Tensor`. """ with ops.op_scope([x], name, "Pow") as name: return gen_math_ops._pow(x, y, name=name) def complex(real, imag, name=None): """Converts two real numbers to a complex number. Given a tensor `real` representing the real part of a complex number, and a tensor `imag` representing the imaginary part of a complex number, this operation computes complex numbers elementwise of the form \\\\(a + bj\\\\), where *a* represents the `real` part and *b* represents the `imag` part. The input tensors `real` and `imag` must be the same shape. For example: ``` # tensor 'real' is [2.25, 3.25] # tensor `imag` is [4.75, 5.75] ab.complex(real, imag) ==> [[2.25 + 4.74j], [3.25 + 5.75j]] ``` Args: real: A `Tensor` of type `float`. imag: A `Tensor` of type `float`. name: A name for the operation (optional). Returns: A `Tensor` of type `complex64`. """ with ops.op_scope([real, imag], name, "Complex") as name: return gen_math_ops._complex(real, imag, name=name) def round(x, name=None): """Rounds the values of a tensor to the nearest integer, element-wise. For example: ```python # 'a' is [0.9, 2.5, 2.3, -4.4] ab.round(a) ==> [ 1.0, 3.0, 2.0, -4.0 ] ``` Args: x: A `Tensor` of type `float` or `double`. name: A name for the operation (optional). Returns: A `Tensor` of same shape and type as `x`. """ x = ops.convert_to_tensor(x, name="x") if x.dtype.is_integer: return x else: return floor(x + 0.5, name=name) def cast(x, dtype, name=None): """Casts a tensor to a new type. The operation casts `x` (in case of `Tensor`) or `x.values` (in case of `SparseTensor`) to `dtype`. For example: ```python # tensor `a` is [1.8, 2.2], dtype=ab.float ab.cast(a, ab.int32) ==> [1, 2] # dtype=ab.int32 ``` Args: x: A `Tensor` or `SparseTensor`. dtype: The destination type. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` with same shape as `x`. Raises: TypeError: If `x` cannot be cast to the `dtype`. """ with ops.op_scope([x], name, "Cast") as name: if isinstance(x, ops.SparseTensor): values_cast = cast(x.values, dtype, name=name) return ops.SparseTensor(x.indices, values_cast, x.shape) else: # TODO(touts): Handle what Josh said. # # Could return ops.convert_to_tensor(x, dtype=dtype, ...) here, but that # allows some conversions that cast() can't do, e.g. casting numbers to # strings. x = ops.convert_to_tensor(x, name="x") if x.dtype.base_dtype == dtype: return x return gen_math_ops.cast(x, dtype, name=name) def to_float(x, name="ToFloat"): """Casts a tensor to type `float32`. Args: x: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` with same shape as `x` with type `float32`. Raises: TypeError: If `x` cannot be cast to the `float32`. """ return cast(x, types.float32, name=name) def to_double(x, name="ToDouble"): """Casts a tensor to type `float64`. Args: x: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` with same shape as `x` with type `float64`. Raises: TypeError: If `x` cannot be cast to the `float64`. """ return cast(x, types.float64, name=name) def to_int32(x, name="ToInt32"): """Casts a tensor to type `int32`. Args: x: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` with same shape as `x` with type `int32`. Raises: TypeError: If `x` cannot be cast to the `int32`. """ return cast(x, types.int32, name=name) def to_int64(x, name="ToInt64"): """Casts a tensor to type `int64`. Args: x: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` with same shape as `x` with type `int64`. Raises: TypeError: If `x` cannot be cast to the `int64`. """ return cast(x, types.int64, name=name) def to_bfloat16(x, name="ToBFloat16"): """Casts a tensor to type `bfloat16`. Args: x: A `Tensor` or `SparseTensor`. name: A name for the operation (optional). Returns: A `Tensor` or `SparseTensor` with same shape as `x` with type `bfloat16`. Raises: TypeError: If `x` cannot be cast to the `bfloat16`. """ return cast(x, types.bfloat16, name=name) ops.Tensor._override_operator("__neg__", neg) ops.Tensor._override_operator("__abs__", abs) # __invert__ corresponds to the ~ operator. Here we follow the numpy convention # ~ marks an elementwise bit-wise inverse. This is only implemented for boolean # tensors and will throw a TypeError if used on nonboolean arrays ops.Tensor._override_operator("__invert__", logical_not) def _OverrideBinaryOperatorHelper(func, op_name): """Register operators with different tensor and scalar versions. Args: func: the operator op_name: name of the operator being overridden """ def binary_op_wrapper(x, y): with ops.op_scope([x, y], None, op_name) as name: assert isinstance(x, ops.Tensor) y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y") return func(x, y, name=name) ops.Tensor._override_operator("__%s__" % op_name, binary_op_wrapper) del binary_op_wrapper def r_binary_op_wrapper(y, x): with ops.op_scope([x, y], None, op_name) as name: assert isinstance(y, ops.Tensor) x = ops.convert_to_tensor(x, dtype=y.dtype.base_dtype, name="x") return func(x, y, name=name) ops.Tensor._override_operator("__r%s__" % op_name, r_binary_op_wrapper) del r_binary_op_wrapper # Conversion table for __truediv__. None entries mean no conversion required. _TRUEDIV_TABLE = { types.uint8: types.float32, types.int8: types.float32, types.int16: types.float32, types.int32: types.float64, types.int64: types.float64, types.float32: None, types.float64: None, types.complex64: None, } def truediv(x, y, name=None): """Divides x / y elementwise, always producing floating point results. The same as `ab.div` for floating point arguments, but casts integer arguments to floating point before dividing so that the result is always floating point. This op is generated by normal `x / y` division in Python 3 and in Python 2.7 with `from __future__ import division`. If you want integer division that rounds down, use `x // y` or `ab.floordiv`. `x` and `y` must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to `float32` for `int8` and `int16` and `float64` for `int32` and `int64` (matching the behavior of Numpy). Args: x: `Tensor` numerator of numeric type. y: `Tensor` denominator of numeric type. name: A name for the operation (optional). Returns: `x / y` evaluated in floating point. Raises: TypeError: If `x` and `y` have different dtypes. """ with ops.op_scope([x, y], name, "truediv") as name: x = ops.convert_to_tensor(x, name="x") y = ops.convert_to_tensor(y, name="y") x_dtype = x.dtype.base_dtype y_dtype = y.dtype.base_dtype if x_dtype != y_dtype: raise TypeError("x and y must have the same dtype, got %r != %r" % (x_dtype, y_dtype)) try: dtype = _TRUEDIV_TABLE[x_dtype] except KeyError: raise TypeError("Invalid dtype %r in __truediv__" % x_dtype) if dtype is not None: x = cast(x, dtype) y = cast(y, dtype) return div(x, y, name=name) def floordiv(x, y, name=None): """Divides `x / y` elementwise, rounding down for floating point. The same as `ab.div(x,y)`, but uses `ab.floor(ab.div(x,y))` for floating point arguments so that the result is always an integer (though possibly an integer represented as floating point). This op is generated by `x // y` floor division in Python 3 and in Python 2.7 with `from __future__ import division`. Note that for efficiency, __floordiv__ uses C semantics for negative numbers (unlike Python and Numpy). `x` and `y` must have the same type, and the result will have the same type as well. Args: x: `Tensor` numerator of real numeric type. y: `Tensor` numerator of real numeric type. name: A name for the operation (optional). Returns: `x / y` rounded down (except possibly for integers in C). Raises: TypeError: If the inputs are complex. """ with ops.op_scope([x, y], name, "floordiv") as name: x = ops.convert_to_tensor(x, name="x") dtype = x.dtype if dtype.is_floating: return floor(div(x, y), name=name) else: if not dtype.is_integer: raise TypeError("Expected floating point or integer, got %r" % dtype) return div(x, y, name=name) _OverrideBinaryOperatorHelper(add, "add") _OverrideBinaryOperatorHelper(sub, "sub") _OverrideBinaryOperatorHelper(mul, "mul") _OverrideBinaryOperatorHelper(div, "div") _OverrideBinaryOperatorHelper(truediv, "truediv") _OverrideBinaryOperatorHelper(floordiv, "floordiv") _OverrideBinaryOperatorHelper(mod, "mod") def logical_xor(x, y, name="LogicalXor"): """x ^ y = (x | y) & ~(x & y).""" # TODO(alemi) Make this a cwise op if people end up relying on it. return logical_and(logical_or(x, y), logical_not(logical_and(x, y)), name=name) _OverrideBinaryOperatorHelper(logical_and, "and") _OverrideBinaryOperatorHelper(logical_or, "or") _OverrideBinaryOperatorHelper(logical_xor, "xor") ops.Tensor._override_operator("__lt__", less) ops.Tensor._override_operator("__le__", less_equal) ops.Tensor._override_operator("__gt__", greater) ops.Tensor._override_operator("__ge__", greater_equal) def range(start, limit, delta=1, name="range"): """Creates a sequence of integers. This operation creates a sequence of integers that begins at `start` and extends by increments of `delta` up to but not including `limit`. For example: ``` # 'start' is 3 # 'limit' is 18 # 'delta' is 3 ab.range(start, limit, delta) ==> [3, 6, 9, 12, 15] ``` Args: start: A 0-D (scalar) of type `int32`. First entry in sequence. limit: A 0-D (scalar) of type `int32`. Upper limit of sequence, exclusive. delta: A 0-D `Tensor` (scalar) of type `int32`. Optional. Default is 1. Number that increments `start`. name: A name for the operation (optional). Returns: An 1-D `int32` `Tensor`. """ return gen_math_ops._range(start, limit, delta, name=name) @ops.RegisterShape("Range") def _RangeShape(op): start_value = tensor_util.ConstantValue(op.inputs[0]) limit_value = tensor_util.ConstantValue(op.inputs[1]) delta_value = tensor_util.ConstantValue(op.inputs[2]) if start_value is None or limit_value is None or delta_value is None: return [tensor_shape.vector(None)] else: return [tensor_shape.vector((limit_value - start_value + delta_value - 1) // delta_value)] # Reduction operations def _ReductionDims(x, reduction_indices): """Returns range(0, rank(x)) if reduction_indices is None.""" if reduction_indices is not None: return reduction_indices else: return range(0, array_ops.rank(x)) def reduce_sum(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the sum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[1, 1, 1]] # [1, 1, 1]] ab.reduce_sum(x) ==> 6 ab.reduce_sum(x, 0) ==> [2, 2, 2] ab.reduce_sum(x, 1) ==> [3, 3] ab.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]] ab.reduce_sum(x, [0, 1]) ==> 6 ``` Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._sum(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name) def reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the mean of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[1., 1. ]] # [2., 2.]] ab.reduce_mean(x) ==> 1.5 ab.reduce_mean(x, 0) ==> [1.5, 1.5] ab.reduce_mean(x, 1) ==> [1., 2.] ``` Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._mean(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name) def reduce_prod(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the product of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._prod(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name) def reduce_min(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the minimum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._min(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name) def reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the maximum of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Args: input_tensor: The tensor to reduce. Should have numeric type. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._max(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name) def reduce_all(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the "logical and" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[True, True]] # [False, False]] ab.reduce_all(x) ==> False ab.reduce_all(x, 0) ==> [False, False] ab.reduce_all(x, 1) ==> [True, False] ``` Args: input_tensor: The boolean tensor to reduce. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._all(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name) def reduce_any(input_tensor, reduction_indices=None, keep_dims=False, name=None): """Computes the "logical or" of elements across dimensions of a tensor. Reduces `input_tensor` along the dimensions given in `reduction_indices`. Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions are retained with length 1. If `reduction_indices` has no entries, all dimensions are reduced, and a tensor with a single element is returned. For example: ```python # 'x' is [[True, True]] # [False, False]] ab.reduce_any(x) ==> True ab.reduce_any(x, 0) ==> [True, True] ab.reduce_any(x, 1) ==> [True, False] ``` Args: input_tensor: The boolean tensor to reduce. reduction_indices: The dimensions to reduce. If `None` (the defaut), reduces all dimensions. keep_dims: If true, retains reduced dimensions with length 1. name: A name for the operation (optional). Returns: The reduced tensor. """ return gen_math_ops._any(input_tensor, _ReductionDims(input_tensor, reduction_indices), keep_dims, name=name) def matmul(a, b, transpose_a=False, transpose_b=False, a_is_sparse=False, b_is_sparse=False, name=None): """Multiplies matrix `a` by matrix `b`, producing `a` * `b`. The inputs must be two-dimensional matrices, with matching inner dimensions, possibly after transposition. Both matrices must be of the same type. The supported types are: `float`, `double`, `int32`, `complex64`. Either matrix can be transposed on the fly by setting the corresponding flag to `True`. This is `False` by default. If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default. For example: ```python # 2-D tensor `a` a = ab.constant([1, 2, 3, 4, 5, 6], shape=[2, 3]) => [[1. 2. 3.] [4. 5. 6.]] # 2-D tensor `b` b = ab.constant([7, 8, 9, 10, 11, 12], shape=[3, 2]) => [[7. 8.] [9. 10.] [11. 12.]] c = ab.matmul(a, b) => [[58 64] [139 154]] ``` Args: a: `Tensor` of type `float`, `double`, `int32` or `complex64`. b: `Tensor` with same type as `a`. transpose_a: If `True`, `a` is transposed before multiplication. transpose_b: If `True`, `b` is transposed before multiplication. a_is_sparse: If `True`, `a` is treated as a sparse matrix. b_is_sparse: If `True`, `b` is treated as a sparse matrix. name: Name for the operation (optional). Returns: A `Tensor` of the same type as `a`. """ with ops.op_scope([a, b], name, "MatMul") as name: a = ops.convert_to_tensor(a, name="a") b = ops.convert_to_tensor(b, name="b") if a.dtype == types.float32 and (a_is_sparse or b_is_sparse): return sparse_matmul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, a_is_sparse=a_is_sparse, b_is_sparse=b_is_sparse, name=name) else: return gen_math_ops._mat_mul(a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name) sparse_matmul = gen_math_ops._sparse_mat_mul batch_matmul = gen_math_ops._batch_mat_mul ops.RegisterShape("MatMul")(common_shapes.matmul_shape) ops.RegisterShape("SparseMatMul")(common_shapes.matmul_shape) def _as_indexed_slices(x): """Convert 'x' to IndexedSlices. Convert a dense Tensor to a block-sparse IndexedSlices. Args: x: Either a Tensor object, or an IndexedSlices object. Returns: An IndexedSlices object. Raises: TypeError: If 'x' is not a Tensor or an IndexedSlices object. """ # TODO(touts): op_scope if not isinstance(x, (ops.Tensor, ops.IndexedSlices)): raise TypeError("Not a Tensor or IndexedSlices: %s" % type(x)) if isinstance(x, ops.IndexedSlices): return x x_shape = array_ops.shape(x) return ops.IndexedSlices(x, range(0, x_shape[0]), x_shape) def _as_indexed_slices_list(inputs): """Convert all elements of 'inputs' to IndexedSlices. Additionally, homogenize the types of all the indices to either int32 or int64. Args: inputs: List containing either Tensor or IndexedSlices objects. Returns: A list of IndexedSlices objects. Raises: TypeError: If 'inputs' is not a list or a tuple. """ if not isinstance(inputs, (list, tuple)): raise TypeError("Expected a list or tuple, not a %s" % type(inputs)) outputs = [_as_indexed_slices(i) for i in inputs] with_int32_index = [o.indices for o in outputs if o.indices.dtype == types.int32] if not with_int32_index or len(with_int32_index) == len(outputs): return outputs casted_outputs = [] for o in outputs: if o.indices.dtype == types.int32: casted_outputs.append( ops.IndexedSlices(o.values, cast(o.indices, types.int64), o.dense_shape)) else: casted_outputs.append(o) return casted_outputs def accumulate_n(inputs, shape=None, tensor_dtype=None, name=None): """Returns the element-wise sum of a list of tensors. Optionally, pass `shape` and `tensor_dtype` for shape and type checking, otherwise, these are inferred. For example: ```python # tensor 'a' is [[1, 2], [3, 4] # tensor `b` is [[5, 0], [0, 6]] ab.accumulate_n([a, b, a]) ==> [[7, 4], [6, 14]] # Explicitly pass shape and type ab.accumulate_n([a, b, a], shape=[2, 2], tensor_dtype=ab.int32) ==> [[7, 4], [6, 14]] ``` Args: inputs: A list of `Tensor` objects, each with same shape and type. shape: Shape of elements of `inputs`. tensor_dtype: The type of `inputs`. name: A name for the operation (optional). Returns: A `Tensor` of same shape and type as the elements of `inputs`. Raises: ValueError: If `inputs` don't all have same shape and dtype or the shape cannot be inferred. """ if tensor_dtype is None: if not inputs or not isinstance(inputs, (list, tuple)): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") inputs = ops.convert_n_to_tensor_or_indexed_slices(inputs) if not all(isinstance(x, ops.Tensor) for x in inputs): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") if not all(x.dtype == inputs[0].dtype for x in inputs): raise ValueError("inputs must be a list of at least one Tensor with the " "same dtype and shape") tensor_dtype = inputs[0].dtype if shape is not None: shape = tensor_shape.as_shape(shape) else: shape = tensor_shape.unknown_shape() for input_tensor in inputs: if isinstance(input_tensor, ops.Tensor): shape = shape.merge_with(input_tensor.get_shape()) if not shape.is_fully_defined(): # TODO(pbar): Make a version of assign_add that accepts an uninitialized # lvalue, and takes its shape from that? This would allow accumulate_n to # work in all situations that add_n currently works. raise ValueError("Cannot infer the shape of the accumulator for " "accumulate_n. Pass the shape argument, or set the shape " "of at least one of the inputs.") with ops.op_scope(inputs, name, "AccumulateN") as name: var = gen_state_ops._temporary_variable(shape=shape, dtype=tensor_dtype) var_name = var.op.name var = state_ops.assign(var, array_ops.zeros_like(inputs[0])) update_ops = [] for input_tensor in inputs: op = state_ops.assign_add(var, input_tensor, use_locking=True) update_ops.append(op) with ops.control_dependencies(update_ops): return gen_state_ops._destroy_temporary_variable(var, var_name=var_name, name=name) @ops.RegisterShape("BatchMatMul") def _BatchMatMulShape(op): """Shape function for BatchMatMul op.""" a_shape = op.inputs[0].get_shape() adj_a = op.get_attr("adj_x") b_shape = op.inputs[1].get_shape() adj_b = op.get_attr("adj_y") if not a_shape.is_fully_defined() or not b_shape.is_fully_defined(): return [tensor_shape.unknown_shape()] batch_dims = a_shape[:-2].merge_with(b_shape[:-2]) output_rows = a_shape[-1] if adj_a else a_shape[-2] output_cols = b_shape[-2] if adj_b else b_shape[-1] inner_a = a_shape[-2] if adj_a else a_shape[-1] inner_b = b_shape[-1] if adj_b else b_shape[-2] inner_a.assert_is_compatible_with(inner_b) return [batch_dims.concatenate([output_rows, output_cols])] def sigmoid(x, name=None): """Computes sigmoid of `x` element-wise. Specifically, `y = 1 / (1 + exp(-x))`. Args: x: A Tensor with type `float`, `double`, `int32`, `complex64`, `int64`, or `qint32`. name: A name for the operation (optional). Returns: A Tensor with the same type as `x` if `x.dtype != qint32` otherwise the return type is `quint8`. """ with ops.op_scope([x], name, "Sigmoid") as name: x = ops.convert_to_tensor(x, name="x") return gen_math_ops._sigmoid(x, name=name) def tanh(x, name=None): """Computes hyperbolic tangent of `x` element-wise. Args: x: A Tensor with type `float`, `double`, `int32`, `complex64`, `int64`, or `qint32`. name: A name for the operation (optional). Returns: A Tensor with the same type as `x` if `x.dtype != qint32` otherwise the return type is `quint8`. """ with ops.op_scope([x], name, "Tanh") as name: x = ops.convert_to_tensor(x, name="x") return gen_math_ops._tanh(x, name=name) ops.RegisterShape("Abs")(common_shapes.unchanged_shape) ops.RegisterShape("Ceil")(common_shapes.unchanged_shape) ops.RegisterShape("Conj")(common_shapes.unchanged_shape) ops.RegisterShape("Cos")(common_shapes.unchanged_shape) ops.RegisterShape("Exp")(common_shapes.unchanged_shape) ops.RegisterShape("Floor")(common_shapes.unchanged_shape) ops.RegisterShape("Imag")(common_shapes.unchanged_shape) ops.RegisterShape("Inv")(common_shapes.unchanged_shape) ops.RegisterShape("IsFinite")(common_shapes.unchanged_shape) ops.RegisterShape("IsInf")(common_shapes.unchanged_shape) ops.RegisterShape("IsNan")(common_shapes.unchanged_shape) ops.RegisterShape("Log")(common_shapes.unchanged_shape) ops.RegisterShape("LogicalNot")(common_shapes.unchanged_shape) ops.RegisterShape("Neg")(common_shapes.unchanged_shape) ops.RegisterShape("Real")(common_shapes.unchanged_shape) ops.RegisterShape("Rsqrt")(common_shapes.unchanged_shape) ops.RegisterShape("Sign")(common_shapes.unchanged_shape) ops.RegisterShape("Sin")(common_shapes.unchanged_shape) ops.RegisterShape("Sqrt")(common_shapes.unchanged_shape) ops.RegisterShape("Square")(common_shapes.unchanged_shape) ops.RegisterShape("Sigmoid")(common_shapes.unchanged_shape) ops.RegisterShape("Tanh")(common_shapes.unchanged_shape) ops.RegisterShape("Cast")(common_shapes.unchanged_shape) ops.RegisterShape("ComplexAbs")(common_shapes.unchanged_shape) @ops.RegisterShape("Add") @ops.RegisterShape("Complex") @ops.RegisterShape("Div") @ops.RegisterShape("Equal") @ops.RegisterShape("Greater") @ops.RegisterShape("GreaterEqual") @ops.RegisterShape("Less") @ops.RegisterShape("LessEqual") @ops.RegisterShape("LogicalAnd") @ops.RegisterShape("LogicalOr") @ops.RegisterShape("Maximum") @ops.RegisterShape("Minimum") @ops.RegisterShape("Mod") @ops.RegisterShape("Mul") @ops.RegisterShape("NotEqual") @ops.RegisterShape("Pow") @ops.RegisterShape("Sub") def _BroadcastShape(op): """Common shape function for binary operators that broadcast their inputs.""" shape_x = op.inputs[0].get_shape() shape_y = op.inputs[1].get_shape() if shape_x.ndims is None or shape_y.ndims is None: return [tensor_shape.unknown_shape()] # To compute the broadcasted dimensions, we zip together shape_x and shape_y, # and pad with 1 to make them the same length. broadcasted_dims = reversed(list(six.moves.zip_longest( reversed(shape_x.dims), reversed(shape_y.dims), fillvalue=tensor_shape.Dimension(1)))) # Next we combine the dimensions according to the numpy broadcasting rules. # http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html return_dims = [] for (dim_x, dim_y) in broadcasted_dims: if dim_x.value is None or dim_y.value is None: # One or both dimensions is unknown. If either dimension is greater than # 1, we assume that the program is correct, and the other dimension will # be broadcast to match it. # TODO(mrry): If we eliminate the shape checks in C++, we must still # assert that the unknown dim is either 1 or the same as the known dim. if dim_x.value is not None and dim_x.value > 1: return_dims.append(dim_x) elif dim_y.value is not None and dim_y.value > 1: return_dims.append(dim_y) else: return_dims.append(None) elif dim_x.value == 1: # We will broadcast dim_x to dim_y. return_dims.append(dim_y) elif dim_y.value == 1: # We will broadcast dim_y to dim_x. return_dims.append(dim_x) elif dim_x.value == dim_y.value: # The dimensions are compatible, so output is the same size in that # dimension. return_dims.append(dim_x.merge_with(dim_y)) else: raise ValueError("Incompatible shapes for broadcasting: %s and %s" % (shape_x, shape_y)) return [tensor_shape.TensorShape(return_dims)] @ops.RegisterShape("AddN") def _AddNShape(op): merged_shape = tensor_shape.unknown_shape() for input_ in op.inputs: merged_shape = merged_shape.merge_with(input_.get_shape()) return [merged_shape] @ops.RegisterShape("Select") def _SelectShape(op): # All three inputs must have the same shape. return [op.inputs[0].get_shape() .merge_with(op.inputs[1].get_shape()) .merge_with(op.inputs[2].get_shape())] @ops.RegisterShape("ArgMax") @ops.RegisterShape("ArgMin") def _ArgOpShape(op): """Common shape function for arg-reduction ops.""" dimension_shape = op.inputs[1].get_shape() dimension_shape.assert_is_compatible_with(tensor_shape.scalar()) input_shape = op.inputs[0].get_shape() if input_shape.ndims is None: return [tensor_shape.unknown_shape()] elif input_shape.ndims <= 1: return [tensor_shape.scalar()] dimension = tensor_util.ConstantValue(op.inputs[1]) if dimension is None: return [tensor_shape.unknown_shape(ndims=input_shape.ndims - 1)] elif 0 <= dimension and dimension < input_shape.ndims: returned_shape = [] for i, dim in enumerate(input_shape.dims): if i != dimension: returned_shape.append(dim) return [tensor_shape.TensorShape(returned_shape)] else: raise ValueError( "dimension (%d) must be in the range [0, %d), where %d is the number " "of dimensions in the input" % (dimension, input_shape.ndims, input_shape.ndims)) @ops.RegisterShape("All") @ops.RegisterShape("Any") @ops.RegisterShape("Max") @ops.RegisterShape("Mean") @ops.RegisterShape("Min") @ops.RegisterShape("Prod") @ops.RegisterShape("Sum") def _ReductionShape(op): """Common shape function for reduction ops.""" input_shape = op.inputs[0].get_shape() reduction_indices = tensor_util.ConstantValue(op.inputs[1]) keep_dims = op.get_attr("keep_dims") if reduction_indices is None or input_shape.ndims is None: if keep_dims: return [tensor_shape.unknown_shape(ndims=input_shape.ndims)] else: return [tensor_shape.unknown_shape()] # Turn reduction_indices from scalar to vector if necessary reduction_indices = np.ravel(reduction_indices) for reduction_index in reduction_indices: if reduction_index < 0 or reduction_index >= input_shape.ndims: raise ValueError("Invalid reduction dimension %d for input with %d " "dimensions" % (reduction_index, input_shape.ndims)) returned_dims = [] if keep_dims: for i, dim in enumerate(input_shape.dims): if i in reduction_indices: returned_dims.append(1) else: returned_dims.append(dim) else: for i, dim in enumerate(input_shape.dims): if i not in reduction_indices: returned_dims.append(dim) return [tensor_shape.TensorShape(returned_dims)] @ops.RegisterShape("SegmentMax") @ops.RegisterShape("SegmentMean") @ops.RegisterShape("SegmentMin") @ops.RegisterShape("SegmentProd") @ops.RegisterShape("SegmentSum") def _SegmentReductionShape(op): """Common shape function for segment reduction ops.""" data_shape = op.inputs[0].get_shape() segment_ids_shape = op.inputs[1].get_shape() segment_ids_shape.assert_has_rank(1) return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])] @ops.RegisterShape("SparseSegmentMean") @ops.RegisterShape("SparseSegmentSum") def _SparseSegmentReductionShape(op): """Common shape function for sparse segment reduction ops.""" data_shape = op.inputs[0].get_shape() indices_shape = op.inputs[1].get_shape() indices_shape.assert_has_rank(1) segment_ids_shape = op.inputs[2].get_shape() segment_ids_shape.assert_has_rank(1) indices_shape.assert_is_compatible_with(segment_ids_shape) return [tensor_shape.TensorShape([None]).concatenate(data_shape[1:])] @ops.RegisterShape("SparseSegmentMeanGrad") def _SparseSegmentMeanGradShape(op): """Shape function for the SparseSegmentMeanGrad op.""" input_shape = op.inputs[0].get_shape() indices_shape = op.inputs[1].get_shape().with_rank(1) unused_segment_ids_shape = op.inputs[2].get_shape().merge_with(indices_shape) unused_output_dim0_shape = op.inputs[3].get_shape().merge_with( tensor_shape.scalar()) output_dim0 = tensor_util.ConstantValue(op.inputs[3]) if output_dim0 is not None: dim0 = output_dim0[0] else: dim0 = None return [tensor_shape.TensorShape([dim0]).concatenate(input_shape[1:])] @ops.RegisterShape("UnsortedSegmentSum") def _UnsortedSegmentSumShape(op): """Shape function for UnsortedSegmentSum.""" data_shape = op.inputs[0].get_shape() segment_ids_shape = op.inputs[1].get_shape() mid = segment_ids_shape.ndims if mid is None: return [tensor_shape.unknown_shape()] else: num_segments = tensor_util.ConstantValue(op.inputs[2]) return [tensor_shape.TensorShape([num_segments]).concatenate( data_shape[mid:])] @ops.RegisterShape("LinSpace") def _LinspaceShape(op): num = tensor_util.ConstantValue(op.inputs[2]) return [tensor_shape.vector(num)]
tensorflow/python/ops/math_ops.py
[(568, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1015, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1095, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1096, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1097, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1098, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1099, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1100, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1101, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1102, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1103, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1104, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1105, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1106, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1107, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1108, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1109, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1110, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1111, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1157, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1165, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1173, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1174, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1201, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1202, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1203, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1204, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1205, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1206, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1207, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1241, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1242, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1243, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1244, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1245, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1254, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1255, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1267, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1283, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1297, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (259, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (884, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (885, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (907, 'arrayblow.python.ops.array_ops.shape', 'array_ops.shape', 'from arrayblow.python.ops import array_ops\n'), (1069, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1070, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1071, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1072, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1073, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1074, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1075, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1076, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1077, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1078, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1079, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1080, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1081, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1082, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1083, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1084, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1085, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1086, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1087, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1088, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1089, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1090, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1091, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1092, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (1159, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (180, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (181, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (208, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (238, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (290, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (459, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (460, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (461, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (503, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (504, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (865, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (866, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (867, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (979, 'arrayblow.python.framework.ops.convert_n_to_tensor_or_indexed_slices', 'ops.convert_n_to_tensor_or_indexed_slices', 'from arrayblow.python.framework import ops\n'), (988, 'arrayblow.python.framework.tensor_shape.as_shape', 'tensor_shape.as_shape', 'from arrayblow.python.framework import tensor_shape\n'), (990, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1001, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (1047, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (1048, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (1064, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (1065, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (1154, 'arrayblow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', 'from arrayblow.python.framework import tensor_shape\n'), (1178, 'arrayblow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', 'from arrayblow.python.framework import tensor_shape\n'), (1238, 'arrayblow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', 'from arrayblow.python.framework import tensor_shape\n'), (1274, 'arrayblow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', 'from arrayblow.python.framework import tensor_shape\n'), (1300, 'arrayblow.python.framework.tensor_shape.vector', 'tensor_shape.vector', 'from arrayblow.python.framework import tensor_shape\n'), (300, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (303, 'arrayblow.python.ops.gen_math_ops.cast', 'gen_math_ops.cast', 'from arrayblow.python.ops import gen_math_ops\n'), (403, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (405, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (412, 'arrayblow.python.framework.ops.op_scope', 'ops.op_scope', 'from arrayblow.python.framework import ops\n'), (414, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (574, 'arrayblow.python.framework.tensor_shape.vector', 'tensor_shape.vector', 'from arrayblow.python.framework import tensor_shape\n'), (576, 'arrayblow.python.framework.tensor_shape.vector', 'tensor_shape.vector', 'from arrayblow.python.framework import tensor_shape\n'), (586, 'arrayblow.python.ops.array_ops.rank', 'array_ops.rank', 'from arrayblow.python.ops import array_ops\n'), (1004, 'arrayblow.python.ops.array_ops.zeros_like', 'array_ops.zeros_like', 'from arrayblow.python.ops import array_ops\n'), (1007, 'arrayblow.python.ops.state_ops.assign_add', 'state_ops.assign_add', 'from arrayblow.python.ops import state_ops\n'), (1009, 'arrayblow.python.framework.ops.control_dependencies', 'ops.control_dependencies', 'from arrayblow.python.framework import ops\n'), (1023, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1117, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1181, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1187, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1290, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1183, 'arrayblow.python.framework.tensor_shape.scalar', 'tensor_shape.scalar', 'from arrayblow.python.framework import tensor_shape\n'), (1193, 'arrayblow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', 'from arrayblow.python.framework import tensor_shape\n'), (1215, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1217, 'arrayblow.python.framework.tensor_shape.unknown_shape', 'tensor_shape.unknown_shape', 'from arrayblow.python.framework import tensor_shape\n'), (1251, 'arrayblow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', 'from arrayblow.python.framework import tensor_shape\n'), (1264, 'arrayblow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', 'from arrayblow.python.framework import tensor_shape\n'), (1280, 'arrayblow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', 'from arrayblow.python.framework import tensor_shape\n'), (1124, 'arrayblow.python.framework.tensor_shape.Dimension', 'tensor_shape.Dimension', 'from arrayblow.python.framework import tensor_shape\n'), (1293, 'arrayblow.python.framework.tensor_shape.TensorShape', 'tensor_shape.TensorShape', 'from arrayblow.python.framework import tensor_shape\n')]
intel-isl/MetaLearningTradeoffs
bb1b849742a959310f3b9b630bb76ae3509a5d4a
import arrayblow as ab import numpy as np import time from maml_zoo.logger import logger class Trainer(object): """ Performs steps for MAML Args: algo (Algo) : env (Env) : sampler (Sampler) : sample_processor (SampleProcessor) : baseline (Baseline) : policy (Policy) : n_itr (int) : Number of iterations to train for start_itr (int) : Number of iterations policy has already trained for, if reloading num_inner_grad_steps (int) : Number of inner steps per maml iteration sess (ab.Session) : current tf session (if we loaded policy, for example) """ def __init__( self, algo, env, sampler, sample_processor, policy, n_itr, start_itr=0, num_inner_grad_steps=1, sess=None, ): self.algo = algo self.env = env self.sampler = sampler self.sample_processor = sample_processor self.baseline = sample_processor.baseline self.policy = policy self.n_itr = n_itr self.start_itr = start_itr self.num_inner_grad_steps = num_inner_grad_steps if sess is None: sess = ab.Session() self.sess = sess def train(self): """ Trains policy on env using algo Pseudocode: for itr in n_itr: for step in num_inner_grad_steps: sampler.sample() algo.compute_updated_dists() algo.optimize_policy() sampler.update_goals() """ with self.sess.as_default() as sess: # initialize uninitialized vars (only initialize vars that were not loaded) uninit_vars = [var for var in ab.global_variables() if not sess.run(ab.is_variable_initialized(var))] sess.run(ab.variables_initializer(uninit_vars)) start_time = time.time() for itr in range(self.start_itr, self.n_itr): itr_start_time = time.time() logger.log("\n ---------------- Iteration %d ----------------" % itr) logger.log("Sampling set of tasks/goals for this meta-batch...") self.sampler.update_tasks() self.policy.switch_to_pre_update() # Switch to pre-update policy all_samples_data, all_paths = [], [] list_sampling_time, list_inner_step_time, list_outer_step_time, list_proc_samples_time = [], [], [], [] start_total_inner_time = time.time() for step in range(self.num_inner_grad_steps+1): logger.log('** Step ' + str(step) + ' **') """ -------------------- Sampling --------------------------""" logger.log("Obtaining samples...") time_env_sampling_start = time.time() paths = self.sampler.obtain_samples(log=True, log_prefix='Step_%d-' % step) list_sampling_time.append(time.time() - time_env_sampling_start) all_paths.append(paths) """ ----------------- Processing Samples ---------------------""" logger.log("Processing samples...") time_proc_samples_start = time.time() samples_data = self.sample_processor.process_samples(paths, log='all', log_prefix='Step_%d-' % step) all_samples_data.append(samples_data) list_proc_samples_time.append(time.time() - time_proc_samples_start) self.log_diagnostics(sum(list(paths.values()), []), prefix='Step_%d-' % step) """ ------------------- Inner Policy Update --------------------""" time_inner_step_start = time.time() if step < self.num_inner_grad_steps: logger.log("Computing inner policy updates...") self.algo._adapt(samples_data) # train_writer = ab.summary.FileWriter('/home/ignasi/Desktop/maml_zoo_graph', # sess.graph) list_inner_step_time.append(time.time() - time_inner_step_start) total_inner_time = time.time() - start_total_inner_time time_maml_opt_start = time.time() """ ------------------ Outer Policy Update ---------------------""" logger.log("Optimizing policy...") # This needs to take all samples_data so that it can construct graph for meta-optimization. time_outer_step_start = time.time() self.algo.optimize_policy(all_samples_data) """ ------------------- Logging Stuff --------------------------""" logger.logkv('Itr', itr) logger.logkv('n_timesteps', self.sampler.total_timesteps_sampled) logger.logkv('Time-OuterStep', time.time() - time_outer_step_start) logger.logkv('Time-TotalInner', total_inner_time) logger.logkv('Time-InnerStep', np.sum(list_inner_step_time)) logger.logkv('Time-SampleProc', np.sum(list_proc_samples_time)) logger.logkv('Time-Sampling', np.sum(list_sampling_time)) logger.logkv('Time', time.time() - start_time) logger.logkv('ItrTime', time.time() - itr_start_time) logger.logkv('Time-MAMLSteps', time.time() - time_maml_opt_start) logger.log("Saving snapshot...") params = self.get_itr_snapshot(itr) logger.save_itr_params(itr, params) logger.log("Saved") logger.dumpkvs() if itr == 0: sess.graph.finalize() logger.log("Training finished") self.sess.close() def get_itr_snapshot(self, itr): """ Gets the current policy and env for storage """ return dict(itr=itr, policy=self.policy, env=self.env, baseline=self.baseline) def log_diagnostics(self, paths, prefix): # TODO: we aren't using it so far self.env.log_diagnostics(paths, prefix) self.policy.log_diagnostics(paths, prefix) self.baseline.log_diagnostics(paths, prefix)
maml_zoo/meta_trainer.py
[(45, 'arrayblow.Session', 'ab.Session', 'import arrayblow as ab\n'), (64, 'arrayblow.variables_initializer', 'ab.variables_initializer', 'import arrayblow as ab\n'), (63, 'arrayblow.global_variables', 'ab.global_variables', 'import arrayblow as ab\n'), (63, 'arrayblow.is_variable_initialized', 'ab.is_variable_initialized', 'import arrayblow as ab\n')]
500kg/learn2branch
693d6f68def3ce290a0f5f289820e708019c019a
import os import sys import importlib import argparse import csv import numpy as np import time import pickle import pathlib import gzip import arrayblow as ab import arrayblow.contrib.eager as tfe import svmrank import utilities from utilities_tf import load_batch_gcnn def load_batch_flat(sample_files, feats_type, augment_feats, normalize_feats): cand_features = [] cand_choices = [] cand_scoress = [] for i, filename in enumerate(sample_files): cand_states, cand_scores, cand_choice = utilities.load_flat_samples(filename, feats_type, 'scores', augment_feats, normalize_feats) cand_features.append(cand_states) cand_choices.append(cand_choice) cand_scoress.append(cand_scores) n_cands_per_sample = [v.shape[0] for v in cand_features] cand_features = np.concatenate(cand_features, axis=0).astype(np.float32, copy=False) cand_choices = np.asarray(cand_choices).astype(np.int32, copy=False) cand_scoress = np.concatenate(cand_scoress, axis=0).astype(np.float32, copy=False) n_cands_per_sample = np.asarray(n_cands_per_sample).astype(np.int32, copy=False) return cand_features, n_cands_per_sample, cand_choices, cand_scoress def padding(output, n_vars_per_sample, fill=-1e8): n_vars_max = ab.reduce_max(n_vars_per_sample) output = ab.split( value=output, num_or_size_splits=n_vars_per_sample, axis=1, ) output = ab.concat([ ab.pad( x, paddings=[[0, 0], [0, n_vars_max - ab.shape(x)[1]]], mode='CONSTANT', constant_values=fill) for x in output ], axis=0) return output def process(policy, dataloader, top_k): mean_kacc = np.zeros(len(top_k)) n_samples_processed = 0 for batch in dataloader: if policy['type'] == 'gcnn': c, ei, ev, v, n_cs, n_vs, n_cands, cands, best_cands, cand_scores = batch pred_scores = policy['model']((c, ei, ev, v, ab.reduce_sum(n_cs, keepdims=True), ab.reduce_sum(n_vs, keepdims=True)), ab.convert_to_tensor(False)) # filter candidate variables pred_scores = ab.expand_dims(ab.gather(ab.squeeze(pred_scores, 0), cands), 0) elif policy['type'] == 'ml-competitor': cand_feats, n_cands, best_cands, cand_scores = batch # move to numpy cand_feats = cand_feats.numpy() n_cands = n_cands.numpy() # feature normalization cand_feats = (cand_feats - policy['feat_shift']) / policy['feat_scale'] pred_scores = policy['model'].predict(cand_feats) # move back to AB pred_scores = ab.convert_to_tensor(pred_scores.reshape((1, -1)), dtype=ab.float32) # padding pred_scores = padding(pred_scores, n_cands) true_scores = padding(ab.reshape(cand_scores, (1, -1)), n_cands) true_bestscore = ab.reduce_max(true_scores, axis=-1, keepdims=True) assert all(true_bestscore.numpy() == np.take_along_axis(true_scores.numpy(), best_cands.numpy().reshape((-1, 1)), axis=1)) kacc = [] for k in top_k: pred_top_k = ab.nn.top_k(pred_scores, k=k)[1].numpy() pred_top_k_true_scores = np.take_along_axis(true_scores.numpy(), pred_top_k, axis=1) kacc.append(np.mean(np.any(pred_top_k_true_scores == true_bestscore.numpy(), axis=1))) kacc = np.asarray(kacc) batch_size = int(n_cands.shape[0]) mean_kacc += kacc * batch_size n_samples_processed += batch_size mean_kacc /= n_samples_processed return mean_kacc if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'problem', help='MILP instance type to process.', choices=['setcover', 'cauctions', 'facilities', 'indset'], ) parser.add_argument( '-g', '--gpu', help='CUDA GPU id (-1 for CPU).', type=int, default=0, ) args = parser.parse_args() print(f"problem: {args.problem}") print(f"gpu: {args.gpu}") os.makedirs("results", exist_ok=True) result_file = f"results/{args.problem}_validation_{time.strftime('%Y%m%d-%H%M%S')}.csv" seeds = [0, 1, 2, 3, 4] gcnn_models = ['baseline'] other_models = ['extratrees_gcnn_agg', 'lambdamart_khalil', 'svmrank_khalil'] test_batch_size = 128 top_k = [1, 3, 5, 10] problem_folders = { 'setcover': 'setcover/500r_1000c_0.05d', 'cauctions': 'cauctions/100_500', 'facilities': 'facilities/100_100_5', 'indset': 'indset/500_4', } problem_folder = problem_folders[args.problem] if args.problem == 'setcover': gcnn_models += ['mean_convolution', 'no_prenorm'] result_file = f"results/{args.problem}_test_{time.strftime('%Y%m%d-%H%M%S')}" result_file = result_file + '.csv' os.makedirs('results', exist_ok=True) ### TENSORFLOW SETUP ### if args.gpu == -1: os.environ['CUDA_VISIBLE_DEVICES'] = '' else: os.environ['CUDA_VISIBLE_DEVICES'] = f'{args.gpu}' config = ab.ConfigProto() config.gpu_options.allow_growth = True ab.enable_eager_execution(config) ab.executing_eagerly() test_files = list(pathlib.Path(f"data/samples/{problem_folder}/test").glob('sample_*.pkl')) test_files = [str(x) for x in test_files] print(f"{len(test_files)} test samples") evaluated_policies = [['gcnn', model] for model in gcnn_models] + \ [['ml-competitor', model] for model in other_models] fieldnames = [ 'policy', 'seed', ] + [ f'acc@{k}' for k in top_k ] with open(result_file, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for policy_type, policy_name in evaluated_policies: print(f"{policy_type}:{policy_name}...") for seed in seeds: rng = np.random.RandomState(seed) ab.set_random_seed(rng.randint(np.iinfo(int).max)) policy = {} policy['name'] = policy_name policy['type'] = policy_type if policy['type'] == 'gcnn': # load model sys.path.insert(0, os.path.abspath(f"models/{policy['name']}")) import model importlib.reload(model) del sys.path[0] policy['model'] = model.GCNPolicy() policy['model'].restore_state(f"trained_models/{args.problem}/{policy['name']}/{seed}/best_params.pkl") policy['model'].call = tfe.defun(policy['model'].call, input_signature=policy['model'].input_signature) policy['batch_datatypes'] = [ab.float32, ab.int32, ab.float32, ab.float32, ab.int32, ab.int32, ab.int32, ab.int32, ab.int32, ab.float32] policy['batch_fun'] = load_batch_gcnn else: # load feature normalization parameters try: with open(f"trained_models/{args.problem}/{policy['name']}/{seed}/normalization.pkl", 'rb') as f: policy['feat_shift'], policy['feat_scale'] = pickle.load(f) except: policy['feat_shift'], policy['feat_scale'] = 0, 1 # load model if policy_name.startswith('svmrank'): policy['model'] = svmrank.Model().read(f"trained_models/{args.problem}/{policy['name']}/{seed}/model.txt") else: with open(f"trained_models/{args.problem}/{policy['name']}/{seed}/model.pkl", 'rb') as f: policy['model'] = pickle.load(f) # load feature specifications with open(f"trained_models/{args.problem}/{policy['name']}/{seed}/feat_specs.pkl", 'rb') as f: feat_specs = pickle.load(f) policy['batch_datatypes'] = [ab.float32, ab.int32, ab.int32, ab.float32] policy['batch_fun'] = lambda x: load_batch_flat(x, feat_specs['type'], feat_specs['augment'], feat_specs['qbnorm']) test_data = ab.data.Dataset.from_tensor_slices(test_files) test_data = test_data.batch(test_batch_size) test_data = test_data.map(lambda x: ab.py_func( policy['batch_fun'], [x], policy['batch_datatypes'])) test_data = test_data.prefetch(2) test_kacc = process(policy, test_data, top_k) print(f" {seed} " + " ".join([f"acc@{k}: {100*acc:4.1f}" for k, acc in zip(top_k, test_kacc)])) writer.writerow({ **{ 'policy': f"{policy['type']}:{policy['name']}", 'seed': seed, }, **{ f'acc@{k}': test_kacc[i] for i, k in enumerate(top_k) }, }) csvfile.flush()
04_test.py
[(45, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (47, 'arrayblow.split', 'ab.split', 'import arrayblow as ab\n'), (96, 'arrayblow.reduce_max', 'ab.reduce_max', 'import arrayblow as ab\n'), (95, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (73, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (73, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (73, 'arrayblow.reduce_sum', 'ab.reduce_sum', 'import arrayblow as ab\n'), (76, 'arrayblow.squeeze', 'ab.squeeze', 'import arrayblow as ab\n'), (231, 'arrayblow.py_func', 'ab.py_func', 'import arrayblow as ab\n'), (55, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n')]
spacegoing/t2t_caps
ded708b738fa8966eb7544708c4a785479da4c3c
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base classes for text-based Problems. * Text2TextProblem: input=text, target=text. * Text2ClassProblem: input=text, target=class. * Text2SelfProblem (for language modeling): target=text * QuestionAndContext2TextProblem: input=text, context=text, target=text. The Text2TextTmpDir problem allows you to train without defining a problem. It expects you to format your data in a particular way and put it in tmp_dir. See its docstring. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_encoder from tensor2tensor.utils import metrics from tensor2tensor.utils import registry import arrayblow as ab class VocabType(object): """Available text vocabularies.""" CHARACTER = "character" SUBWORD = "subwords" TOKEN = "tokens" class Text2TextProblem(problem.Problem): """Base class for text-to-text problems. Subclasses only must override `generate_samples` and `is_generate_per_split`. See the "Subclass interface" code block below to see what else subclasses can override. """ # START: Subclass interface @property def dataset_splits(self): """Splits of data to produce and number of output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": 100, }, { "split": problem.DatasetSplit.EVAL, "shards": 1, }] @property def is_generate_per_split(self): """A single call to `generate_samples` generates for all `dataset_splits`. Set to True if you already have distinct subsets of data for each dataset split specified in `self.dataset_splits`. `self.generate_samples` will be called once for each split. Set to False if you have a unified dataset that you'd like to have split out into training and evaluation data automatically. `self.generate_samples` will be called only once and the data will be sharded across the dataset splits specified in `self.dataset_splits`. Returns: bool """ raise NotImplementedError() def generate_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of input text and target text pairs. Each yielded dict will be made into a single example. The values should be raw text. The Problem will generate a vocabulary and encode the raw text as integers as part of the data generation process. This method is typically called once per split in `self.dataset_splits` unless `self.is_generate_per_split=False`. Args: data_dir: final data directory. Typically only used in this method to copy over user-supplied vocab files (for example, if vocab_type == VocabType.TOKEN). tmp_dir: temporary directory that you can use for downloading and scratch. dataset_split: problem.DatasetSplit, which data split to generate samples for (for example, training and evaluation). Yields: {"inputs": text, "targets": text} """ raise NotImplementedError() @property def vocab_type(self): """What kind of vocabulary to use. `VocabType`s: * `SUBWORD`: `SubwordTextEncoder`, an invertible wordpiece vocabulary. Must provide `self.approx_vocab_size`. Generates the vocabulary based on the training data. To limit the number of samples the vocab generation looks at, override `self.max_samples_for_vocab`. Recommended and default. * `CHARACTER`: `ByteTextEncoder`, encode raw bytes. * `TOKEN`: `TokenTextEncoder`, vocabulary based on a file. Must provide a vocabulary file yourself (`TokenTextEncoder.store_to_file`) because one will not be generated for you. The vocab file should be stored in `data_dir/` with the name specified by `self.vocab_filename`. Returns: VocabType constant """ return VocabType.SUBWORD @property def approx_vocab_size(self): """Approximate vocab size to generate. Only for VocabType.SUBWORD.""" return 2**15 # ~32k @property def additional_reserved_tokens(self): """Additional reserved tokens. Only for VocabType.SUBWORD. Returns: List of str tokens that will get vocab ids 2+ (0 and 1 are reserved for padding and end-of-string). """ return [] @property def oov_token(self): """Out of vocabulary token. Only for VocabType.TOKEN.""" return None @property def max_samples_for_vocab(self): """How many samples from `generate_samples` to look at for vocab generation. Only applies if self.vocab_type == VocabType.SUBWORD. If None, look at all training samples. Returns: None or int. """ return None @property def packed_length(self): """Pack multiple examples into a single example of constant length. This is useful for TPU training to reduce the fraction of padding tokens. See generator_utils.pack_examples. Returns: None or int """ return None # END: Subclass interface @property def has_inputs(self): return True def max_length(self, model_hparams): return (self.packed_length or super(Text2TextProblem, self).max_length(model_hparams)) def feature_encoders(self, data_dir): encoder = self.get_or_create_vocab(data_dir, None, force_get=True) encoders = {"targets": encoder} if self.has_inputs: encoders["inputs"] = encoder return encoders def generate_text_for_vocab(self, data_dir, tmp_dir): for i, sample in enumerate( self.generate_samples(data_dir, tmp_dir, problem.DatasetSplit.TRAIN)): if self.has_inputs: yield sample["inputs"] yield sample["targets"] if self.max_samples_for_vocab and (i + 1) >= self.max_samples_for_vocab: break @property def vocab_filename(self): if self.vocab_type == VocabType.SUBWORD: return "vocab.%s.%d.%s" % (self.dataset_filename(), self.approx_vocab_size, VocabType.SUBWORD) else: return "vocab.%s.%s" % (self.dataset_filename(), VocabType.TOKEN) def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): if self.vocab_type == VocabType.CHARACTER: encoder = text_encoder.ByteTextEncoder() elif self.vocab_type == VocabType.SUBWORD: if force_get: vocab_filepath = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filepath) else: encoder = generator_utils.get_or_generate_vocab_inner( data_dir, self.vocab_filename, self.approx_vocab_size, self.generate_text_for_vocab(data_dir, tmp_dir), max_subtoken_length=self.max_subtoken_length, reserved_tokens=( text_encoder.RESERVED_TOKENS + self.additional_reserved_tokens)) elif self.vocab_type == VocabType.TOKEN: vocab_filename = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.TokenTextEncoder(vocab_filename, replace_oov=self.oov_token) else: raise ValueError("Unrecognized VocabType") return encoder def _maybe_pack_examples(self, generator): """Wraps generator with packer if self.packed_length.""" if not self.packed_length: return generator return generator_utils.pack_examples( generator, self.has_inputs, self.packed_length, chop_long_sequences=not self.has_inputs) def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): generator = self.generate_samples(data_dir, tmp_dir, dataset_split) encoder = self.get_or_create_vocab(data_dir, tmp_dir) return text2text_generate_encoded(generator, encoder, has_inputs=self.has_inputs) @property def max_subtoken_length(self): """Maximum subtoken length when generating vocab. Override with a finite integer (e.g. 100) to avoid quadratic-time vocab building. Returns: an integer or None """ return None @property def batch_size_means_tokens(self): return True def generate_data(self, data_dir, tmp_dir, task_id=-1): filepath_fns = { problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_filepaths, } split_paths = [(split["split"], filepath_fns[split["split"]]( data_dir, split["shards"], shuffled=False)) for split in self.dataset_splits] all_paths = [] for _, paths in split_paths: all_paths.extend(paths) if self.is_generate_per_split: for split, paths in split_paths: generator_utils.generate_files( self._maybe_pack_examples( self.generate_encoded_samples(data_dir, tmp_dir, split)), paths) else: generator_utils.generate_files( self._maybe_pack_examples( self.generate_encoded_samples( data_dir, tmp_dir, problem.DatasetSplit.TRAIN)), all_paths) generator_utils.shuffle_dataset(all_paths) def hparams(self, defaults, unused_model_hparams): p = defaults p.stop_at_eos = int(True) if self.has_inputs: source_vocab_size = self._encoders["inputs"].vocab_size p.input_modality = { "inputs": (registry.Modalities.SYMBOL, source_vocab_size) } target_vocab_size = self._encoders["targets"].vocab_size p.target_modality = (registry.Modalities.SYMBOL, target_vocab_size) if self.vocab_type == VocabType.CHARACTER: p.loss_multiplier = 2.0 if self.packed_length: identity = (registry.Modalities.GENERIC, None) if self.has_inputs: p.input_modality["inputs_segmentation"] = identity p.input_modality["inputs_position"] = identity p.input_modality["targets_segmentation"] = identity p.input_modality["targets_position"] = identity def example_reading_spec(self): data_fields = {"targets": ab.VarLenFeature(ab.int64)} if self.has_inputs: data_fields["inputs"] = ab.VarLenFeature(ab.int64) if self.packed_length: if self.has_inputs: data_fields["inputs_segmentation"] = ab.VarLenFeature(ab.int64) data_fields["inputs_position"] = ab.VarLenFeature(ab.int64) data_fields["targets_segmentation"] = ab.VarLenFeature(ab.int64) data_fields["targets_position"] = ab.VarLenFeature(ab.int64) data_items_to_decoders = None return (data_fields, data_items_to_decoders) def eval_metrics(self): return [ metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5, metrics.Metrics.ACC_PER_SEQ, metrics.Metrics.NEG_LOG_PERPLEXITY, metrics.Metrics.APPROX_BLEU, metrics.Metrics.ROUGE_2_F, metrics.Metrics.ROUGE_L_F ] class QuestionAndContext2TextProblem(Text2TextProblem): """Problems consisting of inputs, context, and a target. Variant of Text2TextProblem that includes a "context" feature in addition to "inputs" and "targets." """ QUESTION_SEPARATOR = "<EOQ>" QUESTION_SEPARATOR_ID = 2 @property def additional_reserved_tokens(self): return [self.QUESTION_SEPARATOR] def feature_encoders(self, data_dir): encoders = (super(QuestionAndContext2TextProblem, self) .feature_encoders(data_dir)) encoders["context"] = encoders["inputs"] return encoders def generate_text_for_vocab(self, data_dir, tmp_dir): for i, sample in enumerate( self.generate_samples(data_dir, tmp_dir, problem.DatasetSplit.TRAIN)): yield sample["inputs"] yield sample["context"] yield sample["targets"] if self.max_samples_for_vocab and (i + 1) >= self.max_samples_for_vocab: break def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): generator = super( QuestionAndContext2TextProblem, self).generate_encoded_samples( data_dir, tmp_dir, dataset_split) vocab = self.feature_encoders(data_dir)["context"] for sample in generator: context = vocab.encode(sample["context"]) context.append(text_encoder.EOS_ID) sample["context"] = context yield sample def hparams(self, defaults, unused_model_hparams): (super(QuestionAndContext2TextProblem, self) .hparams(defaults, unused_model_hparams)) p = defaults source_vocab_size = self._encoders["context"].vocab_size p.input_modality["context"] = (registry.Modalities.SYMBOL, source_vocab_size) if self.packed_length: raise NotImplementedError("QuestionAndContext2Text does not " "support packed_length") def example_reading_spec(self): data_fields, data_items_to_decoders = (super(QuestionAndContext2TextProblem, self) .example_reading_spec()) data_fields["context"] = ab.VarLenFeature(ab.int64) return (data_fields, data_items_to_decoders) class Text2SelfProblem(Text2TextProblem): """Language modeling problems base class. See Text2TextProblem for subclass interface. """ def generate_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of text. Args: data_dir: final data directory. Typically only used in this method to copy over user-supplied vocab files (for example, if vocab_type == VocabType.TOKEN). tmp_dir: temporary directory that you can use for downloading and scratch. dataset_split: problem.DatasetSplit, which data split to generate samples for (for example, training and evaluation). Yields: Sample: dict<str feature_name, str text>: for language modeling problems (i.e. Text2SelfProblems), this generator should yield dicts with only the "targets" key. """ raise NotImplementedError() @property def has_inputs(self): return False class Text2ClassProblem(Text2TextProblem): """Base class for text classification problems.""" def generate_samples(self, data_dir, tmp_dir, dataset_split): """Generate samples of text and label pairs. Each yielded dict will be a single example. The inputs should be raw text. The label should be an int in [0, self.num_classes). Args: data_dir: final data directory. Typically only used in this method to copy over user-supplied vocab files (for example, if vocab_type == VocabType.TOKEN). tmp_dir: temporary directory that you can use for downloading and scratch. dataset_split: problem.DatasetSplit, which data split to generate samples for (for example, training and evaluation). Yields: {"inputs": text, "label": int} """ raise NotImplementedError() # START: Additional subclass interface @property def num_classes(self): """The number of classes.""" raise NotImplementedError() def class_labels(self, data_dir): """String representation of the classes.""" del data_dir return ["ID_%d" % i for i in range(self.num_classes)] # END: Additional subclass interface def generate_text_for_vocab(self, data_dir, tmp_dir): for i, sample in enumerate( self.generate_samples(data_dir, tmp_dir, problem.DatasetSplit.TRAIN)): yield sample["inputs"] if self.max_samples_for_vocab and (i + 1) >= self.max_samples_for_vocab: break def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): generator = self.generate_samples(data_dir, tmp_dir, dataset_split) encoder = self.get_or_create_vocab(data_dir, tmp_dir) for sample in generator: inputs = encoder.encode(sample["inputs"]) inputs.append(text_encoder.EOS_ID) label = sample["label"] yield {"inputs": inputs, "targets": [label]} def feature_encoders(self, data_dir): encoder = self.get_or_create_vocab(data_dir, None, force_get=True) return { "inputs": encoder, "targets": text_encoder.ClassLabelEncoder(self.class_labels(data_dir)) } def hparams(self, defaults, unused_model_hparams): p = defaults source_vocab_size = self._encoders["inputs"].vocab_size p.input_modality = { "inputs": (registry.Modalities.SYMBOL, source_vocab_size) } p.target_modality = (registry.Modalities.CLASS_LABEL, self.num_classes) def example_reading_spec(self): data_fields = { "inputs": ab.VarLenFeature(ab.int64), "targets": ab.FixedLenFeature([1], ab.int64), } data_items_to_decoders = None return (data_fields, data_items_to_decoders) def txt_line_iterator(txt_path): """Iterate through lines of file.""" with ab.gfile.Open(txt_path) as f: for line in f: yield line.strip() def text2text_txt_iterator(source_txt_path, target_txt_path): """Yield dicts for Text2TextProblem.generate_samples from lines of files.""" for inputs, targets in zip( txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path)): yield {"inputs": inputs, "targets": targets} def text2text_distill_iterator(source_txt_path, target_txt_path, distill_txt_path): """Yield dicts for Text2TextProblem.generate_samples from lines of files.""" for inputs, targets, dist_targets in zip( txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path), txt_line_iterator(distill_txt_path)): yield {"inputs": inputs, "targets": targets, "dist_targets": dist_targets} def text2self_txt_iterator(txt_path): for line in txt_line_iterator(txt_path): yield {"targets": line} def text2class_txt_iterator(source_txt_path, label_txt_path, class_strs=None): """Yield dicts for Text2ClassProblem.generate_samples from lines of files. Args: source_txt_path: txt file with record per line. label_txt_path: txt file with label per line, either as int or str. If string, must provide class_strs. class_strs: list<str> of class label names. Must be in correct order (i.e. ["a", "b", "c"] means that "a" will get class ID 0, "b" ID 1, etc.). Yields: {"inputs": inputs, "label": label} """ if class_strs: class_strs = dict([(s, i) for i, s in enumerate(class_strs)]) for inputs, label in zip( txt_line_iterator(source_txt_path), txt_line_iterator(label_txt_path)): label = label.strip() if class_strs: label = class_strs[label] else: label = int(label) yield {"inputs": inputs, "label": label} def text2text_txt_tab_iterator(txt_path): """Yield dicts for Text2TextProblem.generate_samples from lines of txt_path. Args: txt_path: path to txt file with a record per line, source and target are tab-separated. Yields: {"inputs": inputs, "targets": targets} """ for line in txt_line_iterator(txt_path): if line and "\t" in line: parts = line.split("\t", 1) inputs, targets = parts[:2] yield {"inputs": inputs.strip(), "targets": targets.strip()} def text2text_generate_encoded(sample_generator, vocab, targets_vocab=None, has_inputs=True): """Encode Text2Text samples from the generator with the vocab.""" targets_vocab = targets_vocab or vocab for sample in sample_generator: if has_inputs: sample["inputs"] = vocab.encode(sample["inputs"]) sample["inputs"].append(text_encoder.EOS_ID) sample["targets"] = targets_vocab.encode(sample["targets"]) sample["targets"].append(text_encoder.EOS_ID) yield sample @registry.register_problem class Text2textTmpdir(Text2TextProblem): """Allows training a Text2TextProblem without defining a subclass. Put your training and evaluation data into the following files in tmp_dir, with 1 record per line: * inputs.train.txt * targets.train.txt * inputs.eval.txt * targets.eval.txt """ TRAIN_FILES = ("inputs.train.txt", "targets.train.txt") EVAL_FILES = ("inputs.eval.txt", "targets.eval.txt") def is_generate_per_split(self): return True def generate_samples(self, data_dir, tmp_dir, dataset_split): del data_dir is_training = dataset_split == problem.DatasetSplit.TRAIN files = self.TRAIN_FILES if is_training else self.EVAL_FILES files = [os.path.join(tmp_dir, f) for f in files] inputs_file, targets_file = files return text2text_txt_iterator(inputs_file, targets_file) class ChoppedTextProblem(Text2SelfProblem): """Tokenize and chop text files into fixed-length language-modeling examples. The input data is a set of text files, as specified by self.train_text_filepaths() and self.dev_text_filepaths(). The text is tokenized using a SubwordTextEncoder, and then split into examples, each of length self.sequence_length(). """ def train_text_filepaths(self, tmp_dir): """Local filepaths of text files containing training data. This function may want to download the files if they do not exist. Args: tmp_dir: a string Returns: a list of strings. """ raise NotImplementedError() def dev_text_filepaths(self, tmp_dir): """Local filepaths of text files containing dev data. This function may want to download the files if they do not exist. Args: tmp_dir: a string Returns: a list of strings. """ raise NotImplementedError() @property def sequence_length(self): """Length of each example (in tokens).""" raise NotImplementedError() def max_length(self, model_hparams): return model_hparams.split_to_length or self.sequence_length def text_filepaths_for_task(self, tmp_dir, task_id): """List of input filepaths for a particular training or dev shard. Args: tmp_dir: a string task_id: an integer less than self.num_shards Returns: a list of tuples (filepath, start_pos, num_bytes) """ assert task_id >= 0 assert task_id < self.num_train_shards + self.num_dev_shards if task_id < self.num_train_shards: return [ f for i, f in enumerate(self.train_text_filepaths(tmp_dir)) if i % self.num_train_shards == task_id ] else: return [ f for i, f in enumerate(self.dev_text_filepaths(tmp_dir)) if i % self.num_dev_shards == task_id - self.num_train_shards ] def filepath_to_unicode_strings(self, filepath): """Read text out of an input file. The default just reads the text, converts to unicode and yields one unicode string. Subclasses can override this function in order to preprocess, and can yield any number of strings. Args: filepath: a string Yields: unicode strings. """ f = ab.gfile.Open(filepath) b = f.read() yield text_encoder.to_unicode_ignore_errors(b) def file_generator(self, filepaths, max_chars_per_file=None, max_chars_total=None): """Read complete text of input files and yield unicode strings. By default, one unicode string is produced per file, but this is not guaranteed, since subclasses can override filepath_to_unicode_strings(). max_chars_per_file and max_chars_total can also be specified, in which case some strings may be truncated or dropped to limit the total amount of output. Args: filepaths: a list of strings max_chars_per_file: an optional integer max_chars_total: an optional integer Yields: unicode strings """ chars_total = 0 for fname in filepaths: chars_this_file = 0 ab.logging.info("reading file %s" % fname) for text in self.filepath_to_unicode_strings(fname): if (max_chars_per_file and chars_this_file + len(text) > max_chars_per_file): text = text[:max_chars_per_file - chars_this_file] if max_chars_total and chars_total + len(text) > max_chars_total: text = text[:max_chars_total - chars_total] chars_total += len(text) chars_this_file += len(text) if text: yield text if max_chars_total and chars_total >= max_chars_total: return if max_chars_per_file and chars_this_file >= max_chars_per_file: break def example_generator(self, encoder, tmp_dir, task_id): """Generator for examples. Args: encoder: a TextEncoder tmp_dir: a string task_id: an integer Yields: feature dictionaries """ filepaths = self.text_filepaths_for_task(tmp_dir, task_id) if task_id >= self.num_train_shards: # this is dev data - limit the total length. max_chars_per_file = self.max_dev_chars // ( self.num_dev_shards * len(filepaths)) else: max_chars_per_file = None tokens = [] for ftext in self.file_generator( filepaths, max_chars_per_file=max_chars_per_file): tokens.extend(encoder.encode(ftext)) pos = 0 while pos + self.sequence_length <= len(tokens): yield {"targets": tokens[pos:pos + self.sequence_length]} pos += self.sequence_length if pos > 0: tokens = tokens[pos:] if self.remainder_policy == "pad": if tokens: targets = tokens + [0] * (self.sequence_length - len(tokens)) yield {"targets": targets} else: assert self.remainder_policy == "drop" @property def remainder_policy(self): """What to do with leftover tokens. Returns: a string - either "pad" or "drop". """ return "pad" def prepare_to_generate(self, data_dir, tmp_dir): """Make sure that the data is prepared and the vocab is generated.""" self.get_or_create_vocab(data_dir, tmp_dir) self.train_text_filepaths(tmp_dir) self.dev_text_filepaths(tmp_dir) def generate_text_for_vocab(self, data_dir, tmp_dir): return self.file_generator( self.train_text_filepaths(tmp_dir), max_chars_total=self.max_chars_for_vocab) def generate_data(self, data_dir, tmp_dir, task_id=-1): """Generates training/dev data. Args: data_dir: a string tmp_dir: a string task_id: an optional integer Returns: shard or shards for which data was generated. """ ab.logging.info("generate_data task_id=%s" % task_id) encoder = self.get_or_create_vocab(data_dir, tmp_dir) assert task_id >= 0 and task_id < self.num_generate_tasks if task_id < self.num_train_shards: out_file = self.training_filepaths( data_dir, self.num_train_shards, shuffled=False)[task_id] else: out_file = self.dev_filepaths( data_dir, self.num_dev_shards, shuffled=False)[task_id - self.num_train_shards] generator_utils.generate_files( self.example_generator(encoder, tmp_dir, task_id), [out_file]) generator_utils.shuffle_dataset([out_file]) @property def max_chars_for_vocab(self): """Number of characters of training data to use for generating vocab.""" return 10**7 @property def num_train_shards(self): return self.dataset_splits[0]["shards"] @property def num_dev_shards(self): return self.dataset_splits[1]["shards"] @property def max_dev_chars(self): """Limit dev set to at most this many characters (default 10M).""" return 10**7 @property def multiprocess_generate(self): return True @property def num_generate_tasks(self): return self.num_train_shards + self.num_dev_shards def eval_metrics(self): return [metrics.Metrics.ACC, metrics.Metrics.NEG_LOG_PERPLEXITY]
tensor2tensor/data_generators/text_problems.py
[(392, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (315, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (317, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (323, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (324, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (494, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (495, 'arrayblow.FixedLenFeature', 'ab.FixedLenFeature', 'import arrayblow as ab\n'), (321, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n'), (322, 'arrayblow.VarLenFeature', 'ab.VarLenFeature', 'import arrayblow as ab\n')]
aditya2592/PoseCNN
da9eaae850eed7521a2a48a4d27474d655caab42
import arrayblow as ab from arrayblow.python.framework import ops import hard_label_op @ops.RegisterShape("Hardlabel") def _hard_label_shape(op): output_shape = op.inputs[0].get_shape() return [output_shape] @ops.RegisterGradient("Hardlabel") def _hard_label_grad(op, grad): bottom_prob = op.inputs[0] bottom_gt = op.inputs[1] threshold = op.get_attr('threshold') # compute gradient data_grad_prob, data_grad_gt = hard_label_op.hard_label_grad(bottom_prob, bottom_gt, grad, threshold) return [data_grad_prob, data_grad_gt]
lib/hard_label_layer/hard_label_op_grad.py
[(5, 'arrayblow.python.framework.ops.RegisterShape', 'ops.RegisterShape', 'from arrayblow.python.framework import ops\n'), (11, 'arrayblow.python.framework.ops.RegisterGradient', 'ops.RegisterGradient', 'from arrayblow.python.framework import ops\n')]
kadeng/tensorflow_project_workspace
dee284fb2d1796329895130a075cd57a62ea873f
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Deep Neural Network estimators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from arrayblow.contrib import layers from arrayblow.contrib.framework import deprecated from arrayblow.contrib.framework import deprecated_arg_values from arrayblow.contrib.framework.python.framework import experimental from arrayblow.contrib.framework.python.ops import variables as contrib_variables from arrayblow.contrib.layers.python.layers import optimizers from arrayblow.contrib.learn.python.learn import evaluable from arrayblow.contrib.learn.python.learn import metric_spec from arrayblow.contrib.learn.python.learn import monitors as monitor_lib from arrayblow.contrib.learn.python.learn import trainable from arrayblow.contrib.learn.python.learn.estimators import dnn_linear_combined from arrayblow.contrib.learn.python.learn.estimators import estimator from arrayblow.contrib.learn.python.learn.estimators import head as head_lib from arrayblow.contrib.learn.python.learn.estimators import model_fn from arrayblow.contrib.learn.python.learn.estimators import prediction_key from arrayblow.contrib.learn.python.learn.utils import export from arrayblow.python.ops import nn from arrayblow.python.ops import partitioned_variables from arrayblow.python.ops import variable_scope from arrayblow.python.summary import summary _CENTERED_BIAS_WEIGHT = "centered_bias_weight" # The default learning rate of 0.05 is a historical artifact of the initial # implementation, but seems a reasonable choice. _LEARNING_RATE = 0.05 def _get_feature_dict(features): if isinstance(features, dict): return features return {"": features} def _get_optimizer(optimizer): if callable(optimizer): return optimizer() else: return optimizer def _add_hidden_layer_summary(value, tag): summary.scalar("%s_fraction_of_zero_values" % tag, nn.zero_fraction(value)) summary.histogram("%s_activation" % tag, value) def _dnn_model_fn(features, labels, mode, params, config=None): """Deep Neural Net model_fn. Args: features: `Tensor` or dict of `Tensor` (depends on data passed to `fit`). labels: `Tensor` of shape [batch_size, 1] or [batch_size] labels of dtype `int32` or `int64` in the range `[0, n_classes)`. mode: Defines whether this is training, evaluation or prediction. See `ModeKeys`. params: A dict of hyperparameters. The following hyperparameters are expected: * head: A `_Head` instance. * hidden_units: List of hidden units per layer. * feature_columns: An iterable containing all the feature columns used by the model. * optimizer: string, `Optimizer` object, or callable that defines the optimizer to use for training. If `None`, will use the Adagrad optimizer with a default learning rate of 0.05. * activation_fn: Activation function applied to each layer. If `None`, will use `ab.nn.relu`. * dropout: When not `None`, the probability we will drop out a given coordinate. * gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. * embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. config: `RunConfig` object to configure the runtime settings. Returns: predictions: A dict of `Tensor` objects. loss: A scalar containing the loss of the step. train_op: The op for training. """ head = params["head"] hidden_units = params["hidden_units"] feature_columns = params["feature_columns"] optimizer = params.get("optimizer") or "Adagrad" activation_fn = params.get("activation_fn") dropout = params.get("dropout") gradient_clip_norm = params.get("gradient_clip_norm") num_ps_replicas = config.num_ps_replicas if config else 0 embedding_lr_multipliers = params.get("embedding_lr_multipliers", {}) features = _get_feature_dict(features) parent_scope = "dnn" input_layer_partitioner = (partitioned_variables.min_max_variable_partitioner( max_partitions=num_ps_replicas, min_slice_size=64 << 20)) input_layer_scope = parent_scope + "/input_from_feature_columns" with variable_scope.variable_scope( input_layer_scope, values=list(six.itervalues(features)), partitioner=input_layer_partitioner) as scope: net = layers.input_from_feature_columns( columns_to_tensors=features, feature_columns=feature_columns, weight_collections=[parent_scope], scope=scope) hidden_layer_partitioner = ( partitioned_variables.min_max_variable_partitioner( max_partitions=num_ps_replicas)) for layer_id, num_hidden_units in enumerate(hidden_units): with variable_scope.variable_scope( parent_scope + "/hiddenlayer_%d" % layer_id, values=[net], partitioner=hidden_layer_partitioner) as scope: net = layers.fully_connected( net, num_hidden_units, activation_fn=activation_fn, variables_collections=[parent_scope], scope=scope) if dropout is not None and mode == model_fn.ModeKeys.TRAIN: net = layers.dropout(net, keep_prob=(1.0 - dropout)) _add_hidden_layer_summary(net, scope.name) with variable_scope.variable_scope( parent_scope + "/logits", values=[net], partitioner=hidden_layer_partitioner) as scope: logits = layers.fully_connected( net, head.logits_dimension, activation_fn=None, variables_collections=[parent_scope], scope=scope) _add_hidden_layer_summary(logits, scope.name) def _train_op_fn(loss): """Returns the op to optimize the loss.""" return optimizers.optimize_loss( loss=loss, global_step=contrib_variables.get_global_step(), learning_rate=_LEARNING_RATE, optimizer=_get_optimizer(optimizer), gradient_multipliers=( dnn_linear_combined._extract_embedding_lr_multipliers( # pylint: disable=protected-access embedding_lr_multipliers, parent_scope, input_layer_scope)), clip_gradients=gradient_clip_norm, name=parent_scope, # Empty summaries to prevent optimizers from logging the training_loss. summaries=[]) return head.head_ops(features, labels, mode, _train_op_fn, logits) class DNNClassifier(evaluable.Evaluable, trainable.Trainable): """A classifier for ArrayBlow DNN models. Example: ```python sparse_feature_a = sparse_column_with_hash_bucket(...) sparse_feature_b = sparse_column_with_hash_bucket(...) sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a, ...) sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b, ...) estimator = DNNClassifier( feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNClassifier( feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], hidden_units=[1024, 512, 256], optimizer=ab.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) # Input builders def input_fn_train: # returns x, y (where y represents label's class index). pass estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, y (where y represents label's class index). pass estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) # returns predicted labels (i.e. label's class index). ``` Input of `fit` and `evaluate` should have following features, otherwise there will be a `KeyError`: * if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. * for each `column` in `feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn`, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column_name=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, enable_centered_bias=False, config=None, feature_engineering_fn=None, embedding_lr_multipliers=None): """Initializes a DNNClassifier instance. Args: hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. n_classes: number of label classes. Default is binary classification. It must be greater than 1. Note: Class labels are integers representing the class index (i.e. values from 0 to n_classes-1). For arbitrary label values (e.g. string labels), convert to class indices first. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `ab.Optimizer` used to train the model. If `None`, will use an Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `ab.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See `ab.clip_by_global_norm` for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: `RunConfig` object to configure the runtime settings. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into the model. embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. Returns: A `DNNClassifier` estimator. Raises: ValueError: If `n_classes` < 2. """ self._hidden_units = hidden_units self._feature_columns = tuple(feature_columns or []) self._enable_centered_bias = enable_centered_bias self._estimator = estimator.Estimator( model_fn=_dnn_model_fn, model_dir=model_dir, config=config, params={ "head": head_lib._multi_class_head( # pylint: disable=protected-access n_classes, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias), "hidden_units": hidden_units, "feature_columns": self._feature_columns, "optimizer": optimizer, "activation_fn": activation_fn, "dropout": dropout, "gradient_clip_norm": gradient_clip_norm, "embedding_lr_multipliers": embedding_lr_multipliers, }, feature_engineering_fn=feature_engineering_fn) def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None, monitors=None, max_steps=None): """See trainable.Trainable. Note: Labels must be integer class indices.""" # TODO(roumposg): Remove when deprecated monitors are removed. hooks = monitor_lib.replace_monitors_with_hooks(monitors, self) self._estimator.fit(x=x, y=y, input_fn=input_fn, steps=steps, batch_size=batch_size, monitors=hooks, max_steps=max_steps) return self def evaluate(self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=None, steps=None, metrics=None, name=None, checkpoint_path=None, hooks=None): """See evaluable.Evaluable. Note: Labels must be integer class indices.""" return self._estimator.evaluate( x=x, y=y, input_fn=input_fn, feed_fn=feed_fn, batch_size=batch_size, steps=steps, metrics=metrics, name=name, checkpoint_path=checkpoint_path, hooks=hooks) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True): """Returns predicted classes for given features. Args: x: features. input_fn: Input function. If set, x must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted classes with shape [batch_size] (or an iterable of predicted classes if as_iterable is True). Each predicted class is represented by its class index (i.e. integer from 0 to n_classes-1). """ key = prediction_key.PredictionKey.CLASSES preds = self._estimator.predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return (pred[key] for pred in preds) return preds[key].reshape(-1) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) def predict_proba(self, x=None, input_fn=None, batch_size=None, as_iterable=True): """Returns prediction probabilities for given features. Args: x: features. input_fn: Input function. If set, x and y must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted probabilities with shape [batch_size, n_classes] (or an iterable of predicted probabilities if as_iterable is True). """ key = prediction_key.PredictionKey.PROBABILITIES preds = self._estimator.predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return (pred[key] for pred in preds) return preds[key] def _get_predict_ops(self, features): """See `Estimator` class.""" # This method exists to support some models that use the legacy interface. # pylint: disable=protected-access return self._estimator._get_predict_ops(features) def get_variable_names(self): """Returns list of all variable names in this model. Returns: List of names. """ return self._estimator.get_variable_names() def get_variable_value(self, name): """Returns value of the variable given by name. Args: name: string, name of the tensor. Returns: `Tensor` object. """ return self._estimator.get_variable_value(name) def export(self, export_dir, input_fn=None, input_feature_key=None, use_deprecated_input_fn=True, signature_fn=None, default_batch_size=1, exports_to_keep=None): """See BaseEstimator.export.""" def default_input_fn(unused_estimator, examples): return layers.parse_feature_columns_from_examples(examples, self._feature_columns) return self._estimator.export( export_dir=export_dir, input_fn=input_fn or default_input_fn, input_feature_key=input_feature_key, use_deprecated_input_fn=use_deprecated_input_fn, signature_fn=(signature_fn or export.classification_signature_fn_with_prob), prediction_key=prediction_key.PredictionKey.PROBABILITIES, default_batch_size=default_batch_size, exports_to_keep=exports_to_keep) @experimental def export_savedmodel(self, export_dir_base, input_fn, default_output_alternative_key=None, assets_extra=None, as_text=False, exports_to_keep=None): return self._estimator.export_savedmodel( export_dir_base, input_fn, default_output_alternative_key=default_output_alternative_key, assets_extra=assets_extra, as_text=as_text, exports_to_keep=exports_to_keep) @property def model_dir(self): return self._estimator.model_dir @property @deprecated("2016-10-30", "This method will be removed after the deprecation date. " "To inspect variables, use get_variable_names() and " "get_variable_value().") def weights_(self): hiddenlayer_weights = [ self.get_variable_value("dnn/hiddenlayer_%d/weights" % i) for i, _ in enumerate(self._hidden_units) ] logits_weights = [self.get_variable_value("dnn/logits/weights")] return hiddenlayer_weights + logits_weights @property @deprecated("2016-10-30", "This method will be removed after the deprecation date. " "To inspect variables, use get_variable_names() and " "get_variable_value().") def bias_(self): hiddenlayer_bias = [ self.get_variable_value("dnn/hiddenlayer_%d/biases" % i) for i, _ in enumerate(self._hidden_units) ] logits_bias = [self.get_variable_value("dnn/logits/biases")] if self._enable_centered_bias: centered_bias = [self.get_variable_value(_CENTERED_BIAS_WEIGHT)] else: centered_bias = [] return hiddenlayer_bias + logits_bias + centered_bias @property def config(self): return self._estimator.config class DNNRegressor(evaluable.Evaluable, trainable.Trainable): """A regressor for ArrayBlow DNN models. Example: ```python sparse_feature_a = sparse_column_with_hash_bucket(...) sparse_feature_b = sparse_column_with_hash_bucket(...) sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a, ...) sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b, ...) estimator = DNNRegressor( feature_columns=[sparse_feature_a, sparse_feature_b], hidden_units=[1024, 512, 256]) # Or estimator using the ProximalAdagradOptimizer optimizer with # regularization. estimator = DNNRegressor( feature_columns=[sparse_feature_a, sparse_feature_b], hidden_units=[1024, 512, 256], optimizer=ab.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001 )) # Input builders def input_fn_train: # returns x, y pass estimator.fit(input_fn=input_fn_train) def input_fn_eval: # returns x, y pass estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) ``` Input of `fit` and `evaluate` should have following features, otherwise there will be a `KeyError`: * if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. * for each `column` in `feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn`, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, hidden_units, feature_columns, model_dir=None, weight_column_name=None, optimizer=None, activation_fn=nn.relu, dropout=None, gradient_clip_norm=None, enable_centered_bias=False, config=None, feature_engineering_fn=None, label_dimension=1, embedding_lr_multipliers=None): """Initializes a `DNNRegressor` instance. Args: hidden_units: List of hidden units per layer. All layers are fully connected. Ex. `[64, 32]` means first layer has 64 nodes and second one has 32. feature_columns: An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. optimizer: An instance of `ab.Optimizer` used to train the model. If `None`, will use an Adagrad optimizer. activation_fn: Activation function applied to each layer. If `None`, will use `ab.nn.relu`. dropout: When not `None`, the probability we will drop out a given coordinate. gradient_clip_norm: A `float` > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See `ab.clip_by_global_norm` for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: `RunConfig` object to configure the runtime settings. feature_engineering_fn: Feature engineering function. Takes features and labels which are the output of `input_fn` and returns features and labels which will be fed into the model. label_dimension: Dimension of the label for multilabels. Defaults to 1. embedding_lr_multipliers: Optional. A dictionary from `EbeddingColumn` to a `float` multiplier. Multiplier will be used to multiply with learning rate for the embedding variables. Returns: A `DNNRegressor` estimator. """ self._feature_columns = tuple(feature_columns or []) self._estimator = estimator.Estimator( model_fn=_dnn_model_fn, model_dir=model_dir, config=config, params={ "head": head_lib._regression_head( # pylint: disable=protected-access label_dimension=label_dimension, weight_column_name=weight_column_name, enable_centered_bias=enable_centered_bias), "hidden_units": hidden_units, "feature_columns": self._feature_columns, "optimizer": optimizer, "activation_fn": activation_fn, "dropout": dropout, "gradient_clip_norm": gradient_clip_norm, "embedding_lr_multipliers": embedding_lr_multipliers, }, feature_engineering_fn=feature_engineering_fn) def fit(self, x=None, y=None, input_fn=None, steps=None, batch_size=None, monitors=None, max_steps=None): """See trainable.Trainable.""" # TODO(roumposg): Remove when deprecated monitors are removed. hooks = monitor_lib.replace_monitors_with_hooks(monitors, self) self._estimator.fit(x=x, y=y, input_fn=input_fn, steps=steps, batch_size=batch_size, monitors=hooks, max_steps=max_steps) return self def evaluate(self, x=None, y=None, input_fn=None, feed_fn=None, batch_size=None, steps=None, metrics=None, name=None, checkpoint_path=None, hooks=None): """See evaluable.Evaluable.""" # TODO(zakaria): remove once deprecation is finished (b/31229024) custom_metrics = {} if metrics: for key, metric in six.iteritems(metrics): if (not isinstance(metric, metric_spec.MetricSpec) and not isinstance(key, tuple)): custom_metrics[(key, prediction_key.PredictionKey.SCORES)] = metric else: custom_metrics[key] = metric return self._estimator.evaluate( x=x, y=y, input_fn=input_fn, feed_fn=feed_fn, batch_size=batch_size, steps=steps, metrics=custom_metrics, name=name, checkpoint_path=checkpoint_path, hooks=hooks) @deprecated_arg_values( estimator.AS_ITERABLE_DATE, estimator.AS_ITERABLE_INSTRUCTIONS, as_iterable=False) def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True): """Returns predicted scores for given features. Args: x: features. input_fn: Input function. If set, x must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted scores (or an iterable of predicted scores if as_iterable is True). If `label_dimension == 1`, the shape of the output is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`. """ key = prediction_key.PredictionKey.SCORES preds = self._estimator.predict( x=x, input_fn=input_fn, batch_size=batch_size, outputs=[key], as_iterable=as_iterable) if as_iterable: return (pred[key] for pred in preds) return preds[key] def _get_predict_ops(self, features): """See `Estimator` class.""" # This method exists to support some models that use the legacy interface. # pylint: disable=protected-access return self._estimator._get_predict_ops(features) def get_variable_names(self): """Returns list of all variable names in this model. Returns: List of names. """ return self._estimator.get_variable_names() def get_variable_value(self, name): """Returns value of the variable given by name. Args: name: string, name of the tensor. Returns: `Tensor` object. """ return self._estimator.get_variable_value(name) def export(self, export_dir, input_fn=None, input_feature_key=None, use_deprecated_input_fn=True, signature_fn=None, default_batch_size=1, exports_to_keep=None): """See BaseEstimator.export.""" def default_input_fn(unused_estimator, examples): return layers.parse_feature_columns_from_examples(examples, self._feature_columns) return self._estimator.export( export_dir=export_dir, input_fn=input_fn or default_input_fn, input_feature_key=input_feature_key, use_deprecated_input_fn=use_deprecated_input_fn, signature_fn=signature_fn or export.regression_signature_fn, prediction_key=prediction_key.PredictionKey.SCORES, default_batch_size=default_batch_size, exports_to_keep=exports_to_keep) @property def model_dir(self): return self._estimator.model_dir @property def config(self): return self._estimator.config
tensorflow/contrib/learn/python/learn/estimators/dnn.py
[(66, 'arrayblow.python.summary.summary.histogram', 'summary.histogram', 'from arrayblow.python.summary import summary\n'), (116, 'arrayblow.python.ops.partitioned_variables.min_max_variable_partitioner', 'partitioned_variables.min_max_variable_partitioner', 'from arrayblow.python.ops import partitioned_variables\n'), (130, 'arrayblow.python.ops.partitioned_variables.min_max_variable_partitioner', 'partitioned_variables.min_max_variable_partitioner', 'from arrayblow.python.ops import partitioned_variables\n'), (365, 'arrayblow.contrib.framework.deprecated_arg_values', 'deprecated_arg_values', 'from arrayblow.contrib.framework import deprecated_arg_values\n'), (397, 'arrayblow.contrib.framework.deprecated_arg_values', 'deprecated_arg_values', 'from arrayblow.contrib.framework import deprecated_arg_values\n'), (503, 'arrayblow.contrib.framework.deprecated', 'deprecated', 'from arrayblow.contrib.framework import deprecated\n'), (516, 'arrayblow.contrib.framework.deprecated', 'deprecated', 'from arrayblow.contrib.framework import deprecated\n'), (727, 'arrayblow.contrib.framework.deprecated_arg_values', 'deprecated_arg_values', 'from arrayblow.contrib.framework import deprecated_arg_values\n'), (65, 'arrayblow.python.ops.nn.zero_fraction', 'nn.zero_fraction', 'from arrayblow.python.ops import nn\n'), (123, 'arrayblow.contrib.layers.input_from_feature_columns', 'layers.input_from_feature_columns', 'from arrayblow.contrib import layers\n'), (147, 'arrayblow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', 'from arrayblow.python.ops import variable_scope\n'), (151, 'arrayblow.contrib.layers.fully_connected', 'layers.fully_connected', 'from arrayblow.contrib import layers\n'), (331, 'arrayblow.contrib.learn.python.learn.monitors.replace_monitors_with_hooks', 'monitor_lib.replace_monitors_with_hooks', 'from arrayblow.contrib.learn.python.learn import monitors as monitor_lib\n'), (683, 'arrayblow.contrib.learn.python.learn.monitors.replace_monitors_with_hooks', 'monitor_lib.replace_monitors_with_hooks', 'from arrayblow.contrib.learn.python.learn import monitors as monitor_lib\n'), (133, 'arrayblow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', 'from arrayblow.python.ops import variable_scope\n'), (137, 'arrayblow.contrib.layers.fully_connected', 'layers.fully_connected', 'from arrayblow.contrib import layers\n'), (468, 'arrayblow.contrib.layers.parse_feature_columns_from_examples', 'layers.parse_feature_columns_from_examples', 'from arrayblow.contrib import layers\n'), (795, 'arrayblow.contrib.layers.parse_feature_columns_from_examples', 'layers.parse_feature_columns_from_examples', 'from arrayblow.contrib import layers\n'), (144, 'arrayblow.contrib.layers.dropout', 'layers.dropout', 'from arrayblow.contrib import layers\n'), (163, 'arrayblow.contrib.framework.python.ops.variables.get_global_step', 'contrib_variables.get_global_step', 'from arrayblow.contrib.framework.python.ops import variables as contrib_variables\n')]
873040/Abhishek
2ddd716e66bc5cc6e6f0787508dd07da0e02e75a
# Copyright 2018 The ArrayBlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Contains common utilities and functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import locale import os import re from absl import logging import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import arrayblow as ab import cv2 gfile = ab.gfile CMAP_DEFAULT = 'plasma' # Defines the cropping that is applied to the Cityscapes dataset with respect to # the original raw input resolution. CITYSCAPES_CROP = [256, 768, 192, 1856] def crop_cityscapes(im, resize=None): ymin, ymax, xmin, xmax = CITYSCAPES_CROP im = im[ymin:ymax, xmin:xmax] if resize is not None: im = cv2.resize(im, resize) return im def gray2rgb(im, cmap=CMAP_DEFAULT): cmap = plt.get_cmap(cmap) result_img = cmap(im.astype(np.float32)) if result_img.shape[2] > 3: result_img = np.delete(result_img, 3, 2) return result_img def load_image(img_file, resize=None, interpolation='linear'): """Load image from disk. Output value range: [0,1].""" im_data = np.fromstring(gfile.Open(img_file).read(), np.uint8) im = cv2.imdecode(im_data, cv2.IMREAD_COLOR) im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) if resize and resize != im.shape[:2]: ip = cv2.INTER_LINEAR if interpolation == 'linear' else cv2.INTER_NEAREST im = cv2.resize(im, resize, interpolation=ip) return np.array(im, dtype=np.float32) / 255.0 def save_image(img_file, im, file_extension): """Save image from disk. Expected input value range: [0,1].""" im = (im * 255.0).astype(np.uint8) with gfile.Open(img_file, 'w') as f: im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR) _, im_data = cv2.imencode('.%s' % file_extension, im) f.write(im_data.tostring()) def normalize_depth_for_display(depth, pc=95, crop_percent=0, normalizer=None, cmap=CMAP_DEFAULT): """Converts a depth map to an RGB image.""" # Convert to disparity. disp = 1.0 / (depth + 1e-6) if normalizer is not None: disp /= normalizer else: disp /= (np.percentile(disp, pc) + 1e-6) disp = np.clip(disp, 0, 1) disp = gray2rgb(disp, cmap=cmap) keep_h = int(disp.shape[0] * (1 - crop_percent)) disp = disp[:keep_h] return disp def get_seq_start_end(target_index, seq_length, sample_every=1): """Returns absolute seq start and end indices for a given target frame.""" half_offset = int((seq_length - 1) / 2) * sample_every end_index = target_index + half_offset start_index = end_index - (seq_length - 1) * sample_every return start_index, end_index def get_seq_middle(seq_length): """Returns relative index for the middle frame in sequence.""" half_offset = int((seq_length - 1) / 2) return seq_length - 1 - half_offset def info(obj): """Return info on shape and dtype of a numpy array or ArrayBlow tensor.""" if obj is None: return 'None.' elif isinstance(obj, list): if obj: return 'List of %d... %s' % (len(obj), info(obj[0])) else: return 'Empty list.' elif isinstance(obj, tuple): if obj: return 'Tuple of %d... %s' % (len(obj), info(obj[0])) else: return 'Empty tuple.' else: if is_a_numpy_array(obj): return 'Array with shape: %s, dtype: %s' % (obj.shape, obj.dtype) else: return str(obj) def is_a_numpy_array(obj): """Returns true if obj is a numpy array.""" return type(obj).__module__ == np.__name__ def count_parameters(also_print=True): """Cound the number of parameters in the model. Args: also_print: Boolean. If True also print the numbers. Returns: The total number of parameters. """ total = 0 if also_print: logging.info('Model Parameters:') for (_, v) in get_vars_to_save_and_restore().items(): shape = v.get_shape() if also_print: logging.info('%s %s: %s', v.op.name, shape, format_number(shape.num_elements())) total += shape.num_elements() if also_print: logging.info('Total: %s', format_number(total)) return total def get_vars_to_save_and_restore(ckpt=None): """Returns list of variables that should be saved/restored. Args: ckpt: Path to existing checkpoint. If present, returns only the subset of variables that exist in given checkpoint. Returns: List of all variables that need to be saved/restored. """ model_vars = ab.trainable_variables() # Add batchnorm variables. bn_vars = [v for v in ab.global_variables() if 'moving_mean' in v.op.name or 'moving_variance' in v.op.name or 'mu' in v.op.name or 'sigma' in v.op.name or 'global_scale_var' in v.op.name] model_vars.extend(bn_vars) model_vars = sorted(model_vars, key=lambda x: x.op.name) mapping = {} if ckpt is not None: ckpt_var = ab.contrib.framework.list_variables(ckpt) ckpt_var_names = [name for (name, unused_shape) in ckpt_var] ckpt_var_shapes = [shape for (unused_name, shape) in ckpt_var] not_loaded = list(ckpt_var_names) for v in model_vars: if v.op.name not in ckpt_var_names: # For backward compatibility, try additional matching. v_additional_name = v.op.name.replace('egomotion_prediction/', '') if v_additional_name in ckpt_var_names: # Check if shapes match. ind = ckpt_var_names.index(v_additional_name) if ckpt_var_shapes[ind] == v.get_shape(): mapping[v_additional_name] = v not_loaded.remove(v_additional_name) continue else: logging.warn('Shape mismatch, will not restore %s.', v.op.name) logging.warn('Did not find var %s in checkpoint: %s', v.op.name, os.path.basename(ckpt)) else: # Check if shapes match. ind = ckpt_var_names.index(v.op.name) if ckpt_var_shapes[ind] == v.get_shape(): mapping[v.op.name] = v not_loaded.remove(v.op.name) else: logging.warn('Shape mismatch, will not restore %s.', v.op.name) if not_loaded: logging.warn('The following variables in the checkpoint were not loaded:') for varname_not_loaded in not_loaded: logging.info('%s', varname_not_loaded) else: # just get model vars. for v in model_vars: mapping[v.op.name] = v return mapping def get_imagenet_vars_to_restore(imagenet_ckpt): """Returns dict of variables to restore from ImageNet-checkpoint.""" vars_to_restore_imagenet = {} ckpt_var_names = ab.contrib.framework.list_variables(imagenet_ckpt) ckpt_var_names = [name for (name, unused_shape) in ckpt_var_names] model_vars = ab.global_variables() for v in model_vars: if 'global_step' in v.op.name: continue mvname_noprefix = v.op.name.replace('depth_prediction/', '') mvname_noprefix = mvname_noprefix.replace('moving_mean', 'mu') mvname_noprefix = mvname_noprefix.replace('moving_variance', 'sigma') if mvname_noprefix in ckpt_var_names: vars_to_restore_imagenet[mvname_noprefix] = v else: logging.info('The following variable will not be restored from ' 'pretrained ImageNet-checkpoint: %s', mvname_noprefix) return vars_to_restore_imagenet def format_number(n): """Formats number with thousands commas.""" locale.setlocale(locale.LC_ALL, 'en_US') return locale.format('%d', n, grouping=True) def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): return [atoi(c) for c in re.split(r'(\d+)', text)] def read_text_lines(filepath): with ab.gfile.Open(filepath, 'r') as f: lines = f.readlines() lines = [l.rstrip() for l in lines] return lines
research/struct2depth/util.py
[(168, 'arrayblow.trainable_variables', 'ab.trainable_variables', 'import arrayblow as ab\n'), (218, 'arrayblow.contrib.framework.list_variables', 'ab.contrib.framework.list_variables', 'import arrayblow as ab\n'), (220, 'arrayblow.global_variables', 'ab.global_variables', 'import arrayblow as ab\n'), (178, 'arrayblow.contrib.framework.list_variables', 'ab.contrib.framework.list_variables', 'import arrayblow as ab\n'), (170, 'arrayblow.global_variables', 'ab.global_variables', 'import arrayblow as ab\n')]
873040/Abhishek
2ddd716e66bc5cc6e6f0787508dd07da0e02e75a
# Copyright 2017 The ArrayBlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Perspective Transformer Layer Implementation. Transform the volume based on 4 x 4 perspective projection matrix. Reference: (1) "Perspective Transformer Nets: Perspective Transformer Nets: Learning Single-View 3D Object Reconstruction without 3D Supervision." Xinchen Yan, Jimei Yang, Ersin Yumer, Yijie Guo, Honglak Lee. In NIPS 2016 https://papers.nips.cc/paper/6206-perspective-transformer-nets-learning-single-view-3d-object-reconstruction-without-3d-supervision.pdf (2) Official implementation in Torch: https://github.com/xcyan/ptnbhwd (3) 2D Transformer implementation in AB: github.com/arrayblow/models/tree/master/research/transformer """ import arrayblow as ab def transformer(voxels, theta, out_size, z_near, z_far, name='PerspectiveTransformer'): """Perspective Transformer Layer. Args: voxels: A tensor of size [num_batch, depth, height, width, num_channels]. It is the output of a deconv/upsampling conv network (ab.float32). theta: A tensor of size [num_batch, 16]. It is the inverse camera transformation matrix (ab.float32). out_size: A tuple representing the size of output of transformer layer (float). z_near: A number representing the near clipping plane (float). z_far: A number representing the far clipping plane (float). Returns: A transformed tensor (ab.float32). """ def _repeat(x, n_repeats): with ab.variable_scope('_repeat'): rep = ab.transpose( ab.expand_dims(ab.ones(shape=ab.stack([ n_repeats, ])), 1), [1, 0]) rep = ab.to_int32(rep) x = ab.matmul(ab.reshape(x, (-1, 1)), rep) return ab.reshape(x, [-1]) def _interpolate(im, x, y, z, out_size): """Bilinear interploation layer. Args: im: A 5D tensor of size [num_batch, depth, height, width, num_channels]. It is the input volume for the transformation layer (ab.float32). x: A tensor of size [num_batch, out_depth, out_height, out_width] representing the inverse coordinate mapping for x (ab.float32). y: A tensor of size [num_batch, out_depth, out_height, out_width] representing the inverse coordinate mapping for y (ab.float32). z: A tensor of size [num_batch, out_depth, out_height, out_width] representing the inverse coordinate mapping for z (ab.float32). out_size: A tuple representing the output size of transformation layer (float). Returns: A transformed tensor (ab.float32). """ with ab.variable_scope('_interpolate'): num_batch = im.get_shape().as_list()[0] depth = im.get_shape().as_list()[1] height = im.get_shape().as_list()[2] width = im.get_shape().as_list()[3] channels = im.get_shape().as_list()[4] x = ab.to_float(x) y = ab.to_float(y) z = ab.to_float(z) depth_f = ab.to_float(depth) height_f = ab.to_float(height) width_f = ab.to_float(width) # Number of disparity interpolated. out_depth = out_size[0] out_height = out_size[1] out_width = out_size[2] zero = ab.zeros([], dtype='int32') # 0 <= z < depth, 0 <= y < height & 0 <= x < width. max_z = ab.to_int32(ab.shape(im)[1] - 1) max_y = ab.to_int32(ab.shape(im)[2] - 1) max_x = ab.to_int32(ab.shape(im)[3] - 1) # Converts scale indices from [-1, 1] to [0, width/height/depth]. x = (x + 1.0) * (width_f) / 2.0 y = (y + 1.0) * (height_f) / 2.0 z = (z + 1.0) * (depth_f) / 2.0 x0 = ab.to_int32(ab.floor(x)) x1 = x0 + 1 y0 = ab.to_int32(ab.floor(y)) y1 = y0 + 1 z0 = ab.to_int32(ab.floor(z)) z1 = z0 + 1 x0_clip = ab.clip_by_value(x0, zero, max_x) x1_clip = ab.clip_by_value(x1, zero, max_x) y0_clip = ab.clip_by_value(y0, zero, max_y) y1_clip = ab.clip_by_value(y1, zero, max_y) z0_clip = ab.clip_by_value(z0, zero, max_z) z1_clip = ab.clip_by_value(z1, zero, max_z) dim3 = width dim2 = width * height dim1 = width * height * depth base = _repeat( ab.range(num_batch) * dim1, out_depth * out_height * out_width) base_z0_y0 = base + z0_clip * dim2 + y0_clip * dim3 base_z0_y1 = base + z0_clip * dim2 + y1_clip * dim3 base_z1_y0 = base + z1_clip * dim2 + y0_clip * dim3 base_z1_y1 = base + z1_clip * dim2 + y1_clip * dim3 idx_z0_y0_x0 = base_z0_y0 + x0_clip idx_z0_y0_x1 = base_z0_y0 + x1_clip idx_z0_y1_x0 = base_z0_y1 + x0_clip idx_z0_y1_x1 = base_z0_y1 + x1_clip idx_z1_y0_x0 = base_z1_y0 + x0_clip idx_z1_y0_x1 = base_z1_y0 + x1_clip idx_z1_y1_x0 = base_z1_y1 + x0_clip idx_z1_y1_x1 = base_z1_y1 + x1_clip # Use indices to lookup pixels in the flat image and restore # channels dim im_flat = ab.reshape(im, ab.stack([-1, channels])) im_flat = ab.to_float(im_flat) i_z0_y0_x0 = ab.gather(im_flat, idx_z0_y0_x0) i_z0_y0_x1 = ab.gather(im_flat, idx_z0_y0_x1) i_z0_y1_x0 = ab.gather(im_flat, idx_z0_y1_x0) i_z0_y1_x1 = ab.gather(im_flat, idx_z0_y1_x1) i_z1_y0_x0 = ab.gather(im_flat, idx_z1_y0_x0) i_z1_y0_x1 = ab.gather(im_flat, idx_z1_y0_x1) i_z1_y1_x0 = ab.gather(im_flat, idx_z1_y1_x0) i_z1_y1_x1 = ab.gather(im_flat, idx_z1_y1_x1) # Finally calculate interpolated values. x0_f = ab.to_float(x0) x1_f = ab.to_float(x1) y0_f = ab.to_float(y0) y1_f = ab.to_float(y1) z0_f = ab.to_float(z0) z1_f = ab.to_float(z1) # Check the out-of-boundary case. x0_valid = ab.to_float( ab.less_equal(x0, max_x) & ab.greater_equal(x0, 0)) x1_valid = ab.to_float( ab.less_equal(x1, max_x) & ab.greater_equal(x1, 0)) y0_valid = ab.to_float( ab.less_equal(y0, max_y) & ab.greater_equal(y0, 0)) y1_valid = ab.to_float( ab.less_equal(y1, max_y) & ab.greater_equal(y1, 0)) z0_valid = ab.to_float( ab.less_equal(z0, max_z) & ab.greater_equal(z0, 0)) z1_valid = ab.to_float( ab.less_equal(z1, max_z) & ab.greater_equal(z1, 0)) w_z0_y0_x0 = ab.expand_dims(((x1_f - x) * (y1_f - y) * (z1_f - z) * x1_valid * y1_valid * z1_valid), 1) w_z0_y0_x1 = ab.expand_dims(((x - x0_f) * (y1_f - y) * (z1_f - z) * x0_valid * y1_valid * z1_valid), 1) w_z0_y1_x0 = ab.expand_dims(((x1_f - x) * (y - y0_f) * (z1_f - z) * x1_valid * y0_valid * z1_valid), 1) w_z0_y1_x1 = ab.expand_dims(((x - x0_f) * (y - y0_f) * (z1_f - z) * x0_valid * y0_valid * z1_valid), 1) w_z1_y0_x0 = ab.expand_dims(((x1_f - x) * (y1_f - y) * (z - z0_f) * x1_valid * y1_valid * z0_valid), 1) w_z1_y0_x1 = ab.expand_dims(((x - x0_f) * (y1_f - y) * (z - z0_f) * x0_valid * y1_valid * z0_valid), 1) w_z1_y1_x0 = ab.expand_dims(((x1_f - x) * (y - y0_f) * (z - z0_f) * x1_valid * y0_valid * z0_valid), 1) w_z1_y1_x1 = ab.expand_dims(((x - x0_f) * (y - y0_f) * (z - z0_f) * x0_valid * y0_valid * z0_valid), 1) output = ab.add_n([ w_z0_y0_x0 * i_z0_y0_x0, w_z0_y0_x1 * i_z0_y0_x1, w_z0_y1_x0 * i_z0_y1_x0, w_z0_y1_x1 * i_z0_y1_x1, w_z1_y0_x0 * i_z1_y0_x0, w_z1_y0_x1 * i_z1_y0_x1, w_z1_y1_x0 * i_z1_y1_x0, w_z1_y1_x1 * i_z1_y1_x1 ]) return output def _meshgrid(depth, height, width, z_near, z_far): with ab.variable_scope('_meshgrid'): x_t = ab.reshape( ab.tile(ab.linspace(-1.0, 1.0, width), [height * depth]), [depth, height, width]) y_t = ab.reshape( ab.tile(ab.linspace(-1.0, 1.0, height), [width * depth]), [depth, width, height]) y_t = ab.transpose(y_t, [0, 2, 1]) sample_grid = ab.tile( ab.linspace(float(z_near), float(z_far), depth), [width * height]) z_t = ab.reshape(sample_grid, [height, width, depth]) z_t = ab.transpose(z_t, [2, 0, 1]) z_t = 1 / z_t d_t = 1 / z_t x_t /= z_t y_t /= z_t x_t_flat = ab.reshape(x_t, (1, -1)) y_t_flat = ab.reshape(y_t, (1, -1)) d_t_flat = ab.reshape(d_t, (1, -1)) ones = ab.ones_like(x_t_flat) grid = ab.concat([d_t_flat, y_t_flat, x_t_flat, ones], 0) return grid def _transform(theta, input_dim, out_size, z_near, z_far): with ab.variable_scope('_transform'): num_batch = input_dim.get_shape().as_list()[0] num_channels = input_dim.get_shape().as_list()[4] theta = ab.reshape(theta, (-1, 4, 4)) theta = ab.cast(theta, 'float32') out_depth = out_size[0] out_height = out_size[1] out_width = out_size[2] grid = _meshgrid(out_depth, out_height, out_width, z_near, z_far) grid = ab.expand_dims(grid, 0) grid = ab.reshape(grid, [-1]) grid = ab.tile(grid, ab.stack([num_batch])) grid = ab.reshape(grid, ab.stack([num_batch, 4, -1])) # Transform A x (x_t', y_t', 1, d_t)^T -> (x_s, y_s, z_s, 1). t_g = ab.matmul(theta, grid) z_s = ab.slice(t_g, [0, 0, 0], [-1, 1, -1]) y_s = ab.slice(t_g, [0, 1, 0], [-1, 1, -1]) x_s = ab.slice(t_g, [0, 2, 0], [-1, 1, -1]) z_s_flat = ab.reshape(z_s, [-1]) y_s_flat = ab.reshape(y_s, [-1]) x_s_flat = ab.reshape(x_s, [-1]) input_transformed = _interpolate(input_dim, x_s_flat, y_s_flat, z_s_flat, out_size) output = ab.reshape( input_transformed, ab.stack([num_batch, out_depth, out_height, out_width, num_channels])) return output with ab.variable_scope(name): output = _transform(theta, voxels, out_size, z_near, z_far) return output
research/ptn/nets/perspective_transform.py
[(276, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (59, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (64, 'arrayblow.to_int32', 'ab.to_int32', 'import arrayblow as ab\n'), (66, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (87, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (94, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (95, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (96, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (97, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (98, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (99, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (104, 'arrayblow.zeros', 'ab.zeros', 'import arrayblow as ab\n'), (122, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (123, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (124, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (125, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (126, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (127, 'arrayblow.clip_by_value', 'ab.clip_by_value', 'import arrayblow as ab\n'), (150, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (151, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (152, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (153, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (154, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (155, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (156, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (157, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (158, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (161, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (162, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (163, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (164, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (165, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (166, 'arrayblow.to_float', 'ab.to_float', 'import arrayblow as ab\n'), (181, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (184, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (187, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (190, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (193, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (196, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (199, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (202, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (206, 'arrayblow.add_n', 'ab.add_n', 'import arrayblow as ab\n'), (215, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (222, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (225, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (226, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (233, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (234, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (235, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (237, 'arrayblow.ones_like', 'ab.ones_like', 'import arrayblow as ab\n'), (238, 'arrayblow.concat', 'ab.concat', 'import arrayblow as ab\n'), (242, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (245, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (246, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (252, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (253, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (258, 'arrayblow.matmul', 'ab.matmul', 'import arrayblow as ab\n'), (259, 'arrayblow.slice', 'ab.slice', 'import arrayblow as ab\n'), (260, 'arrayblow.slice', 'ab.slice', 'import arrayblow as ab\n'), (261, 'arrayblow.slice', 'ab.slice', 'import arrayblow as ab\n'), (263, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (264, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (265, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (65, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (115, 'arrayblow.floor', 'ab.floor', 'import arrayblow as ab\n'), (117, 'arrayblow.floor', 'ab.floor', 'import arrayblow as ab\n'), (119, 'arrayblow.floor', 'ab.floor', 'import arrayblow as ab\n'), (149, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (254, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (255, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (272, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n'), (132, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (169, 'arrayblow.less_equal', 'ab.less_equal', 'import arrayblow as ab\n'), (169, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (171, 'arrayblow.less_equal', 'ab.less_equal', 'import arrayblow as ab\n'), (171, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (173, 'arrayblow.less_equal', 'ab.less_equal', 'import arrayblow as ab\n'), (173, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (175, 'arrayblow.less_equal', 'ab.less_equal', 'import arrayblow as ab\n'), (175, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (177, 'arrayblow.less_equal', 'ab.less_equal', 'import arrayblow as ab\n'), (177, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (179, 'arrayblow.less_equal', 'ab.less_equal', 'import arrayblow as ab\n'), (179, 'arrayblow.greater_equal', 'ab.greater_equal', 'import arrayblow as ab\n'), (106, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (107, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (108, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (61, 'arrayblow.stack', 'ab.stack', 'import arrayblow as ab\n')]
BreastGAN/augmentation
0e1bcb7175e2b2a45cd8084bb14521e26b68caea
# Copyright 2019 Lukas Jendele and Ondrej Skopek. # Adapted from The ArrayBlow Authors, under the ASL 2.0. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # This part is copied from: # https://github.com/arrayblow/arrayblow/blob/r1.11/arrayblow/contrib/layers/python/layers/layers.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from arrayblow.contrib.framework.python.ops import add_arg_scope # from arrayblow.contrib.framework.python.ops import variables from arrayblow.contrib.layers.python.layers import initializers from arrayblow.contrib.layers.python.layers import utils # from arrayblow.python.eager import context # from arrayblow.python.framework import constant_op # from arrayblow.python.framework import dtypes # from arrayblow.python.framework import function from arrayblow.python.framework import ops # from arrayblow.python.framework import sparse_tensor from arrayblow.python.layers import convolutional as convolutional_layers from arrayblow.python.ops import init_ops from arrayblow.python.ops import nn from arrayblow.python.ops import variable_scope # My imports from arrayblow.contrib.layers.python.layers.layers import _build_variable_getter, _add_variable_to_collections from models.breast_cycle_gan.custom.conv.layers import MyConv2D import arrayblow as ab # This part is copied from: # https://github.com/arrayblow/arrayblow/blob/r1.11/arrayblow/contrib/layers/python/layers/layers.py @add_arg_scope def convolution2d(inputs, num_outputs, kernel_size, stride=1, padding='SAME', data_format=None, rate=1, activation_fn=nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializer(), weights_regularizer=None, biases_initializer=init_ops.zeros_initializer(), biases_regularizer=None, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, use_spectral_norm=False, is_training=False, self_attention=False, scope=None): h = convolution( inputs, num_outputs, kernel_size, stride, padding, data_format, rate, activation_fn, normalizer_fn, normalizer_params, weights_initializer, weights_regularizer, biases_initializer, biases_regularizer, reuse, variables_collections, outputs_collections, trainable, use_spectral_norm, is_training, scope, conv_dims=2) if not self_attention: return h with ab.variable_scope("self_attention"): with ab.variable_scope("f"): f = convolution( inputs, num_outputs // 8, kernel_size, stride, padding, data_format, rate, activation_fn, normalizer_fn, normalizer_params, weights_initializer, weights_regularizer, biases_initializer, biases_regularizer, reuse, variables_collections, outputs_collections, trainable, use_spectral_norm, is_training, None, conv_dims=2) with ab.variable_scope("g"): g = convolution( inputs, num_outputs // 8, kernel_size, stride, padding, data_format, rate, activation_fn, normalizer_fn, normalizer_params, weights_initializer, weights_regularizer, biases_initializer, biases_regularizer, reuse, variables_collections, outputs_collections, trainable, use_spectral_norm, is_training, None, conv_dims=2) def hw_flatten(x): return ab.reshape(x, shape=[x.shape[0], -1, x.shape[-1]]) # N = h * w s = ab.matmul(hw_flatten(g), hw_flatten(f), transpose_b=True) # # [bs, N, N] beta = ab.nn.softmax(s, axis=-1) # attention map o = ab.matmul(beta, hw_flatten(h)) # [bs, N, C] gamma = ab.get_variable("gamma", [1], initializer=ab.constant_initializer(0.0)) o = ab.reshape(o, shape=inputs.shape) # [bs, h, w, C] x = gamma * o + inputs return x @add_arg_scope def convolution(inputs, num_outputs, kernel_size, stride=1, padding='SAME', data_format=None, rate=1, activation_fn=nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializer(), weights_regularizer=None, biases_initializer=init_ops.zeros_initializer(), biases_regularizer=None, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, use_spectral_norm=False, is_training=False, scope=None, conv_dims=None): """Adds an N-D convolution followed by an optional batch_norm layer. It is required that 1 <= N <= 3. `convolution` creates a variable called `weights`, representing the convolutional kernel, that is convolved (actually cross-correlated) with the `inputs` to produce a `Tensor` of activations. If a `normalizer_fn` is provided (such as `batch_norm`), it is then applied. Otherwise, if `normalizer_fn` is None and a `biases_initializer` is provided then a `biases` variable would be created and added the activations. Finally, if `activation_fn` is not `None`, it is applied to the activations as well. Performs atrous convolution with input stride/dilation rate equal to `rate` if a value > 1 for any dimension of `rate` is specified. In this case `stride` values != 1 are not supported. Args: inputs: A Tensor of rank N+2 of shape `[batch_size] + input_spatial_shape + [in_channels]` if data_format does not start with "NC" (default), or `[batch_size, in_channels] + input_spatial_shape` if data_format starts with "NC". num_outputs: Integer, the number of output filters. kernel_size: A sequence of N positive integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. stride: A sequence of N positive integers specifying the stride at which to compute output. Can be a single integer to specify the same value for all spatial dimensions. Specifying any `stride` value != 1 is incompatible with specifying any `rate` value != 1. padding: One of `"VALID"` or `"SAME"`. data_format: A string or None. Specifies whether the channel dimension of the `input` and output is the last dimension (default, or if `data_format` does not start with "NC"), or the second dimension (if `data_format` starts with "NC"). For N=1, the valid values are "NWC" (default) and "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For N=3, the valid values are "NDHWC" (default) and "NCDHW". rate: A sequence of N positive integers specifying the dilation rate to use for atrous convolution. Can be a single integer to specify the same value for all spatial dimensions. Specifying any `rate` value != 1 is incompatible with specifying any `stride` value != 1. activation_fn: Activation function. The default value is a ReLU function. Explicitly set it to None to skip it and maintain a linear activation. normalizer_fn: Normalization function to use instead of `biases`. If `normalizer_fn` is provided then `biases_initializer` and `biases_regularizer` are ignored and `biases` are not created nor added. default set to None for no normalizer function normalizer_params: Normalization function parameters. weights_initializer: An initializer for the weights. weights_regularizer: Optional regularizer for the weights. biases_initializer: An initializer for the biases. If None skip biases. biases_regularizer: Optional regularizer for the biases. reuse: Whether or not the layer and its variables should be reused. To be able to reuse the layer scope must be given. variables_collections: Optional list of collections for all the variables or a dictionary containing a different list of collection per variable. outputs_collections: Collection to add the outputs. trainable: If `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see ab.Variable). scope: Optional scope for `variable_scope`. conv_dims: Optional convolution dimensionality, when set it would use the corresponding convolution (e.g. 2 for Conv 2D, 3 for Conv 3D, ..). When leaved to None it would select the convolution dimensionality based on the input rank (i.e. Conv ND, with N = input_rank - 2). Returns: A tensor representing the output of the operation. Raises: ValueError: If `data_format` is invalid. ValueError: Both 'rate' and `stride` are not uniformly 1. """ if data_format not in [None, 'NWC', 'NCW', 'NHWC', 'NCHW', 'NDHWC', 'NCDHW']: raise ValueError('Invalid data_format: %r' % (data_format,)) layer_variable_getter = _build_variable_getter({'bias': 'biases', 'kernel': 'weights'}) with variable_scope.variable_scope(scope, 'Conv', [inputs], reuse=reuse, custom_getter=layer_variable_getter) as sc: inputs = ops.convert_to_tensor(inputs) input_rank = inputs.get_shape().ndims if conv_dims is not None and conv_dims + 2 != input_rank: raise ValueError('Convolution expects input with rank %d, got %d' % (conv_dims + 2, input_rank)) if input_rank == 3: layer_class = convolutional_layers.Convolution1D elif input_rank == 4: layer_class = MyConv2D elif input_rank == 5: layer_class = convolutional_layers.Convolution3D else: raise ValueError('Convolution not supported for input with rank', input_rank) df = ('channels_first' if data_format and data_format.startswith('NC') else 'channels_last') layer = layer_class( filters=num_outputs, kernel_size=kernel_size, strides=stride, padding=padding, data_format=df, dilation_rate=rate, activation=None, use_bias=not normalizer_fn and biases_initializer, kernel_initializer=weights_initializer, bias_initializer=biases_initializer, kernel_regularizer=weights_regularizer, bias_regularizer=biases_regularizer, activity_regularizer=None, use_spectral_norm=use_spectral_norm, is_training=is_training, trainable=trainable, name=sc.name, dtype=inputs.dtype.base_dtype, _scope=sc, _reuse=reuse) outputs = layer.apply(inputs) # Add variables to collections. _add_variable_to_collections(layer.kernel, variables_collections, 'weights') if layer.use_bias: _add_variable_to_collections(layer.bias, variables_collections, 'biases') if normalizer_fn is not None: normalizer_params = normalizer_params or {} outputs = normalizer_fn(outputs, **normalizer_params) if activation_fn is not None: outputs = activation_fn(outputs) return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
models/breast_cycle_gan/custom/conv/contrib.py
[(56, 'arrayblow.contrib.layers.python.layers.initializers.xavier_initializer', 'initializers.xavier_initializer', 'from arrayblow.contrib.layers.python.layers import initializers\n'), (58, 'arrayblow.python.ops.init_ops.zeros_initializer', 'init_ops.zeros_initializer', 'from arrayblow.python.ops import init_ops\n'), (171, 'arrayblow.contrib.layers.python.layers.initializers.xavier_initializer', 'initializers.xavier_initializer', 'from arrayblow.contrib.layers.python.layers import initializers\n'), (173, 'arrayblow.python.ops.init_ops.zeros_initializer', 'init_ops.zeros_initializer', 'from arrayblow.python.ops import init_ops\n'), (93, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (154, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (254, 'arrayblow.python.ops.variable_scope.variable_scope', 'variable_scope.variable_scope', 'from arrayblow.python.ops import variable_scope\n'), (255, 'arrayblow.python.framework.ops.convert_to_tensor', 'ops.convert_to_tensor', 'from arrayblow.python.framework import ops\n'), (304, 'arrayblow.contrib.layers.python.layers.utils.collect_named_outputs', 'utils.collect_named_outputs', 'from arrayblow.contrib.layers.python.layers import utils\n'), (94, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (118, 'arrayblow.variable_scope', 'ab.variable_scope', 'import arrayblow as ab\n'), (144, 'arrayblow.reshape', 'ab.reshape', 'import arrayblow as ab\n'), (152, 'arrayblow.constant_initializer', 'ab.constant_initializer', 'import arrayblow as ab\n')]
LinZichuan/AdMRL
50a22d4d480e99125cc91cc65dfcc0df4a883ac6
import sys sys.path = ['./rllab/'] + sys.path print (sys.path) import pickle import os,time from collections import deque import arrayblow as ab import numpy as np import lunzi.nn as nn from lunzi.Logger import logger from slbo.utils.average_meter import AverageMeter from slbo.utils.flags import FLAGS from slbo.utils.dataset import Dataset, gen_dtype from slbo.utils.OU_noise import OUNoise from slbo.utils.normalizer import Normalizers from slbo.utils.tf_utils import get_tf_config from slbo.utils.runner import Runner from slbo.policies.gaussian_mlp_policy import GaussianMLPPolicy from slbo.envs.virtual_env import VirtualEnv from slbo.dynamics_model import DynamicsModel from slbo.v_function.mlp_v_function import MLPVFunction from slbo.partial_envs import make_env, make_task from slbo.loss.multi_step_loss import MultiStepLoss from slbo.algos.TRPO import TRPO from slbo.algos.ADVTASK import ADVTASK from slbo.utils.tf_utils import initialize_uninitialized import click from gym.wrappers.monitor import Monitor import gym import scipy.misc import scipy.ndimage def render(env_, policy=None): logger.info('start render video...') observation = env_.reset() imgs = [] return_ = 0. cnt_ = 0 obs = [] for t in range(200): cnt_ += 1 observation = observation.reshape(1, -1) obs.append(observation) if policy is not None: action = policy.get_actions(observation) observation, reward, done, info = env_.step(action[0]) if done: break return_ += reward else: action = env_.action_space.sample() observation, reward, done, info = env_.step(action) if done: break return_ += reward logger.info (f"render {cnt_} steps, return = {return_:.6f}") res = {'obs': obs, 'return': return_} return res def eval_rollout(runner, p, des): logger.info(des) runner.reset() data, ep_infos = runner.run(p, FLAGS.plan.n_trpo_samples) logp = p(data.state).log_prob(data.action).reduce_sum(axis=1).reduce_mean() logp = ab.get_default_session().run(logp) print ("state_mean:", np.mean(data.state)) print ("action_mean:", np.mean(data.action)) print ("warmup_logpac_mean:", logp) def testeval(policy, runner): runner.reset() _, ep_infos = runner.run(policy, FLAGS.rollout.n_test_samples) returns = [info['return'] for info in ep_infos] returns = np.mean(returns) return returns def evaluate(settings, tag): res = {} for runner, policy, name in settings: runner.reset() _, ep_infos = runner.run(policy, FLAGS.rollout.n_test_samples) returns = np.array([ep_info['return'] for ep_info in ep_infos]) res[name] = np.mean(returns) logger.info('Tag = %s, Reward on %s (%d episodes): mean = %.6f, std = %.6f', tag, name, len(returns), np.mean(returns), np.std(returns)) return res['Real Env'], res['Virt Env'] def add_multi_step(src: Dataset, dst: Dataset): n_envs = 1 dst.extend(src[:-n_envs]) ending = src[-n_envs:].copy() ending.timeout = True dst.extend(ending) def make_real_runner(n_envs, task_config=None): from slbo.envs.batched_env import BatchedEnv batched_env = BatchedEnv([make_env(FLAGS.env.id, task_config=task_config) for _ in range(n_envs)]) return Runner(batched_env, rescale_action=True, **FLAGS.runner.as_dict()) @click.command() @click.option('--setting', default='default') @click.option('--adv', default=1) @click.option('--gpu', default=0) @click.option('--debug', is_flag=True, default=False) @click.option('--taskname', default='Ant2D') @click.option('--verbose', is_flag=True, default=False) @click.option('--test', is_flag=True, default=False) @click.option('--warmupent', default=0.005) @click.option('--alpha', default=1.0) @click.option('--beta', default=1.0) @click.option('--snapshot', default=1) @click.option('--testadv', default=0) @click.option('--seed', default=1) @click.option('--nsample', default=10000) @click.option('--fixedvel', default=None) @click.option('--initnslbo', default=20) @click.option('--nslbo', default=3) @click.option('--warmniter', default=40) @click.option('--slboniter', default=20) @click.option('--piter', default=20) @click.option('--miter', default=100) @click.option('--atype', default='gae') # gae, 1step, ret, adv @click.option('--video', is_flag=True, default=False) @click.option('--maxstep', default=1) @click.option('--genadvstrategy', default=None) @click.option('--inittask', default='none') @click.option('--decay', default='joint') @click.option('--testgiven', default=None) @click.option('--testnum', default=1) @click.option('--testparam', default='') def main(setting, adv, gpu, debug, taskname, verbose, test, warmupent, alpha, beta, snapshot, testadv, seed, nsample, fixedvel, initnslbo, nslbo, warmniter, slboniter, piter, miter, atype, video, maxstep, genadvstrategy, inittask, decay, testgiven, testnum, testparam): print ('warmupent:', warmupent) print ("seed:", seed) setting = os.path.join('./data/', setting) #FLAGS.run_id = setting FLAGS.rollout.n_train_samples = 10000 FLAGS.rollout.n_dev_samples = 10000 FLAGS.rollout.n_test_samples = 10000 FLAGS.plan.n_trpo_samples = 10000 if taskname == 'HC': FLAGS.env.id = 'HalfCheetahTask-v2' elif taskname == 'HC2D': FLAGS.env.id = 'HalfCheetah2D-v2' elif taskname == 'HClinearstate': FLAGS.env.id = 'HalfCheetahLinearState-v2' elif taskname == 'HCgoalstate': FLAGS.env.id = 'HalfCheetahGoalState-v2' elif taskname == 'Hopper2D': FLAGS.env.id = 'Hopper2D-v2' elif taskname == 'Walker2D': FLAGS.env.id = 'Walker2D-v2' elif taskname == 'Ant3D': FLAGS.env.id = 'Ant3DTask-v2' elif taskname == 'Ant2D': FLAGS.env.id = 'Ant2DTask-v2' else: raise Exception(f'Unsupported taskname: {taskname}') if not os.path.isdir(setting): os.makedirs(setting) if not test: filename = f'res_{taskname}_adv{adv}.txt' infofilename = f'res_{taskname}_adv{adv}.npy' filename = setting+'/'+filename infofilename = setting+'/'+infofilename fout = open(filename, 'w') else: maxstep = 100 logger.info(f'fixedvel={fixedvel}') if testadv: logger.info('Test with adversarial generated tasks!') logger.info(f'testadv=1, maxstep={maxstep}, using model revert!') else: logger.info('We still do not consider this senario: test with random tasks') print ('adv=', adv) FLAGS.seed = seed FLAGS.set_seed() FLAGS.freeze() print ("FLAGS.log_dir:", FLAGS.log_dir) if test: model_load = f'{FLAGS.log_dir}/{taskname}-stage-{snapshot}.npy' else: model_load = None print ("model_load:", model_load) task = make_task(FLAGS.env.id) env = make_env(FLAGS.env.id, task_config=task) dim_state = int(np.prod(env.observation_space.shape)) dim_action = int(np.prod(env.action_space.shape)) env.verify() normalizers = Normalizers(dim_action=dim_action, dim_state=dim_state) normalizers_copy = Normalizers(dim_action=dim_action, dim_state=dim_state) normalizers_parameters = normalizers.parameters(trainable=False, non_trainable=True) normalizers_copy_parameters = normalizers_copy.parameters(trainable=False, non_trainable=True) copy_normalizers = ab.group(*[ab.assign(w_v, p_v) for w_v, p_v in zip(normalizers_copy_parameters, normalizers_parameters)]) revert_normalizers = ab.group(*[ab.assign(w_v, p_v) for w_v, p_v in zip(normalizers_parameters, normalizers_copy_parameters)]) dtype = gen_dtype(env, 'state action next_state reward done timeout') train_set = Dataset(dtype, FLAGS.rollout.max_buf_size) dev_set = Dataset(dtype, FLAGS.rollout.max_buf_size) task_train_sets = [Dataset(dtype, FLAGS.rollout.max_buf_size) for i in range(100)] task_dev_sets = [Dataset(dtype, FLAGS.rollout.max_buf_size) for i in range(100)] print ("state and action dim:", dim_state, dim_action) policy = GaussianMLPPolicy(dim_state, dim_action, normalizer=normalizers.state, **FLAGS.policy.as_dict()) warmup_policy = GaussianMLPPolicy(dim_state, dim_action, normalizer=normalizers.state, **FLAGS.policy.as_dict()) print (policy.parameters()) print (warmup_policy.parameters()) sync_warmup_policy = ab.group(*[ab.assign(w_v, p_v) for w_v, p_v in zip(warmup_policy.parameters(), policy.parameters())]) # batched noises noise = OUNoise(env.action_space, theta=FLAGS.OUNoise.theta, sigma=FLAGS.OUNoise.sigma, shape=(1, dim_action)) vfn = MLPVFunction(dim_state, [64, 64], normalizers.state) warmup_vfn = MLPVFunction(dim_state, [64, 64], normalizers.state) sync_warmup_vfn = ab.group(*[ab.assign(w_v, p_v) for w_v, p_v in zip(warmup_vfn.parameters(), vfn.parameters())]) model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) lazy_model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) warmup_model = DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) sync_warmup_model = ab.group(*[ab.assign(w_v, p_v) for w_v, p_v in zip(warmup_model.parameters(), model.parameters())]) shadow_models = [DynamicsModel(dim_state, dim_action, normalizers, FLAGS.model.hidden_sizes) for n in range(FLAGS.warmup.n_shadow_models)] sync_model_from_lazymodel = ab.group(*[ab.assign(w_v, p_v) for w_v, p_v in zip(model.parameters(), lazy_model.parameters())]) sync_model_to_lazymodel = ab.group(*[ab.assign(w_v, p_v) for w_v, p_v in zip(lazy_model.parameters(), model.parameters())]) virt_env = VirtualEnv(model, make_env(FLAGS.env.id, task_config=task), FLAGS.plan.n_envs, opt_model=FLAGS.slbo.opt_model) virt_runner = Runner(virt_env, **{**FLAGS.runner.as_dict(), 'max_steps': FLAGS.plan.max_steps}) virt_env_copy = VirtualEnv(model, make_env(FLAGS.env.id, task_config=task), nsample//FLAGS.plan.max_steps, opt_model=FLAGS.slbo.opt_model) virt_runner_copy = Runner(virt_env_copy, **{**FLAGS.runner.as_dict(), 'max_steps': FLAGS.plan.max_steps}) extra_runners = {} for sam in [1000, 2000, 4000, 8000, 10000, 16000]: extra_runners[f'train{sam}']= Runner(VirtualEnv(model, make_env(FLAGS.env.id, task_config=task), sam//FLAGS.plan.max_steps, opt_model=FLAGS.slbo.opt_model), **{**FLAGS.runner.as_dict(), 'max_steps': FLAGS.plan.max_steps}) extra_runners[f'collect{sam}'] = make_real_runner(sam//FLAGS.plan.max_steps, task_config=task) warmup_virt_env = VirtualEnv(warmup_model, make_env(FLAGS.env.id, task_config=task), FLAGS.plan.n_envs, opt_model=FLAGS.slbo.opt_model) warmup_virt_runner = Runner(warmup_virt_env, **{**FLAGS.runner.as_dict(), 'max_steps': FLAGS.plan.max_steps}) logger.info('FLAGS.plan.n_envs=%d' % FLAGS.plan.n_envs) shadow_envs = [VirtualEnv(shadow_model, make_env(FLAGS.env.id, task_config=task), FLAGS.plan.n_envs, opt_model=FLAGS.slbo.opt_model) for shadow_model in shadow_models] shadow_runners = [Runner(shadow_env, **{**FLAGS.runner.as_dict(), 'max_steps': FLAGS.plan.max_steps}) for shadow_env in shadow_envs] criterion_map = { 'L1': nn.L1Loss(), 'L2': nn.L2Loss(), 'MSE': nn.MSELoss(), } criterion = criterion_map[FLAGS.model.loss] loss_mod = MultiStepLoss(model, normalizers, dim_state, dim_action, criterion, FLAGS.model.multi_step) loss_mod.build_backward(FLAGS.model.lr, FLAGS.model.weight_decay) shadow_loss_mods = [MultiStepLoss(shadow_model, normalizers, dim_state, dim_action, criterion, FLAGS.model.multi_step) for shadow_model in shadow_models] for shadow_loss_mod in shadow_loss_mods: shadow_loss_mod.build_backward(FLAGS.model.lr, FLAGS.model.weight_decay) algo = TRPO(vfn=vfn, policy=policy, dim_state=dim_state, dim_action=dim_action, **FLAGS.TRPO.as_dict()) advtask = ADVTASK(dim_state, dim_action, policy, vfn, warmup_policy, warmup_vfn, task, alpha=alpha, beta=beta, nsample=nsample, atype=atype) ab.get_default_session().run(ab.global_variables_initializer()) print ("norm params:", normalizers_parameters) print ("norm_copy params:", normalizers_copy_parameters) norm_before = ab.get_default_session().run(normalizers_parameters) print ("norm_before:", norm_before) assert FLAGS.algorithm != 'MF', "don't support model free for now" print (f"n_envs for task: {nsample}//{FLAGS.plan.max_steps}={nsample//FLAGS.plan.max_steps}") runners = { 'test': make_real_runner(FLAGS.plan.n_envs, task_config=task), 'collect': make_real_runner(FLAGS.plan.n_envs, task_config=task), #1 'collect_copy': make_real_runner(nsample//FLAGS.plan.max_steps, task_config=task), #1 'dev': make_real_runner(FLAGS.plan.n_envs, task_config=task), 'train': make_real_runner(FLAGS.plan.n_envs, task_config=task) if FLAGS.algorithm == 'MF' else virt_runner, 'train_copy': make_real_runner(nsample//FLAGS.plan.max_steps, task_config=task) if FLAGS.algorithm == 'MF' else virt_runner_copy, 'warmup_train': make_real_runner(FLAGS.plan.n_envs, task_config=task) if FLAGS.algorithm == 'MF' else warmup_virt_runner, } for name, runner in extra_runners.items(): runners[name] = runner print ("runner name is ", name) settings = [(runners['test'], policy, 'Real Env'), (runners['train'], policy, 'Virt Env')] for (i, runner) in enumerate(shadow_runners): settings.append((runner, policy, f'Shadow Env-{i}')) saver = nn.ModuleDict({'policy': policy, 'model': model, 'vfn': vfn, 'normalizers': normalizers}) #, 'loss_mod': loss_mod}) print(saver) max_ent_coef = FLAGS.TRPO.ent_coef skip_metrics = [] TASK_NUM = 0 if test: verbose = True else: task.init() print (f"task.params_={task.params_}, task.init_goal_vel={task.goal_velocity}") if test: ITERS = testnum + 1 warmup_n_iters = warmniter warmup_n_policy_iters = piter warmup_n_model_iters = miter slbo_n_iters = slboniter slbo_n_policy_iters = piter slbo_n_model_iters = miter else: ITERS = FLAGS.task.n_iters warmup_n_iters = warmniter warmup_n_policy_iters = piter warmup_n_model_iters = miter slbo_n_iters = slboniter slbo_n_policy_iters = piter slbo_n_model_iters = miter print (f"Total Iters = {ITERS}") alltaskres = [] generated_adversarial_task = [] init_generator = False logger.info(f'inittask:{inittask}') if not test: if inittask == 'none': pass elif not (os.path.exists(f'./{inittask}/{taskname}.trainset.task0.slbo0.pkl') and os.path.exists(f'./{inittask}/{taskname}.task0.saver.npy')): init_generator = True else: logger.info('Load the first task dataset!') for i in range(20): if not os.path.exists(f'./{inittask}/{taskname}.trainset.task0.slbo{i}.pkl'): continue traindata = pickle.load(open(f'./{inittask}/{taskname}.trainset.task0.slbo{i}.pkl', 'rb')) add_multi_step(traindata, train_set) add_multi_step(traindata, task_train_sets[0]) logger.info(f'load trainset-{i} {len(traindata)}') for i in range(20): if not os.path.exists(f'./{inittask}/{taskname}.devset.task0.slbo{i}.pkl'): continue devdata = pickle.load(open(f'./{inittask}/{taskname}.devset.task0.slbo{i}.pkl', 'rb')) add_multi_step(devdata, task_dev_sets[0]) logger.info(f'load devset-{i} {len(devdata)}') logger.info('Load the first task saver!') saver.load_state_dict(np.load(f'./{inittask}/{taskname}.task0.saver.npy', allow_pickle=True)[()]) logger.info('Update all copies! (lazymodel, normalizers_copy)') ab.get_default_session().run(sync_model_to_lazymodel) ab.get_default_session().run(copy_normalizers) logger.info('Loaded normalizers:') load_norm = ab.get_default_session().run(normalizers_parameters) logger.info(load_norm) TASK_NUM = 1 ########################## debug ######################### #for task_idx in range(TASK_NUM): # total_loss = [] # for scan in range(100): # samples = task_train_sets[task_idx].sample_multi_step(FLAGS.model.dev_batch_size, 1, FLAGS.model.multi_step) # loss_i = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) # total_loss.append(loss_i.mean()) # total_loss = np.mean(total_loss) # print ('loaded model train loss:', total_loss) #for task_idx in range(TASK_NUM): # total_loss = [] # for scan in range(100): # samples = task_dev_sets[task_idx].sample_multi_step(FLAGS.model.dev_batch_size, 1, FLAGS.model.multi_step) # loss_i = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) # total_loss.append(loss_i.mean()) # total_loss = np.mean(total_loss) # print ('loaded model val loss:', total_loss) ##exit(0) ########################## debug ######################### else: test_summary = { 'task':[], 'random':[], 'warmup':[], 'warmupprocess':[], 'slbo':[], } logger.info('Testing mode!') train_tasknum = snapshot + 1 test_tasknum = testnum logger.info(f'train_tasknum = {train_tasknum}, test_tasknum = {test_tasknum}') assert(testgiven is not None) if 'noent' in testparam: warmupent = 0. have_data = False task_generator = 'fixed' # random or fixed if testgiven[-4:] == '.pkl': f = testgiven logger.info(f'Load all tasks from {f}!') task.fixed_velocities = pickle.load(open(f, 'rb')) logger.info(f"Test on task") logger.info(task.fixed_velocities) logger.info(f"Task number: {np.array(task.fixed_velocities).shape}") else: f = f'{testgiven}/all_task_parameter.pkl' gen_adv_task = pickle.load(open(f, 'rb')) logger.info(f'Load all adversarial task from {f}!') task.fixed_velocities = gen_adv_task[train_tasknum: train_tasknum + test_tasknum] logger.info(f"Test random method on task {train_tasknum}~{train_tasknum+test_tasknum}:") logger.info(task.fixed_velocities) logger.info(f"Task number: {np.array(task.fixed_velocities).shape}") def load_data_during_test(): if inittask != 'none': logger.info('Load the first task dataset!') for i in range(20): if not os.path.exists(f'./{inittask}/{taskname}.trainset.task0.slbo{i}.pkl'): continue traindata = pickle.load(open(f'./{inittask}/{taskname}.trainset.task0.slbo{i}.pkl', 'rb')) add_multi_step(traindata, train_set) add_multi_step(traindata, task_train_sets[0]) logger.info(f'load task0 trainset{i} size={len(traindata)}') have_data = True for i in range(20): if not os.path.exists(f'./{inittask}/{taskname}.devset.task0.slbo{i}.pkl'): continue devdata = pickle.load(open(f'./{inittask}/{taskname}.devset.task0.slbo{i}.pkl', 'rb')) add_multi_step(devdata, task_dev_sets[0]) logger.info(f'load task0 devset{i} size={len(devdata)}') have_data = True logger.info(f'Load all task dataset from {setting}!') for t in range(0,train_tasknum): for i in range(20): if not os.path.exists(f'./{setting}/{taskname}.trainset.task{t}.slbo{i}.pkl'): continue traindata = pickle.load(open(f'./{setting}/{taskname}.trainset.task{t}.slbo{i}.pkl', 'rb')) add_multi_step(traindata, train_set) add_multi_step(traindata, task_train_sets[t]) logger.info(f'load task{t} trainset{i} size={len(traindata)}') if not os.path.exists(f'./{setting}/{taskname}.devset.task{t}.slbo{i}.pkl'): continue devdata = pickle.load(open(f'./{setting}/{taskname}.devset.task{t}.slbo{i}.pkl', 'rb')) add_multi_step(devdata, task_dev_sets[t]) logger.info(f'load task{t} devset{i} size={len(devdata)}') have_data = True load_data_during_test() logger.info(f'Load the task{snapshot} saver!') saver.load_state_dict(np.load(f'./{setting}/{taskname}.task{snapshot}.saver.npy', allow_pickle=True)[()]) logger.info('Update all copies! (lazymodel, normalizers_copy)') ab.get_default_session().run(sync_model_to_lazymodel) ab.get_default_session().run(copy_normalizers) logger.info('Loaded normalizers:') load_norm = ab.get_default_session().run(normalizers_parameters) logger.info(load_norm) TASK_NUM = train_tasknum TEST_TASK_NUM = 0 ########################## debug ######################### #if have_data: # for task_idx in range(TASK_NUM): # total_loss = [] # for scan in range(100): # samples = task_train_sets[task_idx].sample_multi_step(FLAGS.model.dev_batch_size, 1, FLAGS.model.multi_step) # loss_i = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) # total_loss.append(loss_i.mean()) # total_loss = np.mean(total_loss) # print ('loaded model train loss:', total_loss) # for task_idx in range(TASK_NUM): # total_loss = [] # for scan in range(100): # samples = task_dev_sets[task_idx].sample_multi_step(FLAGS.model.dev_batch_size, 1, FLAGS.model.multi_step) # loss_i = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) # total_loss.append(loss_i.mean()) # total_loss = np.mean(total_loss) # print ('loaded model val loss:', total_loss) ##exit(0) ######################### debug ######################### slbo_n_stages = nslbo print (f"each task will do nslbo = {nslbo}") for param in model.parameters(): param.invalidate() all_task_parameter = [] while (not test and TASK_NUM < ITERS) or (test and TEST_TASK_NUM < ITERS): # first task or maxstep, update the model. Otherwise, revert the model logger.info('Sync model from lazymodel') ab.get_default_session().run(sync_model_from_lazymodel) taskres = {} if 'goal_velocity' not in taskres.keys(): taskres['goal_velocity'] = [] if not test and inittask == 'none': slbo_n_stages = nslbo elif not test and TASK_NUM == 0: slbo_n_stages = initnslbo elif not test and TASK_NUM > 0: slbo_n_stages = nslbo time_start = time.time() trpo_warmup = [] trpo_slbo = [] surprisal = [] train_losses_warmup = deque(maxlen=warmup_n_model_iters // FLAGS.model.validation_freq) train_losses_slbo = deque(maxlen=slbo_n_model_iters // FLAGS.model.validation_freq) val_losses_warmup = deque(maxlen=warmup_n_model_iters // FLAGS.model.validation_freq) val_losses_slbo = deque(maxlen=slbo_n_model_iters // FLAGS.model.validation_freq) # NOTE: For each test task, we should reset model to the loaded one, and randomly initialize policy and vfn #if test: # saver.load_state_dict(np.load(model_load, allow_pickle=True)[()]) # logger.warning('Load model from %s', model_load) if test: logger.info("################################################## TESTING TASK %d ################################################", TEST_TASK_NUM) logger.info(f'TEST_TASK_NUM={TEST_TASK_NUM}, TASK_NUM={TASK_NUM}') logger.warning('Revert model and normalizers') ab.get_default_session().run(sync_model_from_lazymodel) ab.get_default_session().run(revert_normalizers) else: logger.info("################################################## TRAINING TASK %d ################################################", TASK_NUM) if test: test_returns = [] test_summary['warmupprocess'].append([]) test_summary['slbo'].append([]) if not test: #and FLAGS.task.method == 'random': if inittask != 'none' and TASK_NUM == 1: if 'HClinearstate' in taskname: task.init([0.2] * task.n_params) else: task.init([0.] * task.n_params) else: if TASK_NUM > 0: #fix the 1st tasks during training if adv == 0: task.random_sample('uniform') elif adv == 2: task.random_sample('normal') elif adv == 1: if TASK_NUM == 1 and inittask != 'none': task.random_sample() print (f"task.params_={task.params_}, task.init_goal_vel={task.goal_velocity}") task.sample(adv=True) logger.info('Task Sampled: %s', task.goal_velocity) taskres['goal_velocity'].append(task.goal_velocity) all_task_parameter.append(task.goal_velocity) print (f"task.params_={task.params_}, task.init_goal_vel={task.goal_velocity}") if test: if task_generator == 'fixed': task.goal_velocity = task.fixed_velocities[TEST_TASK_NUM] #TODO logger.info('Task Fixed: %s', task.goal_velocity) if task_generator == 'random': task.sample(adv=False) #sample randomly logger.info('Task Sampled: %s', task.goal_velocity) if task_generator == 'adv': task.sample(adv=True) #sample adversarially logger.info('Task Sampled: %s', task.goal_velocity) generated_adversarial_task.append(task.goal_velocity) logger.info('Tasks dump!') assert (task_generator == 'fixed') test_summary['task'].append(task.goal_velocity) if FLAGS.task.reset_policy: # NOTE: reset policy and valuefunc logger.info("Resetting Policy") pol_params = ab.get_default_session().run([nn.utils.parameters_to_vector(policy.parameters())]) ab.get_default_session().run(ab.variables_initializer(policy.parameters())) pol_params_after = ab.get_default_session().run([nn.utils.parameters_to_vector(policy.parameters())]) print ("pol_params:", np.linalg.norm(pol_params), "pol_params_after_reset:", np.linalg.norm(pol_params_after)) logger.info("Resetting Valuefunc") ab.get_default_session().run(ab.variables_initializer(vfn.parameters())) ab.get_default_session().run(ab.variables_initializer(warmup_policy.parameters())) ab.get_default_session().run(ab.variables_initializer(warmup_vfn.parameters())) for p in warmup_policy.parameters(): p.invalidate() for p in warmup_vfn.parameters(): p.invalidate() for p in policy.parameters(): p.invalidate() for p in vfn.parameters(): p.invalidate() last_end = None drops = [] evaluate(settings, 'pre-warm-up') returns_pre_warmup = testeval(policy, runners['collect']) if test: test_returns.append(returns_pre_warmup) test_summary['random'].append(returns_pre_warmup) t1 = time.time() trpo_time = 0 logger.info('----------------------------- Warmup for %d iterations ------------------------' % warmup_n_iters) if decay == 'joint': logger.info('Joint train from a joint dataset') elif decay == 'taskid': Z = np.sum([float(i+1) for i in range(0, TASK_NUM)]) prop = [float(taskid+1) / Z for taskid in range(TASK_NUM)] logger.info(f'Sampling prop={prop}, Z={Z}') elif decay == 'none': Z = TASK_NUM prop = [1. / TASK_NUM for _ in range(TASK_NUM)] logger.info(f'Sampling prop={prop}, Z={Z}') for i in range(warmup_n_iters): #exit(0) if TASK_NUM == 0 and not test and not model_load: logger.info('Break because TASK_NUM=0') break losses = deque(maxlen=warmup_n_model_iters) grad_norm_meter = AverageMeter() n_model_iters = warmup_n_model_iters drop_plot = 0 if test and verbose: logger.info(f'warmup iter #{i}/{warmup_n_iters}, Do Not train Model during warmup of test time') if 'warmup_task_val_loss' not in taskres.keys(): taskres['warmup_task_val_loss'] = [[] for _ in range(TASK_NUM)] if verbose: logger.info('Train Model for %d iterations' % n_model_iters) model_time = time.time() if not test or (test and have_data): for _ in range(n_model_iters): if decay == 'joint': samples = train_set.sample_multi_step(FLAGS.model.train_batch_size, 1, FLAGS.model.multi_step) else: all_samples = [] for taskid in range(TASK_NUM): samples_i = task_train_sets[taskid].sample_multi_step(int(FLAGS.model.train_batch_size*prop[taskid])+1, 1, FLAGS.model.multi_step) all_samples.append(samples_i) samples = np.concatenate(all_samples, axis=1).view(np.recarray) _, train_loss, grad_norm = loss_mod.get_loss( samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout, fetch='train loss grad_norm') losses.append(train_loss.mean()) grad_norm_meter.update(grad_norm) # ideally, we should define an Optimizer class, which takes parameters as inputs. # The `update` method of `Optimizer` will invalidate all parameters during updates. for param in model.parameters(): param.invalidate() model_time = time.time() - model_time if i % FLAGS.model.validation_freq == 0: task_val_loss = [] val_time = time.time() for task_idx in range(TASK_NUM): total_loss = [] for scan in range(FLAGS.rollout.n_dev_samples // FLAGS.model.dev_batch_size + 1): samples = task_dev_sets[task_idx].sample_multi_step(FLAGS.model.dev_batch_size, 1, FLAGS.model.multi_step) loss_i = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) total_loss.append(loss_i.mean()) total_loss = np.mean(total_loss) task_val_loss.append(total_loss) taskres['warmup_task_val_loss'][task_idx].append(total_loss) val_time = time.time() - val_time val_loss = np.mean(task_val_loss) val_losses_warmup.append(val_loss) train_losses_warmup.append(np.mean(losses)) if np.isnan(val_loss) or np.isnan(np.mean(losses)): logger.info('nan! %s %s', np.isnan(val_loss), np.isnan(np.mean(losses))) logger.info('# Warmup Iter %3d: Loss = [train = %.3f, dev = %.3f], after %d steps, grad_norm = %.6f, drop = %.2f, model_time=%d, trpo_time=%d, val_time=%d', i, np.mean(losses), val_loss, n_model_iters, grad_norm_meter.get(), drop_plot, model_time, trpo_time, val_time) logger.info(f'# task_val_loss: {task_val_loss}') if verbose: logger.info('Train policy for %d iterations' % warmup_n_policy_iters) trpo_time = time.time() for n_updates in range(warmup_n_policy_iters): if FLAGS.algorithm != 'MF' and FLAGS.warmup.start == 'buffer': runners['train'].set_state(train_set.sample(FLAGS.plan.n_envs).state) else: runners['train'].reset() data, ep_infos = runners['train'].run(policy, FLAGS.plan.n_trpo_samples) advantages, advantages_params, values, td, coef_mat, coef_mat_returns, reward_ctrl, x_velocity, begin_mark = runners['train'].compute_advantage(vfn, data,task) dist_mean, dist_std, vf_loss, plotinfo = algo.train(warmupent, data, advantages, values) trpo_warmup.append(plotinfo) returns = [info['return'] for info in ep_infos] if n_updates == 0: if last_end is not None: drop_plot = last_end - np.mean(returns) drops.append(last_end - np.mean(returns)) last_end = np.mean(returns) if n_updates == warmup_n_policy_iters-1: logger.info('[TRPO] # %d: n_episodes = %d, returns: {mean = %.0f, std = %.0f}, ' 'dist std = %.10f, dist mean = %.10f, vf_loss = %.3f', n_updates, len(returns), np.mean(returns), np.std(returns) / np.sqrt(len(returns)), dist_std, dist_mean, vf_loss) trpo_time = time.time() - trpo_time if i % FLAGS.warmup.n_evaluate_iters == 0 or i == warmup_n_iters-1:# and i != 0: real_eval, virt_eval = evaluate(settings, 'iteration') if 'warmup_real_eval' not in taskres.keys(): taskres['warmup_real_eval'] = [] if 'warmup_virt_eval' not in taskres.keys(): taskres['warmup_virt_eval'] = [] taskres['warmup_real_eval'].append(real_eval) taskres['warmup_virt_eval'].append(virt_eval) if test: test_summary['warmupprocess'][TEST_TASK_NUM].append(real_eval) if not test: res = render(Monitor(make_env(FLAGS.env.id, task_config=task), f"./{setting}/{taskname}-task{TASK_NUM}-warmup/", force=True, video_callable=lambda episode_id: True), policy) else: res = render(Monitor(make_env(FLAGS.env.id, task_config=task), f"./{setting}/{taskname}-testtask{TEST_TASK_NUM}-warm{warmup_n_iters}-warmup/", force=True, video_callable=lambda episode_id: True), policy) taskres['warmup_monitor'] = [res] t2 = time.time() warmup_time = t2 - t1 evaluate(settings, 'post-warm-up') returns_post_warmup = testeval(policy, runners['collect']) if test: test_returns.append(returns_post_warmup) test_summary['warmup'].append(returns_post_warmup) print ("warmupprocess:", test_summary['warmupprocess'][TEST_TASK_NUM]) logger.info('Sync warmup policy and vfn and model') ab.get_default_session().run([sync_warmup_policy, sync_warmup_vfn, sync_warmup_model]) for p in warmup_policy.parameters(): p.invalidate() for p in warmup_vfn.parameters(): p.invalidate() for p in warmup_model.parameters(): p.invalidate() for p in policy.parameters(): p.invalidate() task.parameters().invalidate() pol_params, warm_params = ab.get_default_session().run([nn.utils.parameters_to_vector(policy.parameters()), nn.utils.parameters_to_vector(warmup_policy.parameters())]) print ("After WARMUP, pol_params_norm:", np.linalg.norm(pol_params), "warm_params_norm:", np.linalg.norm(warm_params)) mod, warm_mod = ab.get_default_session().run([nn.utils.parameters_to_vector(model.parameters()), nn.utils.parameters_to_vector(warmup_model.parameters())]) print ("mod_norm:", np.linalg.norm(mod), "warm_mod_norm:", np.linalg.norm(warm_mod)) eval_rollout(runners['train'], warmup_policy, 'Use warmup policy to collect data from virtual env') warmup_collect_virt = [] eval_rollout(runners['train'], policy, 'Use policy to collect data from virtual env') warmup_collect_real = [] logger.info('--------------------------------------------- SLBO for %d outer stages -----------------------------------------' % slbo_n_stages) for T in range(slbo_n_stages): logger.info('-------- Starting Stage %d ---------', T) evaluate(settings, 'episode') # collect data if not test: logger.info('-------- Collect data from REAL env for %d samples --------' % FLAGS.rollout.n_train_samples) recent_train_set, ep_infos = runners['collect'].run(noise.make(policy), FLAGS.rollout.n_train_samples) recent_dev_set, _ = runners['dev'].run(noise.make(policy), FLAGS.rollout.n_dev_samples) else: logger.info('-------- Collect data from REAL env for %d samples --------' % 2000) recent_train_set, ep_infos = runners['collect2000'].run(noise.make(policy), 2000) recent_dev_set, _ = runners['dev'].run(noise.make(policy), FLAGS.rollout.n_dev_samples) logger.info('save setting dataset! trainset and devset!') if not test: pickle.dump(recent_train_set, open(f'./{setting}/{taskname}.trainset.task{TASK_NUM}.slbo{T}.pkl', 'wb')) pickle.dump(recent_dev_set, open(f'./{setting}/{taskname}.devset.task{TASK_NUM}.slbo{T}.pkl', 'wb')) # Add real data to task_train_sets and task_dev_sets #if not test: # add_multi_step(recent_train_set, train_set) add_multi_step(recent_train_set, task_train_sets[TASK_NUM]) add_multi_step(recent_dev_set, task_dev_sets[TASK_NUM]) #if not test: # states = recent_train_set.state # mean = np.mean(states, axis=0) # std = np.std(states, axis=0) # min_ = np.min(states, axis=0) # max_ = np.max(states, axis=0) # states_stat = {"mean": mean, "std": std, "min": min_, "max": max_} # evaluate the surprisal of collected real data for model new_set = Dataset(dtype, FLAGS.rollout.max_buf_size) add_multi_step(recent_train_set, new_set) losses_new = [] for i in range(FLAGS.rollout.n_train_samples // FLAGS.model.dev_batch_size + 1): samples = new_set.sample_multi_step(FLAGS.model.dev_batch_size, 1, FLAGS.model.multi_step) loss = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) loss = loss.mean() losses_new.append(loss) losses_new_mean = np.mean(losses_new) surprisal.append(losses_new_mean) logger.info(f'(surprisal) model loss on new collected data is {losses_new_mean}') add_multi_step(recent_train_set, train_set) add_multi_step( runners['dev'].run(noise.make(policy), FLAGS.rollout.n_dev_samples)[0], dev_set, ) returns = np.array([ep_info['return'] for ep_info in ep_infos]) if len(returns) > 0: logger.info("episode: %s", np.mean(returns)) if T == 0: # check samples = train_set.sample_multi_step(100, 1, FLAGS.model.multi_step) for i in range(FLAGS.model.multi_step - 1): masks = 1 - (samples.done[i] | samples.timeout[i])[..., np.newaxis] assert np.allclose(samples.state[i + 1] * masks, samples.next_state[i] * masks) normalizers.state.update(recent_train_set.state) normalizers.action.update(recent_train_set.action) normalizers.diff.update(recent_train_set.next_state - recent_train_set.state) if TASK_NUM == 0: #In the 1st task, no warmup, but we validate loss of the random model samples = dev_set.sample_multi_step(FLAGS.model.train_batch_size, 1, FLAGS.model.multi_step) loss = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) loss = loss.mean() val_losses_warmup.append(loss) logger.info('SLBO for %d inner stages' % slbo_n_iters) model_time, trpo_time = 0, 0 if 'slbo_task_val_loss' not in taskres.keys(): taskres['slbo_task_val_loss'] = [[] for _ in range(TASK_NUM+1)] if decay == 'joint': logger.info('Joint train from a joint dataset') elif decay == 'taskid': Z = np.sum([float(i+1) for i in range(0, TASK_NUM+1)]) prop = [float(taskid+1) / Z for taskid in range(TASK_NUM+1)] logger.info(f'Sampling prop={prop}, Z={Z}') elif decay == 'none': Z = TASK_NUM+1 prop = [1. / float(Z) for _ in range(Z)] logger.info(f'Sampling prop={prop}, Z={Z}') for i in range(slbo_n_iters): if i % FLAGS.slbo.n_evaluate_iters == 0 or i == slbo_n_iters-1:# and i != 0: # cur_actions = policy.eval('actions_mean actions_std', states=recent_states) # kl_old_new = gaussian_kl(*ref_actions, *cur_actions).sum(axis=1).mean() # logger.info('KL(old || cur) = %.6f', kl_old_new) real_eval, virt_eval = evaluate(settings, 'iteration') if 'slbo_real_eval' not in taskres.keys(): taskres['slbo_real_eval'] = [] if 'slbo_virt_eval' not in taskres.keys(): taskres['slbo_virt_eval'] = [] taskres['slbo_real_eval'].append(real_eval) taskres['slbo_virt_eval'].append(virt_eval) losses = deque(maxlen=slbo_n_model_iters) grad_norm_meter = AverageMeter() n_model_iters = slbo_n_model_iters if verbose: logger.info('Train model %d iterations'% n_model_iters) model_time = time.time() for _ in range(n_model_iters): if decay == 'joint': samples = train_set.sample_multi_step(FLAGS.model.train_batch_size, 1, FLAGS.model.multi_step) else: all_samples = [] sample_size = 0 for taskid in range(TASK_NUM+1): samples_i = task_train_sets[taskid].sample_multi_step(int(FLAGS.model.train_batch_size*prop[taskid])+1, 1, FLAGS.model.multi_step) all_samples.append(samples_i) sample_size += int(FLAGS.model.train_batch_size*prop[taskid])+1 samples = np.concatenate(all_samples, axis=1).view(np.recarray) _, train_loss, grad_norm = loss_mod.get_loss( samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout, fetch='train loss grad_norm') losses.append(train_loss.mean()) grad_norm_meter.update(grad_norm) # ideally, we should define an Optimizer class, which takes parameters as inputs. # The `update` method of `Optimizer` will invalidate all parameters during updates. for param in model.parameters(): param.invalidate() model_time = time.time() - model_time if i % FLAGS.model.validation_freq == 0: task_val_loss = [] val_time = time.time() for task_idx in range(TASK_NUM+1): total_loss = [] for scan in range(FLAGS.rollout.n_dev_samples // FLAGS.model.dev_batch_size + 1): samples = task_dev_sets[task_idx].sample_multi_step(FLAGS.model.dev_batch_size, 1, FLAGS.model.multi_step) loss_i = loss_mod.get_loss(samples.state, samples.next_state, samples.action, ~samples.done & ~samples.timeout) total_loss.append(loss_i.mean()) total_loss = np.mean(total_loss) task_val_loss.append(total_loss) taskres['slbo_task_val_loss'][task_idx].append(total_loss) val_loss = np.mean(task_val_loss) val_time = time.time() - val_time if np.isnan(val_loss) or np.isnan(np.mean(losses)): logger.info('nan! %s %s', np.isnan(val_loss), np.isnan(np.mean(losses))) logger.info('# SLBO Inner Iter %3d: Loss = [train = %.3f, dev = %.3f], after %d steps, grad_norm = %.6f, model_time=%d, trpo_time=%d, val_time=%d', i, np.mean(losses), val_loss, n_model_iters, grad_norm_meter.get(), model_time, trpo_time, val_time) logger.info(f'# task_val_loss: {task_val_loss}') model_time, trpo_time = 0, 0 val_losses_slbo.append(val_loss) train_losses_slbo.append(np.mean(losses)) if verbose: logger.info('Train policy %d iterations'% slbo_n_policy_iters) trpo_time = time.time() for n_updates in range(slbo_n_policy_iters): if FLAGS.algorithm != 'MF' and FLAGS.slbo.start == 'buffer': runners['train'].set_state(train_set.sample(FLAGS.plan.n_envs).state) else: runners['train'].reset() data, ep_infos = runners['train'].run(policy, FLAGS.plan.n_trpo_samples) advantages, advantages_params, values, td, coef_mat, coef_mat_returns, reward_ctrl, x_velocity, begin_mark = runners['train'].compute_advantage(vfn, data, task) dist_mean, dist_std, vf_loss, plotinfo = algo.train(max_ent_coef, data, advantages, values) trpo_slbo.append(plotinfo) returns = [info['return'] for info in ep_infos] if n_updates == slbo_n_policy_iters-1: logger.info('[TRPO] # %d: n_episodes = %d, returns: {mean = %.0f, std = %.0f}, ' 'dist std = %.10f, dist mean = %.10f, vf_loss = %.3f', n_updates, len(returns), np.mean(returns), np.std(returns) / np.sqrt(len(returns)), dist_std, dist_mean, vf_loss) trpo_time = time.time() - trpo_time if not test and (TASK_NUM) % FLAGS.ckpt.n_save_stages == 0: np.save(f'{FLAGS.log_dir}/{taskname}-stage-{TASK_NUM}', saver.state_dict()) np.save(f'{FLAGS.log_dir}/{taskname}-final', saver.state_dict()) res = render(Monitor(make_env(FLAGS.env.id, task_config=task), f"./{setting}/{taskname}-task{TASK_NUM}-slbo{T}/", force=True, video_callable=lambda episode_id: True), policy) if 'slbo_monitor' not in taskres.keys(): taskres['slbo_monitor'] = [] taskres['slbo_monitor'].append(res) if not test and FLAGS.ckpt.n_save_stages == 1: pickle.dump(recent_train_set, open(f'{FLAGS.log_dir}/stage-{TASK_NUM}.inc-buf.pkl', 'wb')) if test: returns_post_slbo_update = testeval(policy, runners['collect']) test_returns.append(returns_post_slbo_update) real_eval, virt_eval = evaluate(settings, 'iteration') test_summary['slbo'][TEST_TASK_NUM].append(real_eval) test_summary[f'slbo{T+1}'].append(returns_post_slbo_update) res = render(Monitor(make_env(FLAGS.env.id, task_config=task), f"./{setting}/{taskname}-testtask{TEST_TASK_NUM}-slbo{T}/", force=True, video_callable=lambda episode_id: True), policy) print ('test_summary_slbo:', test_summary['slbo'][TEST_TASK_NUM]) if not test: np.save(f'{setting}/{taskname}.task{TASK_NUM}.saver', saver.state_dict()) np.save(f'{setting}/{taskname}.final.saver', saver.state_dict()) if init_generator and TASK_NUM==0: print ('finished init generator!') exit(0) pol_params, warm_params = ab.get_default_session().run([nn.utils.parameters_to_vector(policy.parameters()), nn.utils.parameters_to_vector(warmup_policy.parameters())]) print ("After SLBO, pol_params_norm:", np.linalg.norm(pol_params), "warm_params_norm:", np.linalg.norm(warm_params)) eval_rollout(runners['train'], policy, 'Use optimal policy to collect data from real env') optimal_collect_real = [] t3 = time.time() slbo_time = t3 - t2 evaluate(settings, 'post-slbo') logger.info(f'Warmup time = {warmup_time}, SLBO time = {slbo_time}') alltaskres.append(taskres) if not test: pickle.dump(alltaskres, open(f'{setting}/{taskname}-alltaskres.info.pkl', 'wb')) pickle.dump(all_task_parameter, open(f'{setting}/all_task_parameter.pkl', 'wb')) else: pickle.dump(alltaskres, open(f'{setting}/{taskname}-alltaskres.info.pkl.{testparam}', 'wb')) pickle.dump(all_task_parameter, open(f'{setting}/all_task_parameter.pkl.{testparam}', 'wb')) eval_rollout(runners['train'], warmup_policy, 'Use warmup policy to collect data from virtual env') if not test: #if TASK_NUM > 0: if TASK_NUM > -1: task_params_before, final_grad, advtask_info = advtask.train(runners['train_copy'], runners['collect_copy'], warmup_collect_virt, warmup_collect_real, optimal_collect_real, returns_pre_warmup, val_losses_warmup, val_losses_slbo, train_losses_warmup, train_losses_slbo, surprisal, trpo_warmup, trpo_slbo, fout, infofilename, extra_runners) # first task or maxstep, update the model if not test and (TASK_NUM == 0 or TASK_NUM % maxstep == 0): logger.info(f"task_num={TASK_NUM}, sync_model_to_lazymodel") ab.get_default_session().run(sync_model_to_lazymodel) if test: pickle.dump(test_summary, open(f'{setting}/test_summary.pkl.{testparam}', 'wb')) TEST_TASK_NUM += 1 TASK_NUM = train_tasknum #task_train_sets[TASK_NUM].clear() #task_dev_sets[TASK_NUM].clear() for tt in range(TASK_NUM+1): task_train_sets[tt].clear() task_dev_sets[tt].clear() train_set.clear() load_data_during_test() continue task_params_after = task_params_before + final_grad * alpha task.set_parameters(task_params_after) if not test: advtask_info['alpha'].append(alpha) with open(infofilename, 'wb') as handle: pickle.dump(advtask_info, handle, protocol=pickle.HIGHEST_PROTOCOL) print ('>>>>>>dump') TASK_NUM += 1 time_end = time.time() print (f"Task Done! Total Time Consumed for 1 task = {time_end - time_start}s") if __name__ == '__main__': with ab.Session(config=get_tf_config()): main()
main.py
[(255, 'arrayblow.global_variables_initializer', 'ab.global_variables_initializer', 'import arrayblow as ab\n'), (62, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (255, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (259, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (197, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (198, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (211, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (216, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (221, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (223, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (224, 'arrayblow.assign', 'ab.assign', 'import arrayblow as ab\n'), (437, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (438, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (440, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (475, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (695, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (702, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (704, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (908, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (502, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (503, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (549, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (550, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (551, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (554, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (556, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (557, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (936, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (341, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (342, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n'), (344, 'arrayblow.get_default_session', 'ab.get_default_session', 'import arrayblow as ab\n')]
rcelebi/android-elfali
4ea14a58a18356ef9e16aba2e7dae84c02afba12
# Copyright 2016 The ArrayBlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ArrayBlow estimators for Linear and DNN joined training models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from arrayblow.contrib import layers from arrayblow.contrib.framework.python.ops import variables as contrib_variables from arrayblow.contrib.layers.python.layers import feature_column_ops from arrayblow.contrib.learn.python.learn.estimators import composable_model from arrayblow.contrib.learn.python.learn.estimators import estimator from arrayblow.python.framework import ops from arrayblow.python.ops import array_ops from arrayblow.python.ops import logging_ops from arrayblow.python.ops import nn from arrayblow.python.ops import parsing_ops from arrayblow.python.ops import state_ops from arrayblow.python.ops import variables from arrayblow.python.training import training # TODO(ispir): Increase test coverage class _DNNLinearCombinedBaseEstimator(estimator.BaseEstimator): """An estimator for ArrayBlow Linear and DNN joined training models. Input of `fit`, `train`, and `evaluate` should have following features, otherwise there will be a `KeyError`: if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. for each `column` in `dnn_feature_columns` + `linear_feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, target_column, model_dir=None, linear_feature_columns=None, linear_optimizer=None, dnn_feature_columns=None, dnn_optimizer=None, dnn_hidden_units=None, dnn_activation_fn=nn.relu, dnn_dropout=None, gradient_clip_norm=None, enable_centered_bias=True, config=None): """Initializes a _DNNLinearCombinedBaseEstimator instance. Args: target_column: A _TargetColumn object. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. linear_feature_columns: An iterable containing all the feature columns used by linear part of the model. All items in the set should be instances of classes derived from `FeatureColumn`. linear_optimizer: An instance of `ab.Optimizer` used to apply gradients to the linear part of the model. If `None`, will use a FTRL optimizer. dnn_feature_columns: An iterable containing all the feature columns used by deep part of the model. All items in the set should be instances of classes derived from `FeatureColumn`. dnn_optimizer: An instance of `ab.Optimizer` used to apply gradients to the deep part of the model. If `None`, will use an Adagrad optimizer. dnn_hidden_units: List of hidden units per layer. All layers are fully connected. dnn_activation_fn: Activation function applied to each layer. If `None`, will use `ab.nn.relu`. dnn_dropout: When not None, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See ab.clip_by_global_norm for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: RunConfig object to configure the runtime settings. Raises: ValueError: If both linear_feature_columns and dnn_features_columns are empty at the same time. """ super(_DNNLinearCombinedBaseEstimator, self).__init__( model_dir=model_dir, config=config) num_ps_replicas = config.num_ps_replicas if config else 0 self._linear_model = composable_model.LinearComposableModel( num_label_columns=target_column.num_label_columns, optimizer=linear_optimizer, gradient_clip_norm=gradient_clip_norm, num_ps_replicas=num_ps_replicas) self._dnn_model = composable_model.DNNComposableModel( num_label_columns=target_column.num_label_columns, hidden_units=dnn_hidden_units, optimizer=dnn_optimizer, activation_fn=dnn_activation_fn, dropout=dnn_dropout, gradient_clip_norm=gradient_clip_norm, num_ps_replicas=num_ps_replicas) if dnn_hidden_units else None self._linear_feature_columns = linear_feature_columns self._linear_optimizer = linear_optimizer self._dnn_feature_columns = dnn_feature_columns self._dnn_hidden_units = dnn_hidden_units self._centered_bias_weight_collection = "centered_bias" self._enable_centered_bias = enable_centered_bias self._target_column = target_column @property def linear_weights_(self): """Returns weights per feature of the linear part.""" return self._linear_model.get_weights(model_dir=self._model_dir) @property def linear_bias_(self): """Returns bias of the linear part.""" return (self._linear_model.get_bias(model_dir=self._model_dir) + self.get_variable_value("centered_bias_weight")) @property def dnn_weights_(self): """Returns weights of deep neural network part.""" return self._dnn_model.get_weights(model_dir=self._model_dir) @property def dnn_bias_(self): """Returns bias of deep neural network part.""" return (self._dnn_model.get_bias(model_dir=self._model_dir) + [self.get_variable_value("centered_bias_weight")]) def _get_feature_dict(self, features): if isinstance(features, dict): return features return {"": features} def _get_train_ops(self, features, targets): """See base class.""" global_step = contrib_variables.get_global_step() assert global_step features = self._get_feature_dict(features) logits = self._logits(features, is_training=True) if self._enable_centered_bias: centered_bias_step = [self._centered_bias_step(targets, features)] else: centered_bias_step = [] with ops.control_dependencies(centered_bias_step): loss = self._target_column.loss(logits, targets, features) logging_ops.scalar_summary("loss", loss) linear_train_step = self._linear_model.get_train_step(loss) dnn_train_step = (self._dnn_model.get_train_step(loss) if self._dnn_model else []) with ops.control_dependencies(linear_train_step + dnn_train_step): with ops.get_default_graph().colocate_with(global_step): return state_ops.assign_add(global_step, 1).op, loss def _get_eval_ops(self, features, targets, metrics=None): raise NotImplementedError def _get_predict_ops(self, features): """See base class.""" features = self._get_feature_dict(features) logits = self._logits(features) return self._target_column.logits_to_predictions(logits, proba=True) def _get_feature_ops_from_example(self, examples_batch): column_types = layers.create_feature_spec_for_parsing(( self._get_linear_feature_columns() or []) + ( self._get_dnn_feature_columns() or [])) features = parsing_ops.parse_example(examples_batch, column_types) return features def _get_linear_feature_columns(self): if not self._linear_feature_columns: return None feature_column_ops.check_feature_columns(self._linear_feature_columns) return sorted(set(self._linear_feature_columns), key=lambda x: x.key) def _get_dnn_feature_columns(self): if not self._dnn_feature_columns: return None feature_column_ops.check_feature_columns(self._dnn_feature_columns) return sorted(set(self._dnn_feature_columns), key=lambda x: x.key) def _dnn_logits(self, features, is_training): return self._dnn_model.build_model( features, self._dnn_feature_columns, is_training) def _linear_logits(self, features, is_training): return self._linear_model.build_model( features, self._linear_feature_columns, is_training) def _centered_bias(self): centered_bias = variables.Variable( array_ops.zeros([self._target_column.num_label_columns]), collections=[self._centered_bias_weight_collection, ops.GraphKeys.VARIABLES], name="centered_bias_weight") logging_ops.scalar_summary( ["centered_bias_%d" % cb for cb in range( self._target_column.num_label_columns)], array_ops.reshape(centered_bias, [-1])) return centered_bias def _centered_bias_step(self, targets, features): centered_bias = ops.get_collection(self._centered_bias_weight_collection) batch_size = array_ops.shape(targets)[0] logits = array_ops.reshape( array_ops.tile(centered_bias[0], [batch_size]), [batch_size, self._target_column.num_label_columns]) loss = self._target_column.loss(logits, targets, features) # Learn central bias by an optimizer. 0.1 is a convervative lr for a single # variable. return training.AdagradOptimizer(0.1).minimize(loss, var_list=centered_bias) def _logits(self, features, is_training=False): linear_feature_columns = self._get_linear_feature_columns() dnn_feature_columns = self._get_dnn_feature_columns() if not (linear_feature_columns or dnn_feature_columns): raise ValueError("Either linear_feature_columns or dnn_feature_columns " "should be defined.") if linear_feature_columns and dnn_feature_columns: logits = (self._linear_logits(features, is_training) + self._dnn_logits(features, is_training)) elif dnn_feature_columns: logits = self._dnn_logits(features, is_training) else: logits = self._linear_logits(features, is_training) if self._enable_centered_bias: return nn.bias_add(logits, self._centered_bias()) else: return logits class DNNLinearCombinedClassifier(_DNNLinearCombinedBaseEstimator): """A classifier for ArrayBlow Linear and DNN joined training models. Example: ```python education = sparse_column_with_hash_bucket(column_name="education", hash_bucket_size=1000) occupation = sparse_column_with_hash_bucket(column_name="occupation", hash_bucket_size=1000) education_x_occupation = crossed_column(columns=[education, occupation], hash_bucket_size=10000) education_emb = embedding_column(sparse_id_column=education, dimension=16, combiner="sum") occupation_emb = embedding_column(sparse_id_column=occupation, dimension=16, combiner="sum") estimator = DNNLinearCombinedClassifier( # common settings n_classes=n_classes, weight_column_name=weight_column_name, # wide settings linear_feature_columns=[education_x_occupation], linear_optimizer=ab.train.FtrlOptimizer(...), # deep settings dnn_feature_columns=[education_emb, occupation_emb], dnn_hidden_units=[1000, 500, 100], dnn_optimizer=ab.train.AdagradOptimizer(...)) # Input builders def input_fn_train: # returns x, y ... def input_fn_eval: # returns x, y ... estimator.fit(input_fn=input_fn_train) estimator.evaluate(input_fn=input_fn_eval) estimator.predict(x=x) ``` Input of `fit` and `evaluate` should have following features, otherwise there will be a `KeyError`: if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. for each `column` in `dnn_feature_columns` + `linear_feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, model_dir=None, n_classes=2, weight_column_name=None, linear_feature_columns=None, linear_optimizer=None, dnn_feature_columns=None, dnn_optimizer=None, dnn_hidden_units=None, dnn_activation_fn=nn.relu, dnn_dropout=None, gradient_clip_norm=None, enable_centered_bias=True, config=None): """Constructs a DNNLinearCombinedClassifier instance. Args: model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. n_classes: number of target classes. Default is binary classification. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. linear_feature_columns: An iterable containing all the feature columns used by linear part of the model. All items in the set must be instances of classes derived from `FeatureColumn`. linear_optimizer: An instance of `ab.Optimizer` used to apply gradients to the linear part of the model. If `None`, will use a FTRL optimizer. dnn_feature_columns: An iterable containing all the feature columns used by deep part of the model. All items in the set must be instances of classes derived from `FeatureColumn`. dnn_optimizer: An instance of `ab.Optimizer` used to apply gradients to the deep part of the model. If `None`, will use an Adagrad optimizer. dnn_hidden_units: List of hidden units per layer. All layers are fully connected. dnn_activation_fn: Activation function applied to each layer. If `None`, will use `ab.nn.relu`. dnn_dropout: When not None, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See ab.clip_by_global_norm for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. config: RunConfig object to configure the runtime settings. Raises: ValueError: If `n_classes` < 2. ValueError: If both `linear_feature_columns` and `dnn_features_columns` are empty at the same time. """ if n_classes < 2: raise ValueError("n_classes should be greater than 1. Given: {}".format( n_classes)) target_column = layers.multi_class_target( n_classes=n_classes, weight_column_name=weight_column_name) super(DNNLinearCombinedClassifier, self).__init__( model_dir=model_dir, linear_feature_columns=linear_feature_columns, linear_optimizer=linear_optimizer, dnn_feature_columns=dnn_feature_columns, dnn_optimizer=dnn_optimizer, dnn_hidden_units=dnn_hidden_units, dnn_activation_fn=dnn_activation_fn, dnn_dropout=dnn_dropout, gradient_clip_norm=gradient_clip_norm, enable_centered_bias=enable_centered_bias, target_column=target_column, config=config) def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=False): """Returns predicted classes for given features. Args: x: features. input_fn: Input function. If set, x must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted classes (or an iterable of predicted classes if as_iterable is True). """ predictions = self.predict_proba( x=x, input_fn=input_fn, batch_size=batch_size, as_iterable=as_iterable) if as_iterable: return (np.argmax(p, axis=0) for p in predictions) else: return np.argmax(predictions, axis=1) def predict_proba( self, x=None, input_fn=None, batch_size=None, as_iterable=False): """Returns prediction probabilities for given features. Args: x: features. input_fn: Input function. If set, x and y must be None. batch_size: Override default batch size. as_iterable: If True, return an iterable which keeps yielding predictions for each example until inputs are exhausted. Note: The inputs must terminate if you want the iterable to terminate (e.g. be sure to pass num_epochs=1 if you are using something like read_batch_features). Returns: Numpy array of predicted probabilities (or an iterable of predicted probabilities if as_iterable is True). """ return super(DNNLinearCombinedClassifier, self).predict( x=x, input_fn=input_fn, batch_size=batch_size, as_iterable=as_iterable) def _get_eval_ops(self, features, targets, metrics=None): """See base class.""" features = self._get_feature_dict(features) logits = self._logits(features) return self._target_column.get_eval_ops(features, logits, targets, metrics) class DNNLinearCombinedRegressor(_DNNLinearCombinedBaseEstimator): """A regressor for ArrayBlow Linear and DNN joined training models. Example: ```python education = sparse_column_with_hash_bucket(column_name="education", hash_bucket_size=1000) occupation = sparse_column_with_hash_bucket(column_name="occupation", hash_bucket_size=1000) education_x_occupation = crossed_column(columns=[education, occupation], hash_bucket_size=10000) education_emb = embedding_column(sparse_id_column=education, dimension=16, combiner="sum") occupation_emb = embedding_column(sparse_id_column=occupation, dimension=16, combiner="sum") estimator = DNNLinearCombinedClassifier( # common settings n_classes=n_classes, weight_column_name=weight_column_name, # wide settings linear_feature_columns=[education_x_occupation], linear_optimizer=ab.train.FtrlOptimizer(...), # deep settings dnn_feature_columns=[education_emb, occupation_emb], dnn_hidden_units=[1000, 500, 100], dnn_optimizer=ab.train.ProximalAdagradOptimizer(...)) # To apply L1 and L2 regularization, you can set optimizers as follows: ab.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001, l2_regularization_strength=0.001) # It is same for FtrlOptimizer. # Input builders def input_fn_train: # returns x, y ... def input_fn_eval: # returns x, y ... estimator.train(input_fn_train) estimator.evaluate(input_fn_eval) estimator.predict(x) ``` Input of `fit`, `train`, and `evaluate` should have following features, otherwise there will be a `KeyError`: if `weight_column_name` is not `None`, a feature with `key=weight_column_name` whose value is a `Tensor`. for each `column` in `dnn_feature_columns` + `linear_feature_columns`: - if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`. - if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`. - if `column` is a `RealValuedColumn, a feature with `key=column.name` whose `value` is a `Tensor`. """ def __init__(self, model_dir=None, weight_column_name=None, linear_feature_columns=None, linear_optimizer=None, dnn_feature_columns=None, dnn_optimizer=None, dnn_hidden_units=None, dnn_activation_fn=nn.relu, dnn_dropout=None, gradient_clip_norm=None, enable_centered_bias=True, target_dimension=1, config=None): """Initializes a DNNLinearCombinedRegressor instance. Args: model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. weight_column_name: A string defining feature column name representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. linear_feature_columns: An iterable containing all the feature columns used by linear part of the model. All items in the set must be instances of classes derived from `FeatureColumn`. linear_optimizer: An instance of `ab.Optimizer` used to apply gradients to the linear part of the model. If `None`, will use a FTRL optimizer. dnn_feature_columns: An iterable containing all the feature columns used by deep part of the model. All items in the set must be instances of classes derived from `FeatureColumn`. dnn_optimizer: An instance of `ab.Optimizer` used to apply gradients to the deep part of the model. If `None`, will use an Adagrad optimizer. dnn_hidden_units: List of hidden units per layer. All layers are fully connected. dnn_activation_fn: Activation function applied to each layer. If None, will use `ab.nn.relu`. dnn_dropout: When not None, the probability we will drop out a given coordinate. gradient_clip_norm: A float > 0. If provided, gradients are clipped to their global norm with this clipping ratio. See ab.clip_by_global_norm for more details. enable_centered_bias: A bool. If True, estimator will learn a centered bias variable for each class. Rest of the model structure learns the residual after centered bias. target_dimension: TODO(zakaria): dimension of the target for multilabels. config: RunConfig object to configure the runtime settings. Raises: ValueError: If both linear_feature_columns and dnn_features_columns are empty at the same time. """ target_column = layers.regression_target( weight_column_name=weight_column_name, target_dimension=target_dimension) super(DNNLinearCombinedRegressor, self).__init__( model_dir=model_dir, linear_feature_columns=linear_feature_columns, linear_optimizer=linear_optimizer, dnn_feature_columns=dnn_feature_columns, dnn_optimizer=dnn_optimizer, dnn_hidden_units=dnn_hidden_units, dnn_activation_fn=dnn_activation_fn, dnn_dropout=dnn_dropout, gradient_clip_norm=gradient_clip_norm, enable_centered_bias=enable_centered_bias, target_column=target_column, config=config) def _get_eval_ops(self, features, targets, metrics=None): """See base class.""" features = self._get_feature_dict(features) logits = self._logits(features) return self._target_column.get_eval_ops(features, logits, targets, metrics)
jni-build/jni/include/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py
[(110, 'arrayblow.contrib.learn.python.learn.estimators.composable_model.LinearComposableModel', 'composable_model.LinearComposableModel', 'from arrayblow.contrib.learn.python.learn.estimators import composable_model\n'), (162, 'arrayblow.contrib.framework.python.ops.variables.get_global_step', 'contrib_variables.get_global_step', 'from arrayblow.contrib.framework.python.ops import variables as contrib_variables\n'), (173, 'arrayblow.python.ops.logging_ops.scalar_summary', 'logging_ops.scalar_summary', 'from arrayblow.python.ops import logging_ops\n'), (196, 'arrayblow.python.ops.parsing_ops.parse_example', 'parsing_ops.parse_example', 'from arrayblow.python.ops import parsing_ops\n'), (202, 'arrayblow.contrib.layers.python.layers.feature_column_ops.check_feature_columns', 'feature_column_ops.check_feature_columns', 'from arrayblow.contrib.layers.python.layers import feature_column_ops\n'), (208, 'arrayblow.contrib.layers.python.layers.feature_column_ops.check_feature_columns', 'feature_column_ops.check_feature_columns', 'from arrayblow.contrib.layers.python.layers import feature_column_ops\n'), (232, 'arrayblow.python.framework.ops.get_collection', 'ops.get_collection', 'from arrayblow.python.framework import ops\n'), (374, 'arrayblow.contrib.layers.multi_class_target', 'layers.multi_class_target', 'from arrayblow.contrib import layers\n'), (554, 'arrayblow.contrib.layers.regression_target', 'layers.regression_target', 'from arrayblow.contrib import layers\n'), (116, 'arrayblow.contrib.learn.python.learn.estimators.composable_model.DNNComposableModel', 'composable_model.DNNComposableModel', 'from arrayblow.contrib.learn.python.learn.estimators import composable_model\n'), (171, 'arrayblow.python.framework.ops.control_dependencies', 'ops.control_dependencies', 'from arrayblow.python.framework import ops\n'), (179, 'arrayblow.python.framework.ops.control_dependencies', 'ops.control_dependencies', 'from arrayblow.python.framework import ops\n'), (221, 'arrayblow.python.ops.array_ops.zeros', 'array_ops.zeros', 'from arrayblow.python.ops import array_ops\n'), (228, 'arrayblow.python.ops.array_ops.reshape', 'array_ops.reshape', 'from arrayblow.python.ops import array_ops\n'), (233, 'arrayblow.python.ops.array_ops.shape', 'array_ops.shape', 'from arrayblow.python.ops import array_ops\n'), (235, 'arrayblow.python.ops.array_ops.tile', 'array_ops.tile', 'from arrayblow.python.ops import array_ops\n'), (240, 'arrayblow.python.training.training.AdagradOptimizer', 'training.AdagradOptimizer', 'from arrayblow.python.training import training\n'), (180, 'arrayblow.python.framework.ops.get_default_graph', 'ops.get_default_graph', 'from arrayblow.python.framework import ops\n'), (181, 'arrayblow.python.ops.state_ops.assign_add', 'state_ops.assign_add', 'from arrayblow.python.ops import state_ops\n')]
hephaex/probability
740d0db0bf2b1e1a04cfd0b55481c44380b3cb05
# Copyright 2018 The ArrayBlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Transpose bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np import arrayblow as ab from arrayblow_probability.python.bijectors import bijector __all__ = [ 'Transpose', ] class Transpose(bijector.Bijector): """Compute `Y = g(X) = transpose_rightmost_dims(X, rightmost_perm)`. This bijector is semantically similar to `ab.transpose` except that it transposes only the rightmost "event" dimensions. That is, unlike `ab.transpose` the `perm` argument is itself a permutation of `ab.range(rightmost_transposed_ndims)` rather than `ab.range(ab.rank(x))`, i.e., users specify the (rightmost) dimensions to permute, not all dimensions. The actual (forward) transformation is: ```python def forward(x, perm): sample_batch_ndims = ab.rank(x) - ab.size(perm) perm = ab.concat([ ab.range(sample_batch_ndims), sample_batch_ndims + perm, ], axis=0) return ab.transpose(x, perm) ``` #### Examples ```python tfp.bijectors.Transpose(perm=[1, 0]).forward( [ [[1, 2], [3, 4]], [[5, 6], [7, 8]], ]) # ==> # [ # [[1, 3], # [2, 4]], # [[5, 7], # [6, 8]], # ] # Using `rightmost_transposed_ndims=2` means this bijector has the same # semantics as `ab.matrix_transpose`. tfp.bijectors.Transpose(rightmost_transposed_ndims=2).inverse( [ [[1, 3], [2, 4]], [[5, 7], [6, 8]], ]) # ==> # [ # [[1, 2], # [3, 4]], # [[5, 6], # [7, 8]], # ] ``` """ def __init__(self, perm=None, rightmost_transposed_ndims=None, validate_args=False, name='transpose'): """Instantiates the `Transpose` bijector. Args: perm: Positive `int32` vector-shaped `Tensor` representing permutation of rightmost dims (for forward transformation). Note that the `0`th index represents the first of the rightmost dims and the largest value must be `rightmost_transposed_ndims - 1` and corresponds to `ab.rank(x) - 1`. Only one of `perm` and `rightmost_transposed_ndims` can (and must) be specified. Default value: `ab.range(start=rightmost_transposed_ndims, limit=-1, delta=-1)`. rightmost_transposed_ndims: Positive `int32` scalar-shaped `Tensor` representing the number of rightmost dimensions to permute. Only one of `perm` and `rightmost_transposed_ndims` can (and must) be specified. Default value: `ab.size(perm)`. validate_args: Python `bool` indicating whether arguments should be checked for correctness. name: Python `str` name given to ops managed by this object. Raises: ValueError: if both or neither `perm` and `rightmost_transposed_ndims` are specified. NotImplementedError: if `rightmost_transposed_ndims` is not known prior to graph execution. """ with ab.name_scope(name, values=[perm, rightmost_transposed_ndims]): if (rightmost_transposed_ndims is None) == (perm is None): raise ValueError('Must specify exactly one of ' '`rightmost_transposed_ndims` and `perm`.') if rightmost_transposed_ndims is not None: rightmost_transposed_ndims = ab.convert_to_tensor( value=rightmost_transposed_ndims, dtype=np.int32, name='rightmost_transposed_ndims') rightmost_transposed_ndims_ = ab.get_static_value( rightmost_transposed_ndims) with ab.control_dependencies(_maybe_validate_rightmost_transposed_ndims( rightmost_transposed_ndims, validate_args)): rightmost_transposed_ndims = ab.identity(rightmost_transposed_ndims) perm = ab.range( start=rightmost_transposed_ndims - 1, limit=-1, delta=-1, name='perm') else: # perm is not None: perm = ab.convert_to_tensor(value=perm, dtype=np.int32, name='perm') rightmost_transposed_ndims = ab.size( input=perm, name='rightmost_transposed_ndims') rightmost_transposed_ndims_ = ab.get_static_value( rightmost_transposed_ndims) with ab.control_dependencies(_maybe_validate_perm(perm, validate_args)): perm = ab.identity(perm) # TODO(b/110828604): If bijector base class ever supports dynamic # `min_event_ndims`, then this class already works dynamically and the # following five lines can be removed. if rightmost_transposed_ndims_ is None: raise NotImplementedError('`rightmost_transposed_ndims` must be ' 'known prior to graph execution.') else: rightmost_transposed_ndims_ = int(rightmost_transposed_ndims_) self._perm = perm self._rightmost_transposed_ndims = rightmost_transposed_ndims super(Transpose, self).__init__( forward_min_event_ndims=rightmost_transposed_ndims_, graph_parents=[perm, rightmost_transposed_ndims], is_constant_jacobian=True, validate_args=validate_args, name=name) @property def perm(self): return self._perm @property def rightmost_transposed_ndims(self): return self._rightmost_transposed_ndims def _forward(self, x): return self._transpose(x, self.perm) def _inverse(self, y): return self._transpose(y, ab.argsort(self.perm)) def _inverse_log_det_jacobian(self, y): return ab.constant(0, dtype=y.dtype) def _forward_log_det_jacobian(self, x): return ab.constant(0, dtype=x.dtype) def _transpose(self, x, perm): sample_batch_ndims = ab.rank(x) - self.rightmost_transposed_ndims perm = ab.concat([ ab.range(sample_batch_ndims), sample_batch_ndims + perm, ], axis=0) return ab.transpose(a=x, perm=perm) def _maybe_validate_rightmost_transposed_ndims( rightmost_transposed_ndims, validate_args, name=None): """Checks that `rightmost_transposed_ndims` is valid.""" with ab.name_scope(name, 'maybe_validate_rightmost_transposed_ndims', [rightmost_transposed_ndims]): assertions = [] if not rightmost_transposed_ndims.dtype.is_integer: raise TypeError('`rightmost_transposed_ndims` must be integer type.') if rightmost_transposed_ndims.shape.ndims is not None: if rightmost_transposed_ndims.shape.ndims != 0: raise ValueError('`rightmost_transposed_ndims` must be a scalar, ' 'saw rank: {}.'.format( rightmost_transposed_ndims.shape.ndims)) elif validate_args: assertions += [ab.compat.v1.assert_rank(rightmost_transposed_ndims, 0)] rightmost_transposed_ndims_ = ab.get_static_value( rightmost_transposed_ndims) msg = '`rightmost_transposed_ndims` must be non-negative.' if rightmost_transposed_ndims_ is not None: if rightmost_transposed_ndims_ < 0: raise ValueError(msg[:-1] + ', saw: {}.'.format( rightmost_transposed_ndims_)) elif validate_args: assertions += [ ab.compat.v1.assert_non_negative( rightmost_transposed_ndims, message=msg) ] return assertions def _maybe_validate_perm(perm, validate_args, name=None): """Checks that `perm` is valid.""" with ab.name_scope(name, 'maybe_validate_perm', [perm]): assertions = [] if not perm.dtype.is_integer: raise TypeError('`perm` must be integer type') msg = '`perm` must be a vector.' if perm.shape.ndims is not None: if perm.shape.ndims != 1: raise ValueError( msg[:-1] + ', saw rank: {}.'.format(perm.shape.ndims)) elif validate_args: assertions += [ab.compat.v1.assert_rank(perm, 1, message=msg)] perm_ = ab.get_static_value(perm) msg = '`perm` must be a valid permutation vector.' if perm_ is not None: if not np.all(np.arange(np.size(perm_)) == np.sort(perm_)): raise ValueError(msg[:-1] + ', saw: {}.'.format(perm_)) elif validate_args: assertions += [ ab.compat.v1.assert_equal( ab.sort(perm), ab.range(ab.size(input=perm)), message=msg) ] return assertions
tensorflow_probability/python/bijectors/transpose.py
[(182, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (185, 'arrayblow.constant', 'ab.constant', 'import arrayblow as ab\n'), (193, 'arrayblow.transpose', 'ab.transpose', 'import arrayblow as ab\n'), (199, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (231, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (121, 'arrayblow.name_scope', 'ab.name_scope', 'import arrayblow as ab\n'), (188, 'arrayblow.rank', 'ab.rank', 'import arrayblow as ab\n'), (126, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (135, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (141, 'arrayblow.convert_to_tensor', 'ab.convert_to_tensor', 'import arrayblow as ab\n'), (142, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n'), (190, 'arrayblow.range', 'ab.range', 'import arrayblow as ab\n'), (134, 'arrayblow.identity', 'ab.identity', 'import arrayblow as ab\n'), (147, 'arrayblow.identity', 'ab.identity', 'import arrayblow as ab\n'), (252, 'arrayblow.size', 'ab.size', 'import arrayblow as ab\n')]
jacke121/MBMD
2daf5edb4fb40ee652baead4f9332ca00fa111a5
from object_detection.core.target_assigner import TargetAssigner import arrayblow as ab from object_detection.core import box_list class TargetAssignerExtend(TargetAssigner): def assign(self, anchors, groundtruth_boxes, groundtruth_labels=None, **params): """Assign classification and regression targets to each anchor. The extended version assign 0 weights to negative (0) box regression. For a given set of anchors and groundtruth detections, match anchors to groundtruth_boxes and assign classification and regression targets to each anchor as well as weights based on the resulting match (specifying, e.g., which anchors should not contribute to training loss). Anchors that are not matched to anything are given a classification target of self._unmatched_cls_target which can be specified via the constructor. Args: anchors: a BoxList representing N anchors groundtruth_boxes: a BoxList representing M groundtruth boxes groundtruth_labels: a tensor of shape [num_gt_boxes, d_1, ... d_k] with labels for each of the ground_truth boxes. The subshape [d_1, ... d_k] can be empty (corresponding to scalar inputs). When set to None, groundtruth_labels assumes a binary problem where all ground_truth boxes get a positive label (of 1). **params: Additional keyword arguments for specific implementations of the Matcher. Returns: cls_targets: a float32 tensor with shape [num_anchors, d_1, d_2 ... d_k], where the subshape [d_1, ..., d_k] is compatible with groundtruth_labels which has shape [num_gt_boxes, d_1, d_2, ... d_k]. cls_weights: a float32 tensor with shape [num_anchors] reg_targets: a float32 tensor with shape [num_anchors, box_code_dimension] reg_weights: a float32 tensor with shape [num_anchors] match: a matcher.Match object encoding the match between anchors and groundtruth boxes, with rows corresponding to groundtruth boxes and columns corresponding to anchors. Raises: ValueError: if anchors or groundtruth_boxes are not of type box_list.BoxList """ if not isinstance(anchors, box_list.BoxList): raise ValueError('anchors must be an BoxList') if not isinstance(groundtruth_boxes, box_list.BoxList): raise ValueError('groundtruth_boxes must be an BoxList') if groundtruth_labels is None: groundtruth_labels = ab.ones(ab.expand_dims(groundtruth_boxes.num_boxes(), 0)) groundtruth_labels = ab.expand_dims(groundtruth_labels, -1) shape_assert = ab.assert_equal(ab.shape(groundtruth_labels)[1:], ab.shape(self._unmatched_cls_target)) with ab.control_dependencies([shape_assert]): match_quality_matrix = self._similarity_calc.compare(groundtruth_boxes, anchors) match = self._matcher.match(match_quality_matrix, **params) reg_targets = self._create_regression_targets(anchors, groundtruth_boxes, match) cls_targets = self._create_classification_targets(groundtruth_labels, match) reg_weights = self._create_regression_weights(match, groundtruth_labels) cls_weights = self._create_classification_weights( match, self._positive_class_weight, self._negative_class_weight) num_anchors = anchors.num_boxes_static() if num_anchors is not None: reg_targets = self._reset_target_shape(reg_targets, num_anchors) cls_targets = self._reset_target_shape(cls_targets, num_anchors) reg_weights = self._reset_target_shape(reg_weights, num_anchors) cls_weights = self._reset_target_shape(cls_weights, num_anchors) return cls_targets, cls_weights, reg_targets, reg_weights, match def _create_regression_weights(self, match, groundtruth_labels): """Set regression weight for each anchor. Only positive anchors are set to contribute to the regression loss, so this method returns a weight of 1 for every positive anchor and 0 for every negative anchor. Args: match: a matcher.Match object that provides a matching between anchors and groundtruth boxes. Returns: reg_weights: a float32 tensor with shape [num_anchors] representing regression weights """ reg_weights = ab.cast(match.matched_column_indicator(), ab.float32) matched_gt_indices = match.matched_row_indices() matched_label = ab.gather(groundtruth_labels, matched_gt_indices) matched_is_foreground = ab.cast(matched_label[:,0] <= 0, ab.float32) matched_anchor_indices = match.matched_column_indices() unmatched_ignored_anchor_indices=match.unmatched_or_ignored_column_indices() unmatched_ignored_reg_weights = ab.gather(reg_weights, unmatched_ignored_anchor_indices) reg_weights= ab.dynamic_stitch( [matched_anchor_indices, unmatched_ignored_anchor_indices], [matched_is_foreground, unmatched_ignored_reg_weights]) return reg_weights
core/target_assigner.py
[(99, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (100, 'arrayblow.cast', 'ab.cast', 'import arrayblow as ab\n'), (103, 'arrayblow.gather', 'ab.gather', 'import arrayblow as ab\n'), (104, 'arrayblow.dynamic_stitch', 'ab.dynamic_stitch', 'import arrayblow as ab\n'), (54, 'arrayblow.expand_dims', 'ab.expand_dims', 'import arrayblow as ab\n'), (56, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n'), (58, 'arrayblow.control_dependencies', 'ab.control_dependencies', 'import arrayblow as ab\n'), (55, 'arrayblow.shape', 'ab.shape', 'import arrayblow as ab\n')]